View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.rng.core.source64;
19  
20  import org.apache.commons.rng.JumpableUniformRandomProvider;
21  import org.apache.commons.rng.LongJumpableUniformRandomProvider;
22  import org.apache.commons.rng.UniformRandomProvider;
23  import org.apache.commons.rng.core.util.NumberFactory;
24  
25  /**
26   * This abstract class is a base for algorithms from the Xor-Shift-Rotate family of 64-bit
27   * generators with 128-bits of state.
28   *
29   * @see <a href="http://xoshiro.di.unimi.it/">xorshiro / xoroshiro generators</a>
30   * @since 1.3
31   */
32  abstract class AbstractXoRoShiRo128 extends LongProvider implements LongJumpableUniformRandomProvider {
33      /** Size of the state vector. */
34      private static final int SEED_SIZE = 2;
35      /** The coefficients for the jump function. */
36      private static final long[] JUMP_COEFFICIENTS = {
37          0xdf900294d8f554a5L, 0x170865df4b3201fcL
38      };
39      /** The coefficients for the long jump function. */
40      private static final long[] LONG_JUMP_COEFFICIENTS = {
41          0xd2a98b26625eee7bL, 0xdddf9b1090aa7ac1L
42      };
43  
44      // State is maintained using variables rather than an array for performance
45  
46      /** State 0 of the generator. */
47      protected long state0;
48      /** State 1 of the generator. */
49      protected long state1;
50  
51      /**
52       * Creates a new instance.
53       *
54       * @param seed Initial seed.
55       * If the length is larger than 2, only the first 2 elements will
56       * be used; if smaller, the remaining elements will be automatically
57       * set. A seed containing all zeros will create a non-functional generator.
58       */
59      AbstractXoRoShiRo128(long[] seed) {
60          if (seed.length < SEED_SIZE) {
61              final long[] state = new long[SEED_SIZE];
62              fillState(state, seed);
63              setState(state);
64          } else {
65              setState(seed);
66          }
67      }
68  
69      /**
70       * Creates a new instance using a 2 element seed.
71       * A seed containing all zeros will create a non-functional generator.
72       *
73       * @param seed0 Initial seed element 0.
74       * @param seed1 Initial seed element 1.
75       */
76      AbstractXoRoShiRo128(long seed0, long seed1) {
77          state0 = seed0;
78          state1 = seed1;
79      }
80  
81      /**
82       * Creates a copy instance.
83       *
84       * @param source Source to copy.
85       */
86      protected AbstractXoRoShiRo128(AbstractXoRoShiRo128 source) {
87          super(source);
88          state0 = source.state0;
89          state1 = source.state1;
90      }
91  
92      /**
93       * Copies the state from the array into the generator state.
94       *
95       * @param state the new state
96       */
97      private void setState(long[] state) {
98          state0 = state[0];
99          state1 = state[1];
100     }
101 
102     /** {@inheritDoc} */
103     @Override
104     protected byte[] getStateInternal() {
105         return composeStateInternal(NumberFactory.makeByteArray(new long[] {state0, state1}),
106                                     super.getStateInternal());
107     }
108 
109     /** {@inheritDoc} */
110     @Override
111     protected void setStateInternal(byte[] s) {
112         final byte[][] c = splitStateInternal(s, SEED_SIZE * 8);
113 
114         setState(NumberFactory.makeLongArray(c[0]));
115 
116         super.setStateInternal(c[1]);
117     }
118 
119     /** {@inheritDoc} */
120     @Override
121     public long next() {
122         final long result = nextOutput();
123 
124         final long s0 = state0;
125         long s1 = state1;
126 
127         s1 ^= s0;
128         state0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b
129         state1 = Long.rotateLeft(s1, 37); // c
130 
131         return result;
132     }
133 
134     /**
135      * Use the current state to compute the next output from the generator.
136      * The output function shall vary with respect to different generators.
137      * This method is called from {@link #next()} before the current state is updated.
138      *
139      * @return the next output
140      */
141     protected abstract long nextOutput();
142 
143     /**
144      * {@inheritDoc}
145      *
146      * <p>The jump size is the equivalent of 2<sup>64</sup>
147      * calls to {@link UniformRandomProvider#nextLong() nextLong()}. It can provide
148      * up to 2<sup>64</sup> non-overlapping subsequences.</p>
149      */
150     @Override
151     public UniformRandomProvider jump() {
152         final UniformRandomProvider copy = copy();
153         performJump(JUMP_COEFFICIENTS);
154         return copy;
155     }
156 
157     /**
158      * {@inheritDoc}
159      *
160      * <p>The jump size is the equivalent of 2<sup>96</sup> calls to
161      * {@link UniformRandomProvider#nextLong() nextLong()}. It can provide up to
162      * 2<sup>32</sup> non-overlapping subsequences of length 2<sup>96</sup>; each
163      * subsequence can provide up to 2<sup>32</sup> non-overlapping subsequences of
164      * length 2<sup>64</sup> using the {@link #jump()} method.</p>
165      */
166     @Override
167     public JumpableUniformRandomProvider longJump() {
168         final JumpableUniformRandomProvider copy = copy();
169         performJump(LONG_JUMP_COEFFICIENTS);
170         return copy;
171     }
172 
173     /**
174      * Create a copy.
175      *
176      * @return the copy
177      */
178     protected abstract AbstractXoRoShiRo128 copy();
179 
180     /**
181      * Perform the jump to advance the generator state. Resets the cached state of the generator.
182      *
183      * @param jumpCoefficients Jump coefficients.
184      */
185     final void performJump(long[] jumpCoefficients) {
186         long s0 = 0;
187         long s1 = 0;
188         for (final long jc : jumpCoefficients) {
189             for (int b = 0; b < 64; b++) {
190                 if ((jc & (1L << b)) != 0) {
191                     s0 ^= state0;
192                     s1 ^= state1;
193                 }
194                 next();
195             }
196         }
197         state0 = s0;
198         state1 = s1;
199         resetCachedState();
200     }
201 }