src/java.base/share/classes/java/util/random/AbstractSplittableRNG.java
author jlaskey
Thu, 27 Jun 2019 18:30:27 -0300
branchJDK-8193209-branch
changeset 57437 f02ffcb61dce
parent 57436 b0c958c0e6c6
permissions -rw-r--r--
Rename Rng.java to RandomNumberGenerator.java, clean up javadoc and misc code changes

/*
 * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package java.util.random;

import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * This class provides much of the implementation of the {@link SplittableRNG} interface, to
 * minimize the effort required to implement this interface.
 * <p>
 * To implement a pseudorandom number generator, the programmer needs only to extend this class and
 * provide implementations for the methods {@code nextInt()}, {@code nextLong()}, {@code period()},
 * and {@code split(SplittableRNG)}.
 * <p>
 * (If the pseudorandom number generator also has the ability to jump, then the programmer may wish
 * to consider instead extending the class {@link ArbitrarilyJumpableRNG}.  But if the pseudorandom
 * number generator furthermore has the ability to jump an arbitrary specified distance, then the
 * programmer may wish to consider instead extending the class {@link
 * AbstractArbitrarilyJumpableRNG}.)
 * <p>
 * The programmer should generally provide at least three constructors: one that takes no arguments,
 * one that accepts a {@code long} seed value, and one that accepts an array of seed {@code byte}
 * values. This class provides a public {@code initialSeed()} method that may be useful in
 * initializing some static state from which to derive defaults seeds for use by the no-argument
 * constructor.
 * <p>
 * For the stream methods (such as {@code ints()} and {@code splits()}), this class provides {@link
 * Spliterator} based implementations that allow parallel execution when appropriate.
 * <p>
 * The documentation for each non-abstract method in this class describes its implementation in
 * detail. Each of these methods may be overridden if the pseudorandom number generator being
 * implemented admits a more efficient implementation.
 *
 * @since 14
 */
public abstract class AbstractSplittableRNG extends AbstractSpliteratorRNG implements SplittableRNG {

    /*
     * Implementation Overview.
     *
     * This class provides most of the "user API" methods needed to
     * satisfy the interface JumpableRNG.  Most of these methods
     * are in turn inherited from AbstractRNG and the non-public class
     * AbstractSpliteratorRNG; this file implements two versions of the
     * splits method and defines the spliterators necessary to support
     * them.
     *
     * The abstract split() method from interface SplittableRNG is redeclared
     * here so as to narrow the return type to AbstractSplittableRNG.
     *
     * File organization: First the non-public methods needed by the class
     * AbstractSpliteratorRNG, then the main public methods, followed by some
     * custom spliterator classes.
     */

    Spliterator.OfInt makeIntsSpliterator(long index, long fence, int origin, int bound) {
        return new RandomIntsSpliterator(this, index, fence, origin, bound);
    }

    Spliterator.OfLong makeLongsSpliterator(long index, long fence, long origin, long bound) {
        return new RandomLongsSpliterator(this, index, fence, origin, bound);
    }

    Spliterator.OfDouble makeDoublesSpliterator(long index, long fence, double origin, double bound) {
        return new RandomDoublesSpliterator(this, index, fence, origin, bound);
    }

    Spliterator<SplittableRNG> makeSplitsSpliterator(long index, long fence, SplittableRNG source) {
        return new RandomSplitsSpliterator(source, index, fence, this);
    }

    /* ---------------- public methods ---------------- */

    /**
     * Implements the @code{split()} method as {@code this.split(this) }.
     *
     * @return the new {@link AbstractSplittableRNG} instance
     */
    public SplittableRNG split() {
        return this.split(this);
    }

    // Stream methods for splittings

    /**
     * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
     * implements the {@link SplittableRNG} interface.
     * <p>
     * This pseudorandom number generator provides the entropy used to seed the new ones.
     *
     * @return a stream of {@link SplittableRNG} objects
     *
     * @implNote This method is implemented to be equivalent to {@code splits(Long.MAX_VALUE)}.
     */
    public Stream<SplittableRNG> splits() {
        return this.splits(Long.MAX_VALUE, this);
    }

    /**
     * Returns a stream producing the given {@code streamSize} number of new pseudorandom number
     * generators, each of which implements the {@link SplittableRNG} interface.
     * <p>
     * This pseudorandom number generator provides the entropy used to seed the new ones.
     *
     * @param streamSize the number of values to generate
     *
     * @return a stream of {@link SplittableRNG} objects
     *
     * @throws IllegalArgumentException if {@code streamSize} is less than zero
     */
    public Stream<SplittableRNG> splits(long streamSize) {
        return this.splits(streamSize, this);
    }

    /**
     * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
     * implements the {@link SplittableRNG} interface.
     *
     * @param source a {@link SplittableRNG} instance to be used instead of this one as a source of
     *               pseudorandom bits used to initialize the state of the new ones.
     *
     * @return a stream of {@link SplittableRNG} objects
     *
     * @implNote This method is implemented to be equivalent to {@code splits(Long.MAX_VALUE)}.
     */
    public Stream<SplittableRNG> splits(SplittableRNG source) {
        return this.splits(Long.MAX_VALUE, source);
    }

    /**
     * Returns a stream producing the given {@code streamSize} number of new pseudorandom number
     * generators, each of which implements the {@link SplittableRNG} interface.
     *
     * @param streamSize the number of values to generate
     * @param source     a {@link SplittableRNG} instance to be used instead of this one as a source
     *                   of pseudorandom bits used to initialize the state of the new ones.
     *
     * @return a stream of {@link SplittableRNG} objects
     *
     * @throws IllegalArgumentException if {@code streamSize} is less than zero
     */
    public Stream<SplittableRNG> splits(long streamSize, SplittableRNG source) {
        RNGSupport.checkStreamSize(streamSize);
        return StreamSupport.stream(makeSplitsSpliterator(0L, streamSize, source), false);
    }

    /**
     * Spliterator for int streams.  We multiplex the four int versions into one class by treating a
     * bound less than origin as unbounded, and also by treating "infinite" as equivalent to
     * {@code Long.MAX_VALUE}. For splits, it uses the standard divide-by-two approach. The long and
     * double versions of this class are identical except for types.
     */
    static class RandomIntsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator.OfInt {
        final SplittableRNG generatingRNG;
        final int origin;
        final int bound;

        RandomIntsSpliterator(SplittableRNG generatingRNG, long index, long fence, int origin, int bound) {
            super(index, fence);
            this.generatingRNG = generatingRNG;
            this.origin = origin; this.bound = bound;
        }

        public Spliterator.OfInt trySplit() {
            long i = index, m = (i + fence) >>> 1;
            if (m <= i) return null;
            index = m;
            return new RandomIntsSpliterator(generatingRNG.split(), i, m, origin, bound);
        }

        public boolean tryAdvance(IntConsumer consumer) {
            if (consumer == null) throw new NullPointerException();
            long i = index, f = fence;
            if (i < f) {
                consumer.accept(RNGSupport.boundedNextInt(generatingRNG, origin, bound));
                index = i + 1;
                return true;
            }
            else return false;
        }

        public void forEachRemaining(IntConsumer consumer) {
            if (consumer == null) throw new NullPointerException();
            long i = index, f = fence;
            if (i < f) {
                index = f;
                RandomNumberGenerator r = generatingRNG;
                int o = origin, b = bound;
                do {
                    consumer.accept(RNGSupport.boundedNextInt(r, o, b));
                } while (++i < f);
            }
        }
    }

    /**
     * Spliterator for long streams.
     */
    static class RandomLongsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator.OfLong {
        final SplittableRNG generatingRNG;
        final long origin;
        final long bound;

        RandomLongsSpliterator(SplittableRNG generatingRNG, long index, long fence, long origin, long bound) {
            super(index, fence);
            this.generatingRNG = generatingRNG;
            this.origin = origin; this.bound = bound;
        }

        public Spliterator.OfLong trySplit() {
            long i = index, m = (i + fence) >>> 1;
            if (m <= i) return null;
            index = m;
            return new RandomLongsSpliterator(generatingRNG.split(), i, m, origin, bound);
        }

        public boolean tryAdvance(LongConsumer consumer) {
            if (consumer == null) throw new NullPointerException();
            long i = index, f = fence;
            if (i < f) {
                consumer.accept(RNGSupport.boundedNextLong(generatingRNG, origin, bound));
                index = i + 1;
                return true;
            }
            else return false;
        }

        public void forEachRemaining(LongConsumer consumer) {
            if (consumer == null) throw new NullPointerException();
            long i = index, f = fence;
            if (i < f) {
                index = f;
                RandomNumberGenerator r = generatingRNG;
                long o = origin, b = bound;
                do {
                    consumer.accept(RNGSupport.boundedNextLong(r, o, b));
                } while (++i < f);
            }
        }
    }

    /**
     * Spliterator for double streams.
     */
    static class RandomDoublesSpliterator extends RNGSupport.RandomSpliterator implements Spliterator.OfDouble {
        final SplittableRNG generatingRNG;
        final double origin;
        final double bound;

        RandomDoublesSpliterator(SplittableRNG generatingRNG, long index, long fence, double origin, double bound) {
            super(index, fence);
            this.generatingRNG = generatingRNG;
            this.origin = origin; this.bound = bound;
        }

        public Spliterator.OfDouble trySplit() {
            long i = index, m = (i + fence) >>> 1;
            if (m <= i) return null;
            index = m;
            return new RandomDoublesSpliterator(generatingRNG.split(), i, m, origin, bound);
        }

        public boolean tryAdvance(DoubleConsumer consumer) {
            if (consumer == null) throw new NullPointerException();
            long i = index, f = fence;
            if (i < f) {
                consumer.accept(RNGSupport.boundedNextDouble(generatingRNG, origin, bound));
                index = i + 1;
                return true;
            }
            else return false;
        }

        public void forEachRemaining(DoubleConsumer consumer) {
            if (consumer == null) throw new NullPointerException();
            long i = index, f = fence;
            if (i < f) {
                index = f;
                RandomNumberGenerator r = generatingRNG;
                double o = origin, b = bound;
                do {
                    consumer.accept(RNGSupport.boundedNextDouble(r, o, b));
                } while (++i < f);
            }
        }
    }

    /**
     * Spliterator for stream of generators of type SplittableRNG.  We multiplex the two
     * versions into one class by treating "infinite" as equivalent to Long.MAX_VALUE.
     * For splits, it uses the standard divide-by-two approach.
     */
    static class RandomSplitsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator<SplittableRNG> {
        final SplittableRNG generatingRNG;
        final SplittableRNG constructingRNG;

        RandomSplitsSpliterator(SplittableRNG generatingRNG, long index, long fence, SplittableRNG constructingRNG) {
            super(index, fence);
            this.generatingRNG = generatingRNG;
            this.constructingRNG = constructingRNG;
        }

        public Spliterator<SplittableRNG> trySplit() {
            long i = index, m = (i + fence) >>> 1;
            if (m <= i) return null;
            index = m;
            return new RandomSplitsSpliterator(generatingRNG.split(), i, m, constructingRNG);
        }

        public boolean tryAdvance(Consumer<? super SplittableRNG> consumer) {
            if (consumer == null) throw new NullPointerException();
            long i = index, f = fence;
            if (i < f) {
                consumer.accept(constructingRNG.split(generatingRNG));
                index = i + 1;
                return true;
            }
            else return false;
        }

        public void forEachRemaining(Consumer<? super SplittableRNG> consumer) {
            if (consumer == null) throw new NullPointerException();
            long i = index, f = fence;
            if (i < f) {
                index = f;
                SplittableRNG c = constructingRNG;
                SplittableRNG r = generatingRNG;
                do {
                    consumer.accept(c.split(r));
                } while (++i < f);
            }
        }
    }

}