src/java.base/share/classes/java/util/random/AbstractArbitrarilyJumpableRNG.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) 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 ArbitrarilyJumpableRNG} interface, to minimize the effort
 * required to implement that interface.
 *
 * 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 copy()},
 * {@code jump(distance)}, {@code jumpPowerOfTwo(distance)},
 * {@code defaultJumpDistance()}, and {@code defaultLeapDistance()}.
 *
 * (If the pseudorandom number generator also has the ability to split,
 * then the programmer may wish to consider instead extending
 * {@link AbstractSplittableRNG}.)
 *
 * 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.
 *
 * For the stream methods (such as {@code ints()} and {@code splits()}),
 * this class provides {@link Spliterator}-based implementations that
 * allow parallel execution when appropriate.  In this respect
 * {@link ArbitrarilyJumpableRNG} differs from {@link JumpableRNG},
 * which provides very simple implementations that produce
 * sequential streams only.
 *
 * <p>An implementation of the {@link AbstractArbitrarilyJumpableRNG} class
 * must provide concrete definitions for the methods {@code nextInt()},
 * {@code nextLong}, {@code period()}, {@code copy()}, {@code jump(double)},
 * {@code defaultJumpDistance()}, and {@code defaultLeapDistance()}.
 * Default implementations are provided for all other methods.
 *
 * 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 AbstractArbitrarilyJumpableRNG
    extends AbstractSpliteratorRNG implements ArbitrarilyJumpableRNG {

    /*
     * Implementation Overview.
     *
     * This class provides most of the "user API" methods needed to satisfy
     * the interface ArbitrarilyJumpableRNG.  Most of these methods
     * are in turn inherited from AbstractRNG and the non-public class
     * AbstractSpliteratorRNG; this file implements four versions of the
     * jumps method and defines the spliterators necessary to support them.
     *
     * File organization: First the non-public methods needed by the class
     * AbstractSpliteratorRNG, then the main public methods, followed by some
     * custom spliterator classes needed for stream methods.
     */

    // IllegalArgumentException messages
    static final String BadLogDistance  = "logDistance must be non-negative";

    // Methods required by class AbstractSpliteratorRNG
    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);
    }

    // Similar methods used by this class
    Spliterator<RandomNumberGenerator> makeJumpsSpliterator(long index, long fence, double distance) {
        return new RandomJumpsSpliterator(this, index, fence, distance);
    }
    Spliterator<JumpableRNG> makeLeapsSpliterator(long index, long fence, double distance) {
        return new RandomLeapsSpliterator(this, index, fence, distance);
    }
    Spliterator<ArbitrarilyJumpableRNG> makeArbitraryJumpsSpliterator(long index, long fence, double distance) {
        return new RandomArbitraryJumpsSpliterator(this, index, fence, distance);
    }

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

    /**
     * Returns a new generator whose internal state is an exact copy
     * of this generator (therefore their future behavior should be
     * identical if subjected to the same series of operations).
     *
     * @return a new object that is a copy of this generator
     */
    public abstract AbstractArbitrarilyJumpableRNG copy();

    // Stream methods for jumping

    private static <T> Stream<T> stream(Spliterator<T> srng) {
        return StreamSupport.stream(srng, false);
    }

    /**
     * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
     * implements the {@link RandomNumberGenerator} interface, produced by jumping copies of this
     * generator by different integer multiples of the default jump distance.
     *
     * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
     *
     * @implNote This method is implemented to be equivalent to {@code
     *         jumps(Long.MAX_VALUE)}.
     */
    public Stream<RandomNumberGenerator> jumps() {
        return stream(makeJumpsSpliterator(0L, Long.MAX_VALUE, defaultJumpDistance()));
    }

    /**
     * Returns a stream producing the given {@code streamSize} number of
     * new pseudorandom number generators, each of which implements the
     * {@link RandomNumberGenerator} interface, produced by jumping copies of this generator
     * by different integer multiples of the default jump distance.
     *
     * @param streamSize the number of generators to generate
     *
     * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
     *
     * @throws IllegalArgumentException if {@code streamSize} is less than zero
     */
    public Stream<RandomNumberGenerator> jumps(long streamSize) {
        RNGSupport.checkStreamSize(streamSize);
        return stream(makeJumpsSpliterator(0L, streamSize, defaultJumpDistance()));
    }

    /**
     * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
     * implements the {@link RandomNumberGenerator} interface, produced by jumping copies of this
     * generator by different integer multiples of the specified jump distance.
     *
     * @param distance a distance to jump forward within the state cycle
     *
     * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
     *
     * @implNote This method is implemented to be equivalent to {@code
     *         jumps(Long.MAX_VALUE)}.
     */
    public Stream<ArbitrarilyJumpableRNG> jumps(double distance) {
        return stream(makeArbitraryJumpsSpliterator(0L, Long.MAX_VALUE, distance));
    }

    /**
     * Returns a stream producing the given {@code streamSize} number of new pseudorandom number
     * generators, each of which implements the {@link RandomNumberGenerator} interface, produced by
     * jumping copies of this generator by different integer multiples of the specified jump
     * distance.
     *
     * @param streamSize the number of generators to generate
     * @param distance   a distance to jump forward within the state cycle
     *
     * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
     *
     * @throws IllegalArgumentException if {@code streamSize} is less than zero
     */
    public Stream<ArbitrarilyJumpableRNG> jumps(long streamSize, double distance) {
        RNGSupport.checkStreamSize(streamSize);
        return stream(makeArbitraryJumpsSpliterator(0L, streamSize, distance));
    }

    /**
     * Alter the state of this pseudorandom number generator so as to
     * jump forward a very large, fixed distance (typically 2<sup>128</sup>
     * or more) within its state cycle.  The distance used is that
     * returned by method {@code defaultLeapDistance()}.
     */
    public void leap() {
        jump(defaultLeapDistance());
    }

    // Stream methods for leaping

    /**
     * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
     * implements the {@link RandomNumberGenerator} interface, produced by jumping copies of this
     * generator by different integer multiples of the default leap distance.
     *
     * @implNote This method is implemented to be equivalent to {@code leaps(Long.MAX_VALUE)}.
     *
     * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
     */
    public Stream<JumpableRNG> leaps() {
        return stream(makeLeapsSpliterator(0L, Long.MAX_VALUE, defaultLeapDistance()));
    }

    /**
     * Returns a stream producing the given {@code streamSize} number of new pseudorandom number
     * generators, each of which implements the {@link RandomNumberGenerator} interface, produced by
     * jumping copies of this generator by different integer multiples of the default leap
     * distance.
     *
     * @param streamSize the number of generators to generate
     *
     * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
     *
     * @throws IllegalArgumentException if {@code streamSize} is less than zero
     */
    public Stream<JumpableRNG> leaps(long streamSize) {
        return stream(makeLeapsSpliterator(0L, streamSize, defaultLeapDistance()));
    }


    /**
     * 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, we choose to override the method {@code trySplit()} to
     * try to optimize execution speed: instead of dividing a range in half, it breaks off the
     * largest possible chunk whose size is a power of two such that the remaining chunk is not
     * empty. In this way, the necessary jump distances will tend to be powers of two.  The long
     * and double versions of this class are identical except for types.
     */
    static class RandomIntsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator.OfInt {
        final ArbitrarilyJumpableRNG generatingRNG;
        final int origin;
        final int bound;

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

        public Spliterator.OfInt trySplit() {
            long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
            if (m <= i) return null;
            index = m;
            ArbitrarilyJumpableRNG r = generatingRNG;
            return new RandomIntsSpliterator(r.copyAndJump((double)delta), 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;
                ArbitrarilyJumpableRNG 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 ArbitrarilyJumpableRNG generatingRNG;
        final long origin;
        final long bound;

        RandomLongsSpliterator(ArbitrarilyJumpableRNG 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, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
            if (m <= i) return null;
            index = m;
            ArbitrarilyJumpableRNG r = generatingRNG;
            return new RandomLongsSpliterator(r.copyAndJump((double)delta), 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;
                ArbitrarilyJumpableRNG 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 ArbitrarilyJumpableRNG generatingRNG;
        final double origin;
        final double bound;

        RandomDoublesSpliterator(ArbitrarilyJumpableRNG 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, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
            if (m <= i) return null;
            index = m;
            ArbitrarilyJumpableRNG r = generatingRNG;
            return new RandomDoublesSpliterator(r.copyAndJump((double)delta), 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;
                ArbitrarilyJumpableRNG r = generatingRNG;
                double o = origin, b = bound;
                do {
                    consumer.accept(RNGSupport.boundedNextDouble(r, o, b));
                } while (++i < f);
            }
        }
    }

    // Spliterators for producing new generators by jumping or leaping.  The
    // complete implementation of each of these spliterators is right here.
    // In the same manner as for the preceding spliterators, the method trySplit() is
    // coded to optimize execution speed: instead of dividing a range
    // in half, it breaks off the largest possible chunk whose
    // size is a power of two such that the remaining chunk is not
    // empty.  In this way, the necessary jump distances will tend to be
    // powers of two.

    /**
     * Spliterator for stream of generators of type RandomNumberGenerator produced by jumps.
     */
    static class RandomJumpsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator<RandomNumberGenerator> {
        ArbitrarilyJumpableRNG generatingRNG;
        final double distance;

        RandomJumpsSpliterator(ArbitrarilyJumpableRNG generatingRNG, long index, long fence, double distance) {
            super(index, fence);
            this.generatingRNG = generatingRNG; this.distance = distance;
        }

        public Spliterator<RandomNumberGenerator> trySplit() {
            long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
            if (m <= i) return null;
            index = m;
            ArbitrarilyJumpableRNG r = generatingRNG;
            // Because delta is a power of two, (distance * (double)delta) can always be computed exactly.
            return new RandomJumpsSpliterator(r.copyAndJump(distance * (double)delta), i, m, distance);
        }

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

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

    /**
     * Spliterator for stream of generators of type RandomNumberGenerator produced by leaps.
     */
    static class RandomLeapsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator<JumpableRNG> {
        ArbitrarilyJumpableRNG generatingRNG;
        final double distance;

        RandomLeapsSpliterator(ArbitrarilyJumpableRNG generatingRNG, long index, long fence, double distance) {
            super(index, fence);
            this.generatingRNG = generatingRNG; this.distance = distance;
        }

        public Spliterator<JumpableRNG> trySplit() {
            long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
            if (m <= i) return null;
            index = m;
            // Because delta is a power of two, (distance * (double)delta) can always be computed exactly.
            return new RandomLeapsSpliterator(generatingRNG.copyAndJump(distance * (double)delta), i, m, distance);
        }

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

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

    /**
     * Spliterator for stream of generators of type RandomNumberGenerator produced by arbitrary jumps.
     */
    static class RandomArbitraryJumpsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator<ArbitrarilyJumpableRNG> {
        ArbitrarilyJumpableRNG generatingRNG;
        final double distance;

        RandomArbitraryJumpsSpliterator(ArbitrarilyJumpableRNG generatingRNG, long index, long fence, double distance) {
            super(index, fence);
            this.generatingRNG = generatingRNG; this.distance = distance;
        }

        public Spliterator<ArbitrarilyJumpableRNG> trySplit() {
            long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
            if (m <= i) return null;
            index = m;
            // Because delta is a power of two, (distance * (double)delta) can always be computed exactly.
            return new RandomArbitraryJumpsSpliterator(generatingRNG.copyAndJump(distance * (double)delta), i, m, distance);
        }

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

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

}