( min: number, max: number, halfOpen: boolean, draw: () => Uint8Array )
| 135 | // Draws an integer by rejection sampling over 53-bit (or, for ranges wider than |
| 136 | // 2^53, 54-bit) draws, so every integer in the range has the same probability. |
| 137 | const intBetweenUnsafe = ( |
| 138 | min: number, |
| 139 | max: number, |
| 140 | halfOpen: boolean, |
| 141 | draw: () => Uint8Array |
| 142 | ): number => { |
| 143 | const minInt = Math.ceil(min) |
| 144 | const maxInt = Math.floor(max) |
| 145 | if (!Number.isSafeInteger(minInt) || !Number.isSafeInteger(maxInt)) { |
| 146 | throw new RangeError("bounds must round to safe integers") |
| 147 | } |
| 148 | if (maxInt - minInt < Number.MAX_SAFE_INTEGER) { |
| 149 | // Every intermediate stays below 2^53, and `%` is exact, so the divisions |
| 150 | // below are exact without BigInt. |
| 151 | const count = maxInt - minInt + (halfOpen ? 0 : 1) |
| 152 | if (count <= 0) { |
| 153 | throw new RangeError("range must contain at least one integer") |
| 154 | } |
| 155 | // `+ 0` turns `Math.ceil` of a value in (-1, 0) into 0 instead of -0. |
| 156 | if (count === 1) return minInt + 0 |
| 157 | const bucketSize = (2 ** 53 - (2 ** 53 % count)) / count |
| 158 | const limit = bucketSize * count |
| 159 | while (true) { |
| 160 | const value = readUint53(draw()) |
| 161 | if (value < limit) return minInt + (value - (value % bucketSize)) / bucketSize |
| 162 | } |
| 163 | } |
| 164 | // BigInt keeps every integer distinct when the range is wider than 2^53. |
| 165 | const lower = BigInt(minInt) |
| 166 | const count = BigInt(maxInt) - lower + (halfOpen ? BigInt(0) : BigInt(1)) |
| 167 | const wide = count > BigInt(1) << BigInt(53) |
| 168 | const bucketSize = (wide ? BigInt(1) << BigInt(54) : BigInt(1) << BigInt(53)) / count |
| 169 | const limit = bucketSize * count |
| 170 | while (true) { |
| 171 | const bytes = draw() |
| 172 | const value = BigInt(readUint53(bytes)) + (wide && (bytes[0] & 0x20) !== 0 ? BigInt(1) << BigInt(53) : BigInt(0)) |
| 173 | if (value < limit) return Number(lower + value / bucketSize) |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | const makeUuid = ( |
| 178 | bytes: (randomBytes: Uint8Array) => Uint8Array, |
no test coverage detected