Skip to content
Myr

fix: size customRandom's byte request from the ID length (#612)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix: size customRandom's byte request from the ID length A generator created with default size 0 never requested any entropy when later called with a positive size, so the rejection loop never terminated. * refactor: keep step comments next to the sized byte request

authored by 00200200 · committed by GitHub · parent ac313f9 · Browse files · 3 files+28 added−16 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+28 added−16 removed

  • tests:+14 added−0 removed
  • other:+14 added−16 removed

3 files+28 added−16 removed

modified:test/index.test.js+14 added
217 unmodified lines
218 equal(customAlphabet('')(0), '')219 equal(customAlphabet('', 0)(0), '')220 })221222 test(`does not hang when default size is 0`, { timeout: 2000 }, () => {223 let nanoid2 = customAlphabet('абв', 0)224 let id = nanoid2(8)225 equal(id.length, 8)226 for (let char of id) {227 ok('абв'.includes(char))228 }229 })230231 test(`avoids pool pollution, infinite loop`, () => {232 let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'233 let nanoid2 = customAlphabet(ALPHABET)234 nanoid2(2.1)
57 unmodified lines
292 equal(nanoid0(0), '')293 equal(customRandom('', 5, size => new Uint8Array(size))(0), '')294 })295296 test(`does not hang when default size is 0`, { timeout: 2000 }, () => {297 let nanoid0 = customRandom('abc', 0, size => new Uint8Array(size).fill(1))298 equal(nanoid0(8), 'bbbbbbbb')299 })300301 test(`supports power-of-two alphabets`, () => {302 let sequence = [2, 255, 3, 7]303 function fakeRandom(size) {304 let bytes = []
55 unmodified lines
modified:index.browser.js+7 added-8 removed
modified:index.js+7 added-8 removed
57 unmodified lines
58 }59 }60 }6162 // Secure random calls are expensive because system calls63 // for entropy collection take time. To avoid extra calls,64 // extra bytes are requested in advance to cover rejections.65 //66 // `step` determines how many random bytes to request.67 // `1.6` is a magic number chosen from benchmarks.68 let step = Math.ceil((1.6 * 256 * defaultSize) / safeByteCutoff)6962 return (size = defaultSize) => {63 if (!size) return ''64 let id = ''65 // Secure random calls are expensive because system calls66 // for entropy collection take time. To avoid extra calls,67 // extra bytes are requested in advance to cover rejections.68 //69 // `step` determines how many random bytes to request.70 // `1.6` is a magic number chosen from benchmarks.71 let step = Math.ceil((1.6 * 256 * size) / safeByteCutoff)72 while (true) {73 let bytes = getRandom(step)74 // A compact alternative for `for (let i = 0; i < step; i++)`.75 let i = step
101 unmodified lines