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.source32;
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 32-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 AbstractXoShiRo128 extends IntProvider implements LongJumpableUniformRandomProvider {
33      /** Size of the state vector. */
34      private static final int SEED_SIZE = 4;
35      /** The coefficients for the jump function. */
36      private static final int[] JUMP_COEFFICIENTS = {
37          0x8764000b, 0xf542d2d3, 0x6fa035c3, 0x77f2db5b
38      };
39      /** The coefficients for the long jump function. */
40      private static final int[] LONG_JUMP_COEFFICIENTS = {
41          0xb523952e, 0x0b6f099f, 0xccf5a0ef, 0x1c580662
42      };
43  
44      // State is maintained using variables rather than an array for performance
45  
46      /** State 0 of the generator. */
47      protected int state0;
48      /** State 1 of the generator. */
49      protected int state1;
50      /** State 2 of the generator. */
51      protected int state2;
52      /** State 3 of the generator. */
53      protected int state3;
54  
55      /**
56       * Creates a new instance.
57       *
58       * @param seed Initial seed.
59       * If the length is larger than 4, only the first 4 elements will
60       * be used; if smaller, the remaining elements will be automatically
61       * set. A seed containing all zeros will create a non-functional generator.
62       */
63      AbstractXoShiRo128(int[] seed) {
64          if (seed.length < SEED_SIZE) {
65              final int[] state = new int[SEED_SIZE];
66              fillState(state, seed);
67              setState(state);
68          } else {
69              setState(seed);
70          }
71      }
72  
73      /**
74       * Creates a new instance using a 4 element seed.
75       * A seed containing all zeros will create a non-functional generator.
76       *
77       * @param seed0 Initial seed element 0.
78       * @param seed1 Initial seed element 1.
79       * @param seed2 Initial seed element 2.
80       * @param seed3 Initial seed element 3.
81       */
82      AbstractXoShiRo128(int seed0, int seed1, int seed2, int seed3) {
83          state0 = seed0;
84          state1 = seed1;
85          state2 = seed2;
86          state3 = seed3;
87      }
88  
89      /**
90       * Creates a copy instance.
91       *
92       * @param source Source to copy.
93       */
94      protected AbstractXoShiRo128(AbstractXoShiRo128 source) {
95          super(source);
96          state0 = source.state0;
97          state1 = source.state1;
98          state2 = source.state2;
99          state3 = source.state3;
100     }
101 
102     /**
103      * Copies the state from the array into the generator state.
104      *
105      * @param state the new state
106      */
107     private void setState(int[] state) {
108         state0 = state[0];
109         state1 = state[1];
110         state2 = state[2];
111         state3 = state[3];
112     }
113 
114     /** {@inheritDoc} */
115     @Override
116     protected byte[] getStateInternal() {
117         return composeStateInternal(NumberFactory.makeByteArray(
118                                         new int[] {state0, state1, state2, state3}),
119                                     super.getStateInternal());
120     }
121 
122     /** {@inheritDoc} */
123     @Override
124     protected void setStateInternal(byte[] s) {
125         final byte[][] c = splitStateInternal(s, SEED_SIZE * 4);
126 
127         setState(NumberFactory.makeIntArray(c[0]));
128 
129         super.setStateInternal(c[1]);
130     }
131 
132     /** {@inheritDoc} */
133     @Override
134     public int next() {
135         final int result = nextOutput();
136 
137         final int t = state1 << 9;
138 
139         state2 ^= state0;
140         state3 ^= state1;
141         state1 ^= state2;
142         state0 ^= state3;
143 
144         state2 ^= t;
145 
146         state3 = Integer.rotateLeft(state3, 11);
147 
148         return result;
149     }
150 
151     /**
152      * Use the current state to compute the next output from the generator.
153      * The output function shall vary with respect to different generators.
154      * This method is called from {@link #next()} before the current state is updated.
155      *
156      * @return the next output
157      */
158     protected abstract int nextOutput();
159 
160     /**
161      * {@inheritDoc}
162      *
163      * <p>The jump size is the equivalent of 2<sup>64</sup>
164      * calls to {@link UniformRandomProvider#nextInt() nextInt()}. It can provide
165      * up to 2<sup>64</sup> non-overlapping subsequences.</p>
166      */
167     @Override
168     public UniformRandomProvider jump() {
169         final UniformRandomProvider copy = copy();
170         performJump(JUMP_COEFFICIENTS);
171         return copy;
172     }
173 
174     /**
175      * {@inheritDoc}
176      *
177      * <p>The jump size is the equivalent of 2<sup>96</sup> calls to
178      * {@link UniformRandomProvider#nextLong() nextLong()}. It can provide up to
179      * 2<sup>32</sup> non-overlapping subsequences of length 2<sup>96</sup>; each
180      * subsequence can provide up to 2<sup>32</sup> non-overlapping subsequences of
181      * length 2<sup>64</sup> using the {@link #jump()} method.</p>
182      */
183     @Override
184     public JumpableUniformRandomProvider longJump() {
185         final JumpableUniformRandomProvider copy = copy();
186         performJump(LONG_JUMP_COEFFICIENTS);
187         return copy;
188     }
189 
190     /**
191      * Create a copy.
192      *
193      * @return the copy
194      */
195     protected abstract AbstractXoShiRo128 copy();
196 
197     /**
198      * Perform the jump to advance the generator state. Resets the cached state of the generator.
199      *
200      * @param jumpCoefficients Jump coefficients.
201      */
202     private void performJump(int[] jumpCoefficients) {
203         int s0 = 0;
204         int s1 = 0;
205         int s2 = 0;
206         int s3 = 0;
207         for (final int jc : jumpCoefficients) {
208             for (int b = 0; b < 32; b++) {
209                 if ((jc & (1 << b)) != 0) {
210                     s0 ^= state0;
211                     s1 ^= state1;
212                     s2 ^= state2;
213                     s3 ^= state3;
214                 }
215                 next();
216             }
217         }
218         state0 = s0;
219         state1 = s1;
220         state2 = s2;
221         state3 = s3;
222         resetCachedState();
223     }
224 }