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    *      https://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  package org.apache.commons.lang3;
18  
19  import java.util.Objects;
20  import java.util.Random;
21  
22  /**
23   * Generates random integers of specific bit length.
24   *
25   * <p>
26   * It is more efficient than calling Random.nextInt(1 << nbBits). It uses a cache of cacheSize random bytes that it replenishes when it gets empty. This is
27   * especially beneficial for SecureRandom Drbg implementations, which incur a constant cost at each randomness generation.
28   * </p>
29   *
30   * <p>
31   * Used internally by RandomStringUtils.
32   * </p>
33   *
34   * <p>
35   * #NotThreadSafe#
36   * </p>
37   */
38  final class CachedRandomBits {
39  
40      /**
41       * The maximum size of the cache.
42       *
43       * <p>
44       * This is to prevent the possibility of overflow in the {@code if (bitIndex >> 3 >= cache.length)} in the {@link #nextBits(int)} method.
45       * </p>
46       */
47      private static final int MAX_CACHE_SIZE = Integer.MAX_VALUE >> 3;
48  
49      /** Maximum number of bits that can be generated (size of an int) */
50      private static final int MAX_BITS = 32;
51  
52      /** Mask to extract the bit offset within a byte (0-7) */
53      private static final int BIT_INDEX_MASK = 0x7;
54  
55      /** Number of bits in a byte */
56      private static final int BITS_PER_BYTE = 8;
57      private final Random random;
58      private final byte[] cache;
59  
60      /**
61       * Index of the next bit in the cache to be used.
62       *
63       * <ul>
64       * <li>bitIndex=0 means the cache is fully random and none of the bits have been used yet.</li>
65       * <li>bitIndex=1 means that only the LSB of cache[0] has been used and all other bits can be used.</li>
66       * <li>bitIndex=8 means that only the 8 bits of cache[0] has been used.</li>
67       * </ul>
68       */
69      private int bitIndex;
70  
71      /**
72       * Creates a new instance.
73       *
74       * @param cacheSize number of bytes cached (only affects performance)
75       * @param random random source
76       */
77      CachedRandomBits(final int cacheSize, final Random random) {
78          if (cacheSize <= 0) {
79              throw new IllegalArgumentException("cacheSize must be positive");
80          }
81          this.cache = cacheSize <= MAX_CACHE_SIZE ? new byte[cacheSize] : new byte[MAX_CACHE_SIZE];
82          this.random = Objects.requireNonNull(random, "random");
83          this.random.nextBytes(this.cache);
84          this.bitIndex = 0;
85      }
86  
87      /**
88       * Generates a random integer with the specified number of bits.
89       *
90       * <p>
91       * This method efficiently generates random bits by using a byte cache and bit manipulation:
92       * <ul>
93       *   <li>Uses a byte array cache to avoid frequent calls to the underlying random number generator</li>
94       *   <li>Extracts bits from each byte using bit shifting and masking</li>
95       *   <li>Handles partial bytes to avoid wasting random bits</li>
96       *   <li>Accumulates bits until the requested number is reached</li>
97       * </ul>
98       * </p>
99       *
100      * @param bits number of bits to generate, MUST be between 1 and 32 (inclusive)
101      * @return random integer containing exactly the requested number of random bits
102      * @throws IllegalArgumentException Thrown if bits is not between 1 and 32.
103      */
104     public int nextBits(final int bits) {
105         if (bits > MAX_BITS || bits <= 0) {
106             throw new IllegalArgumentException("number of bits must be between 1 and " + MAX_BITS);
107         }
108         int result = 0;
109         int generatedBits = 0; // number of generated bits up to now
110         while (generatedBits < bits) {
111             // Check if we need to refill the cache
112             // Convert bitIndex to byte index by dividing by 8 (right shift by 3)
113             if (bitIndex >> 3 >= cache.length) {
114                 // We exhausted the number of bits in the cache
115                 // This should only happen if the bitIndex is exactly matching the cache length
116                 assert bitIndex == cache.length * BITS_PER_BYTE;
117                 random.nextBytes(cache);
118                 bitIndex = 0;
119             }
120             // Calculate how many bits we can extract from the current byte
121             // 1. Get current position within byte (0-7) using bitIndex & 0x7
122             // 2. Calculate remaining bits in byte: 8 - (position within byte)
123             // 3. Take minimum of remaining bits in byte and bits still needed
124             final int generatedBitsInIteration = Math.min(
125                 BITS_PER_BYTE - (bitIndex & BIT_INDEX_MASK),
126                 bits - generatedBits);
127             // Shift existing result left to make room for new bits
128             result = result << generatedBitsInIteration;
129             // Extract and append new bits:
130             // 1. Get byte from cache (bitIndex >> 3 converts bit index to byte index)
131             // 2. Shift right by bit position within byte (bitIndex & 0x7)
132             // 3. Mask to keep only the bits we want ((1 << generatedBitsInIteration) - 1)
133             result |= cache[bitIndex >> 3] >> (bitIndex & BIT_INDEX_MASK) & (1 << generatedBitsInIteration) - 1;
134             // Update counters
135             generatedBits += generatedBitsInIteration;
136             bitIndex += generatedBitsInIteration;
137         }
138         return result;
139     }
140 }