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       * Index of the next bit in the cache to be used.
61       *
62       * <ul>
63       * <li>bitIndex=0 means the cache is fully random and none of the bits have been used yet.</li>
64       * <li>bitIndex=1 means that only the LSB of cache[0] has been used and all other bits can be used.</li>
65       * <li>bitIndex=8 means that only the 8 bits of cache[0] has been used.</li>
66       * </ul>
67       */
68      private int bitIndex;
69      /**
70       * Creates a new instance.
71       *
72       * @param cacheSize number of bytes cached (only affects performance)
73       * @param random random source
74       */
75      CachedRandomBits(final int cacheSize, final Random random) {
76          if (cacheSize <= 0) {
77              throw new IllegalArgumentException("cacheSize must be positive");
78          }
79          this.cache = cacheSize <= MAX_CACHE_SIZE ? new byte[cacheSize] : new byte[MAX_CACHE_SIZE];
80          this.random = Objects.requireNonNull(random, "random");
81          this.random.nextBytes(this.cache);
82          this.bitIndex = 0;
83      }
84  
85      /**
86       * Generates a random integer with the specified number of bits.
87       *
88       * <p>This method efficiently generates random bits by using a byte cache and bit manipulation:
89       * <ul>
90       *   <li>Uses a byte array cache to avoid frequent calls to the underlying random number generator</li>
91       *   <li>Extracts bits from each byte using bit shifting and masking</li>
92       *   <li>Handles partial bytes to avoid wasting random bits</li>
93       *   <li>Accumulates bits until the requested number is reached</li>
94       * </ul>
95       * </p>
96       *
97       * @param bits number of bits to generate, MUST be between 1 and 32 (inclusive)
98       * @return random integer containing exactly the requested number of random bits
99       * @throws IllegalArgumentException if bits is not between 1 and 32
100      */
101     public int nextBits(final int bits) {
102         if (bits > MAX_BITS || bits <= 0) {
103             throw new IllegalArgumentException("number of bits must be between 1 and " + MAX_BITS);
104         }
105         int result = 0;
106         int generatedBits = 0; // number of generated bits up to now
107         while (generatedBits < bits) {
108             // Check if we need to refill the cache
109             // Convert bitIndex to byte index by dividing by 8 (right shift by 3)
110             if (bitIndex >> 3 >= cache.length) {
111                 // We exhausted the number of bits in the cache
112                 // This should only happen if the bitIndex is exactly matching the cache length
113                 assert bitIndex == cache.length * BITS_PER_BYTE;
114                 random.nextBytes(cache);
115                 bitIndex = 0;
116             }
117             // Calculate how many bits we can extract from the current byte
118             // 1. Get current position within byte (0-7) using bitIndex & 0x7
119             // 2. Calculate remaining bits in byte: 8 - (position within byte)
120             // 3. Take minimum of remaining bits in byte and bits still needed
121             final int generatedBitsInIteration = Math.min(
122                 BITS_PER_BYTE - (bitIndex & BIT_INDEX_MASK),
123                 bits - generatedBits);
124             // Shift existing result left to make room for new bits
125             result = result << generatedBitsInIteration;
126             // Extract and append new bits:
127             // 1. Get byte from cache (bitIndex >> 3 converts bit index to byte index)
128             // 2. Shift right by bit position within byte (bitIndex & 0x7)
129             // 3. Mask to keep only the bits we want ((1 << generatedBitsInIteration) - 1)
130             result |= cache[bitIndex >> 3] >> (bitIndex & BIT_INDEX_MASK) & ((1 << generatedBitsInIteration) - 1);
131             // Update counters
132             generatedBits += generatedBitsInIteration;
133             bitIndex += generatedBitsInIteration;
134         }
135         return result;
136     }
137 }