Use full byte range in customAlphabet (+ ~75% ops / sec optimisation) (#582)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Use full byte range in customAlphabet * Add comment to clarify bitmask usage for power-of-two alphabets in customRandom * Optimise customRandom function to avoid unneccesary if check at runtime * Update customAlphabet limit in package.json to 193 B * Document safeByteCutoff and mask usage in customRandom
authored by Denis Saripov · committed by GitHub · parent f4e7fbe · Browse files · 4 files·+88 added−49 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+88 added−49 removed
- tests:+5 added−2 removed
- other:+83 added−47 removed
Provenance
- Commit
e1acf37- Tree
100706f- Author
Denis Saripov <74184888+saripovdenis@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
f4e7fbe
4 files changed+88 added−49 removed
modified:test/index.test.js+5 added-2 removed
139 unmodified lines140 141 test(`${type} / customAlphabet / is ready for 0 size`, () => {142 equal(customAlphabet('abc')(0), '')143 equal(customAlphabet('abc', 0)(0), '')144+ equal(customAlphabet('')(0), '')145+ equal(customAlphabet('', 0)(0), '')146 })147 148 test(`${type} / customAlphabet / avoids pool pollution, infinite loop`, () => {149 let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'14 unmodified lines164 return bytes165 }166 let nanoid4 = customRandom('abcde', 4, fakeRandom)167 let nanoid18 = customRandom('abcde', 18, fakeRandom)166- equal(nanoid4(), 'adca')167- equal(nanoid18(), 'cbadcbadcbadcbadcc')168+ equal(nanoid4(), 'cccc')169+ equal(nanoid18(), 'acccccdcbacccccdcb')170 })171 172 test(`${type} / customRandom / is ready for 0 size`, () => {173 let nanoid0 = customRandom('abc', 5, size => new Uint8Array(size))174 equal(nanoid0(0), '')175+ equal(customRandom('', 5, size => new Uint8Array(size))(0), '')176 })177 178 test(`${type} / urlAlphabet / is string`, () => {179 equal(typeof urlAlphabet, 'string')70 unmodified linesmodified:index.browser.js+41 added-25 removed
8 unmodified lines910111213141516171819202113141516171819202122232425262728293023242531323334272829303536373839404142434445464748495032333435515253545556575844454647485960616263646566676815 unmodified lines8 unmodified lines
export let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
export let customRandom = (alphabet, defaultSize, getRandom) => { // First, a bitmask is necessary to generate the ID. The bitmask makes bytes // values closer to the alphabet size. The bitmask calculates the closest // `2^31 - 1` number, which exceeds the alphabet size. // For example, the bitmask for the alphabet size 30 is 31 (00011111). // `Math.clz32` is not used, because it is not available in browsers. let mask = (2 << Math.log2(alphabet.length - 1)) - 1 // Though, the bitmask solution is not perfect since the bytes exceeding // the alphabet size are refused. Therefore, to reliably generate the ID, // the random bytes redundancy has to be satisfied. // Random bytes are 0-255 and already have full entropy. // `% alphabet.length` can waste that entropy by making some symbols more likely. // `safeByteCutoff` is the exclusive upper bound for unbiased bytes. // Bytes below it are safe. Bytes at or above it are rejected. // // Example: with 17 symbols, `safeByteCutoff` is 255. // Bytes 0-254 preserve entropy evenly: each symbol gets 15 source bytes. // Byte 255 would map to `0` again, making one symbol slightly more likely. // So we reject 255. let safeByteCutoff = 256 - (256 % alphabet.length) // Note: secure random calls are expensive because system calls for entropy collection take time. // To avoid extra calls, extra bytes are requested in advance to cover rejections. // // `step` determines how many random bytes to request. // It depends on ID size and the share of safe bytes (`safeByteCutoff / 256`). // `1.6` is a magic number chosen from benchmarks. let step = Math.ceil((1.6 * 256 * defaultSize) / safeByteCutoff)
// Note: every hardware random generator call is performance expensive, // because the system call for entropy collection takes a lot of time. // So, to avoid additional system calls, extra bytes are requested in advance. // Power-of-two alphabets can use `& mask` instead of modulo. if (safeByteCutoff === 256) { let mask = alphabet.length - 1
// Next, a step determines how many random bytes to generate. // The number of random bytes gets decided upon the ID size, mask, // alphabet size, and magic number 1.6 (using 1.6 peaks at performance // according to benchmarks). return (size = defaultSize) => { if (!size) return '' let id = '' while (true) { let bytes = getRandom(step) // A compact alternative for `for (var i = 0; i < step; i++)`. let j = step while (j--) { // Here, `& mask` is equivalent to `% alphabet.length`, but faster id += alphabet[bytes[j] & mask] if (id.length >= size) return id } } } }
// `-~f => Math.ceil(f)` if f is a float // `-~i => i + 1` if i is an integer let step = -~((1.6 * mask * defaultSize) / alphabet.length)
return (size = defaultSize) => { if (!size) return '' let id = '' while (true) { let bytes = getRandom(step) // A compact alternative for `for (var i = 0; i < step; i++)`. let j = step while (j--) { let next = alphabet[bytes[j] & mask] // Adding `continue` refuses a random byte that exceeds the alphabet size. if (!next) continue id += next if (id.length >= size) return id // Reject bytes >= `safeByteCutoff` to avoid modulo bias // and give each symbol an equal chance. if (bytes[j] < safeByteCutoff) { id += alphabet[bytes[j] % alphabet.length] if (id.length >= size) return id } } } }}15 unmodified linesmodified:index.js+41 added-21 removed
29 unmodified lines30313233343536373839404134353637383940414243444546474849505143444552535455474849505156575859606162636465666768697071727374757677787961626364658081828384858687888920 unmodified lines29 unmodified lines return pool.subarray(poolOffset - bytes, poolOffset)}
export function customRandom(alphabet, defaultSize, getRandom) { // First, a bitmask is necessary to generate the ID. The bitmask makes bytes // values closer to the alphabet size. The bitmask calculates the closest // `2^31 - 1` number, which exceeds the alphabet size. // For example, the bitmask for the alphabet size 30 is 31 (00011111). let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 // Though, the bitmask solution is not perfect since the bytes exceeding // the alphabet size are refused. Therefore, to reliably generate the ID, // the random bytes redundancy has to be satisfied. // Random bytes are 0-255 and already have full entropy. // `% alphabet.length` can waste that entropy by making some symbols more likely. // `safeByteCutoff` is the exclusive upper bound for unbiased bytes. // Bytes below it are safe. Bytes at or above it are rejected. // // Example: with 17 symbols, `safeByteCutoff` is 255. // Bytes 0-254 preserve entropy evenly: each symbol gets 15 source bytes. // Byte 255 would map to `0` again, making one symbol slightly more likely. // So we reject 255. let safeByteCutoff = 256 - (256 % alphabet.length) // Note: secure random calls are expensive because system calls for entropy collection take time. // To avoid extra calls, extra bytes are requested in advance to cover rejections. // // `step` determines how many random bytes to request. // It depends on ID size and the share of safe bytes (`safeByteCutoff / 256`). // `1.6` is a magic number chosen from benchmarks. let step = Math.ceil((1.6 * 256 * defaultSize) / safeByteCutoff)
// Note: every hardware random generator call is performance expensive, // because the system call for entropy collection takes a lot of time. // So, to avoid additional system calls, extra bytes are requested in advance. // Power-of-two alphabets can use `& mask` instead of modulo. if (safeByteCutoff === 256) { let mask = alphabet.length - 1
// Next, a step determines how many random bytes to generate. // The number of random bytes gets decided upon the ID size, mask, // alphabet size, and magic number 1.6 (using 1.6 peaks at performance // according to benchmarks). let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) return (size = defaultSize) => { if (!size) return '' let id = '' while (true) { let bytes = getRandom(step) // A compact alternative for `for (let i = 0; i < step; i++)`. let i = step while (i--) { // Here, `& mask` is equivalent to `% alphabet.length`, but faster id += alphabet[bytes[i] & mask] if (id.length >= size) return id } } } }
return (size = defaultSize) => { if (!size) return '' let id = '' while (true) { let bytes = getRandom(step) // A compact alternative for `for (let i = 0; i < step; i++)`. let i = step while (i--) { let next = alphabet[bytes[i] & mask] // Adding `continue` refuses a random byte that exceeds the alphabet size. if (!next) continue id += next if (id.length >= size) return id // Reject bytes >= `safeByteCutoff` to avoid modulo bias // and give each symbol an equal chance. if (bytes[i] < safeByteCutoff) { id += alphabet[bytes[i] % alphabet.length] if (id.length >= size) return id } } } }}20 unmodified linesmodified:package.json+1 added-1 removed
86 unmodified lines87 },88 {89 "name": "customAlphabet",90 "import": "{ customAlphabet }",91- "limit": "178 B"91+ "limit": "193 B"92 },93 {94 "name": "urlAlphabet",95 "import": "{ urlAlphabet }",32 unmodified lines