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;
19  
20  import org.apache.commons.rng.RestorableUniformRandomProvider;
21  import org.apache.commons.rng.RandomProviderState;
22  
23  /**
24   * Base class with default implementation for common methods.
25   */
26  public abstract class BaseProvider
27      implements RestorableUniformRandomProvider {
28      /** {@inheritDoc} */
29      @Override
30      public int nextInt(int n) {
31          checkStrictlyPositive(n);
32  
33          if ((n & -n) == n) {
34              return (int) ((n * (long) (nextInt() >>> 1)) >> 31);
35          }
36          int bits;
37          int val;
38          do {
39              bits = nextInt() >>> 1;
40              val = bits % n;
41          } while (bits - val + (n - 1) < 0);
42  
43          return val;
44      }
45  
46      /** {@inheritDoc} */
47      @Override
48      public long nextLong(long n) {
49          checkStrictlyPositive(n);
50  
51          long bits;
52          long val;
53          do {
54              bits = nextLong() >>> 1;
55              val  = bits % n;
56          } while (bits - val + (n - 1) < 0);
57  
58          return val;
59      }
60  
61      /** {@inheritDoc} */
62      @Override
63      public RandomProviderState saveState() {
64          return new RandomProviderDefaultState(getStateInternal());
65      }
66  
67      /** {@inheritDoc} */
68      @Override
69      public void restoreState(RandomProviderState state) {
70          if (state instanceof RandomProviderDefaultState) {
71              setStateInternal(((RandomProviderDefaultState) state).getState());
72          } else {
73              throw new IllegalArgumentException("Foreign instance");
74          }
75      }
76  
77      /** {@inheritDoc} */
78      @Override
79      public String toString() {
80          return getClass().getName();
81      }
82  
83      /**
84       * Creates a snapshot of the RNG state.
85       *
86       * @return the internal state.
87       * @throws UnsupportedOperationException if not implemented.
88       */
89      protected byte[] getStateInternal() {
90          throw new UnsupportedOperationException();
91      }
92  
93      /**
94       * Resets the RNG to the given {@code state}.
95       *
96       * @param state State (previously obtained by a call to
97       * {@link #getStateInternal()}).
98       * @throws UnsupportedOperationException if not implemented.
99       *
100      * @see #checkStateSize(byte[],int)
101      */
102     protected void setStateInternal(byte[] state) {
103         throw new UnsupportedOperationException();
104     }
105 
106     /**
107      * Simple filling procedure.
108      * It will
109      * <ol>
110      *  <li>
111      *   fill the beginning of {@code state} by copying
112      *   {@code min(seed.length, state.length)} elements from
113      *   {@code seed},
114      *  </li>
115      *  <li>
116      *   set all remaining elements of {@code state} with non-zero
117      *   values (even if {@code seed.length < state.length}).
118      *  </li>
119      * </ol>
120      *
121      * @param state State. Must be allocated.
122      * @param seed Seed. Cannot be null.
123      */
124     protected void fillState(int[] state,
125                              int[] seed) {
126         final int stateSize = state.length;
127         final int seedSize = seed.length;
128         System.arraycopy(seed, 0, state, 0, Math.min(seedSize, stateSize));
129 
130         if (seedSize < stateSize) {
131             for (int i = seedSize; i < stateSize; i++) {
132                 state[i] = (int) (scrambleWell(state[i - seed.length], i) & 0xffffffffL);
133             }
134         }
135     }
136 
137     /**
138      * Simple filling procedure.
139      * It will
140      * <ol>
141      *  <li>
142      *   fill the beginning of {@code state} by copying
143      *   {@code min(seed.length, state.length)} elements from
144      *   {@code seed},
145      *  </li>
146      *  <li>
147      *   set all remaining elements of {@code state} with non-zero
148      *   values (even if {@code seed.length < state.length}).
149      *  </li>
150      * </ol>
151      *
152      * @param state State. Must be allocated.
153      * @param seed Seed. Cannot be null.
154      */
155     protected void fillState(long[] state,
156                              long[] seed) {
157         final int stateSize = state.length;
158         final int seedSize = seed.length;
159         System.arraycopy(seed, 0, state, 0, Math.min(seedSize, stateSize));
160 
161         if (seedSize < stateSize) {
162             for (int i = seedSize; i < stateSize; i++) {
163                 state[i] = scrambleWell(state[i - seed.length], i);
164             }
165         }
166     }
167 
168     /**
169      * Checks that the {@code state} has the {@code expected} size.
170      *
171      * @param state State.
172      * @param expected Expected length of {@code state} array.
173      * @throws IllegalArgumentException if {@code state.length != expected}.
174      */
175     protected void checkStateSize(byte[] state,
176                                   int expected) {
177         if (state.length != expected) {
178             throw new IllegalArgumentException("State size must be " + expected +
179                                                " but was " + state.length);
180         }
181     }
182 
183     /**
184      * Checks whether {@code index} is in the range {@code [min, max]}.
185      *
186      * @param min Lower bound.
187      * @param max Upper bound.
188      * @param index Value that must lie within the {@code [min, max]} interval.
189      * @throws IndexOutOfBoundsException if {@code index} is not within the
190      * {@code [min, max]} interval.
191      */
192     protected void checkIndex(int min,
193                               int max,
194                               int index) {
195         if (index < min ||
196             index > max) {
197             throw new IndexOutOfBoundsException(index + " is out of interval [" +
198                                                 min + ", " +
199                                                 max + "]");
200         }
201     }
202 
203     /**
204      * Checks that the argument is strictly positive.
205      *
206      * @param n Number to check.
207      * @throws IllegalArgumentException if {@code n <= 0}.
208      */
209     private void checkStrictlyPositive(long n) {
210         if (n <= 0) {
211             throw new IllegalArgumentException("Must be strictly positive: " + n);
212         }
213     }
214 
215     /**
216      * Transformation used to scramble the initial state of
217      * a generator.
218      *
219      * @param n Seed element.
220      * @param mult Multiplier.
221      * @param shift Shift.
222      * @param add Offset.
223      * @return the transformed seed element.
224      */
225     private static long scramble(long n,
226                                  long mult,
227                                  int shift,
228                                  int add) {
229         // Code inspired from "AbstractWell" class.
230         return mult * (n ^ (n >> shift)) + add;
231     }
232 
233     /**
234      * Transformation used to scramble the initial state of
235      * a generator.
236      *
237      * @param n Seed element.
238      * @param add Offset.
239      * @return the transformed seed element.
240      * @see #scramble(long,long,int,int)
241      */
242     private static long scrambleWell(long n,
243                                      int add) {
244         // Code inspired from "AbstractWell" class.
245         return scramble(n, 1812433253L, 30, add);
246     }
247 }