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>This method efficiently generates random bits by using a byte cache and bit manipulation:
91 * <ul>
92 * <li>Uses a byte array cache to avoid frequent calls to the underlying random number generator</li>
93 * <li>Extracts bits from each byte using bit shifting and masking</li>
94 * <li>Handles partial bytes to avoid wasting random bits</li>
95 * <li>Accumulates bits until the requested number is reached</li>
96 * </ul>
97 * </p>
98 *
99 * @param bits number of bits to generate, MUST be between 1 and 32 (inclusive)
100 * @return random integer containing exactly the requested number of random bits
101 * @throws IllegalArgumentException if bits is not between 1 and 32
102 */
103 public int nextBits(final int bits) {
104 if (bits > MAX_BITS || bits <= 0) {
105 throw new IllegalArgumentException("number of bits must be between 1 and " + MAX_BITS);
106 }
107 int result = 0;
108 int generatedBits = 0; // number of generated bits up to now
109 while (generatedBits < bits) {
110 // Check if we need to refill the cache
111 // Convert bitIndex to byte index by dividing by 8 (right shift by 3)
112 if (bitIndex >> 3 >= cache.length) {
113 // We exhausted the number of bits in the cache
114 // This should only happen if the bitIndex is exactly matching the cache length
115 assert bitIndex == cache.length * BITS_PER_BYTE;
116 random.nextBytes(cache);
117 bitIndex = 0;
118 }
119 // Calculate how many bits we can extract from the current byte
120 // 1. Get current position within byte (0-7) using bitIndex & 0x7
121 // 2. Calculate remaining bits in byte: 8 - (position within byte)
122 // 3. Take minimum of remaining bits in byte and bits still needed
123 final int generatedBitsInIteration = Math.min(
124 BITS_PER_BYTE - (bitIndex & BIT_INDEX_MASK),
125 bits - generatedBits);
126 // Shift existing result left to make room for new bits
127 result = result << generatedBitsInIteration;
128 // Extract and append new bits:
129 // 1. Get byte from cache (bitIndex >> 3 converts bit index to byte index)
130 // 2. Shift right by bit position within byte (bitIndex & 0x7)
131 // 3. Mask to keep only the bits we want ((1 << generatedBitsInIteration) - 1)
132 result |= cache[bitIndex >> 3] >> (bitIndex & BIT_INDEX_MASK) & ((1 << generatedBitsInIteration) - 1);
133 // Update counters
134 generatedBits += generatedBitsInIteration;
135 bitIndex += generatedBitsInIteration;
136 }
137 return result;
138 }
139 }