Skip to content
Myr

index.js

This file

Path

index.js

177 lines · 6.1 KiB · JavaScript

Last changed by

Fix non-integer size in customRandom() (#616)lostsignalsbefore adoption0b2cec5

History of this file

Take it

The walk stopped after 200 commits: lines older than cdc3edc point at it.

Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f

line 1why, one step back
1import { urlAlphabet } from './url-alphabet/index.js'

Update size limitAndrey Sitnikbefore adoptioncdc3edc

line 2why, one step back
2

Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f

line 3why, one step back
3export { urlAlphabet }

Update size limitAndrey Sitnikbefore adoptioncdc3edc

line 4why, one step back
4

Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f

lines 5–7why, one step back
5// `crypto.getRandomValues` rejects requests over 65536 bytes,
6// so bigger buffers are filled by chunks.7const GET_RANDOM_LIMIT = 65536

Update size limitAndrey Sitnikbefore adoptioncdc3edc

line 8why, one step back
8

Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f

lines 9–14why, one step back
9function fillRandom(buffer) {
10 let from = 011 while (from < buffer.length) {12 let to = Math.min(from + GET_RANDOM_LIMIT, buffer.length)13 crypto.getRandomValues(buffer.subarray(from, to))14 from = to

Update size limitAndrey Sitnikbefore adoptioncdc3edc

lines 15–18why, one step back
15 }
16}1718export function random(bytes) {

Fix comment 80 columsn limit (#585)Andrey Sitnikbefore adoption94953df

line 19why, one step back
19 // `|=` convert `bytes` to number to prevent `valueOf` abusing

Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f

lines 20–26why, one step back
20 bytes |= 0
21 if (bytes < 0) throw new RangeError('Wrong ID size')22 // `random()` is used rarely and not in hot paths, so it makes23 // a direct crypto call instead of using a byte pool.24 let buffer = Buffer.allocUnsafe(bytes)25 fillRandom(buffer)26 return buffer

Update size limitAndrey Sitnikbefore adoptioncdc3edc

lines 27–29why, one step back
27}
2829export function customRandom(alphabet, defaultSize, getRandom) {

Improve comments (#583)Andrey Sitnikbefore adoptiond3030b7

lines 30–31why, one step back
30 // Random bytes are 0-255. `random % alphabet.length` can waste
31 // that entropy by making some symbols more likely.

Use full byte range in customAlphabet (+ ~75% ops / sec optimisation) (#582)Denis Saripovbefore adoptione1acf37

line 32why, one step back
32 //

Improve comments (#583)Andrey Sitnikbefore adoptiond3030b7

lines 33–35why, one step back
33 // `safeByteCutoff` will be divided by `alphabet.length` without remainder
34 // fixing issue of broken distribution.35 //

Use full byte range in customAlphabet (+ ~75% ops / sec optimisation) (#582)Denis Saripovbefore adoptione1acf37

lines 36–40why, one step back
36 // Example: with 17 symbols, `safeByteCutoff` is 255.
37 // Bytes 0-254 preserve entropy evenly: each symbol gets 15 source bytes.38 // Byte 255 would map to `0` again, making one symbol slightly more likely.39 // So we reject 255.40 let safeByteCutoff = 256 - (256 % alphabet.length)

Update size limitAndrey Sitnikbefore adoptioncdc3edc

line 41why, one step back
41

Use full byte range in customAlphabet (+ ~75% ops / sec optimisation) (#582)Denis Saripovbefore adoptione1acf37

lines 42–44why, one step back
42 // Power-of-two alphabets can use `& mask` instead of modulo.
43 if (safeByteCutoff === 256) {44 let mask = alphabet.length - 1

Update size limitAndrey Sitnikbefore adoptioncdc3edc

line 45why, one step back
45

Use full byte range in customAlphabet (+ ~75% ops / sec optimisation) (#582)Denis Saripovbefore adoptione1acf37

lines 46–49why, one step back
46 return (size = defaultSize) => {
47 if (!size) return ''48 let id = ''49 while (true) {

Improve comments (#583)Andrey Sitnikbefore adoptiond3030b7

line 50why, one step back
50 let bytes = getRandom(size)

Use full byte range in customAlphabet (+ ~75% ops / sec optimisation) (#582)Denis Saripovbefore adoptione1acf37

line 51why, one step back
51 // A compact alternative for `for (let i = 0; i < step; i++)`.

Fix non-integer size in customRandom() (#616)lostsignalsbefore adoption0b2cec5

lines 52–53why, one step back
52 // `|=` convert `size` to integer, so it can be used as a byte index
53 let i = (size |= 0)

Use full byte range in customAlphabet (+ ~75% ops / sec optimisation) (#582)Denis Saripovbefore adoptione1acf37

lines 54–61why, one step back
54 while (i--) {
55 // Here, `& mask` is equivalent to `% alphabet.length`, but faster56 id += alphabet[bytes[i] & mask]57 if (id.length >= size) return id58 }59 }60 }61 }

Update size limitAndrey Sitnikbefore adoptioncdc3edc

lines 62–63why, one step back
62
63 return (size = defaultSize) => {

Normalize behaviourAndrey Sitnikbefore adoption464d36b

line 64why, one step back
64 if (!size) return ''

Update size limitAndrey Sitnikbefore adoptioncdc3edc

line 65why, one step back
65 let id = ''

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

lines 66–72why, one step back
66 // Secure random calls are expensive because system calls
67 // for entropy collection take time. To avoid extra calls,68 // extra bytes are requested in advance to cover rejections.69 //70 // `step` determines how many random bytes to request.71 // `1.6` is a magic number chosen from benchmarks.72 let step = Math.ceil((1.6 * 256 * size) / safeByteCutoff)

Update size limitAndrey Sitnikbefore adoptioncdc3edc

lines 73–77why, one step back
73 while (true) {
74 let bytes = getRandom(step)75 // A compact alternative for `for (let i = 0; i < step; i++)`.76 let i = step77 while (i--) {

Use full byte range in customAlphabet (+ ~75% ops / sec optimisation) (#582)Denis Saripovbefore adoptione1acf37

lines 78–83why, one step back
78 // Reject bytes >= `safeByteCutoff` to avoid modulo bias
79 // and give each symbol an equal chance.80 if (bytes[i] < safeByteCutoff) {81 id += alphabet[bytes[i] % alphabet.length]82 if (id.length >= size) return id83 }

Update size limitAndrey Sitnikbefore adoptioncdc3edc

lines 84–88why, one step back
84 }
85 }86 }87}88

Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f

lines 89–91why, one step back
89// The string pool optimizations in `customAlphabet()` and `nanoid()`
90// were ported from the nope-id project by Orhan Aydoğdu:91// https://github.com/orhanayd/nope-id

Update size limitAndrey Sitnikbefore adoptioncdc3edc

line 92why, one step back
92

Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f

lines 93–94why, one step back
93// Maximum size of the pre-generated string pool in `customAlphabet()`.
94const POOL_MAX = GET_RANDOM_LIMIT / 2

Improve comments (#583)Andrey Sitnikbefore adoptiond3030b7

line 95why, one step back
95

Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f

lines 96–98why, one step back
96export function customAlphabet(alphabet, defaultSize = 21) {
97 if (98 typeof alphabet !== 'string' ||

simplify (#603)Dimitri POSTOLOVbefore adoption41aceb1

line 99why, one step back
99 !alphabet ||

Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f

lines 100–102why, one step back
100 alphabet.length > 256
101 ) {102 return customRandom(alphabet, defaultSize, random)

Update size limitAndrey Sitnikbefore adoptioncdc3edc

line 103why, one step back
103 }

Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f

lines 104–174why, one step back
104 for (let i = 0; i < alphabet.length; i++) {
105 if (alphabet.charCodeAt(i) > 255) {106 // The fast path below writes char codes to a byte buffer,107 // so it supports only single-byte characters.108 return customRandom(alphabet, defaultSize, random)109 }110 }111112 // Alphabet char codes to write IDs into a byte buffer directly.113 let charCodes = Uint8Array.from(alphabet, str => {114 return str.charCodeAt(0)115 })116 let alphabetLen = alphabet.length117 // The smallest `2^n - 1` covering all alphabet indexes. Rejecting118 // `byte & mask >= alphabetLen` avoids modulo bias without `%` operation.119 let mask = (2 << (31 - Math.clz32((alphabetLen - 1) | 1))) - 1120121 // IDs are pre-generated into a string pool: accepted alphabet chars are122 // written to a byte buffer, converted to a string with one123 // `Buffer#toString()` call, and every ID is a cheap `String#substring()`.124 // It avoids per-character string concatenations and pays string125 // allocation cost once per refill.126 //127 // The pool starts at the first requested size and grows geometrically,128 // so short-living generators do not pay for a full pool.129 let pool = ''130 let poolOffset = 0131 let poolNext = 0132133 return (size = defaultSize) => {134 // `|=` convert `size` to number to prevent `valueOf` abusing135 // and pool offset pollution136 size |= 0137 if (size < 0) throw new RangeError('Wrong ID size')138 if (size === 0) return ''139 if (poolOffset + size > pool.length) {140 let target = Math.max(poolNext, size)141 poolNext = Math.min(target * 16, POOL_MAX)142 let buffer = Buffer.allocUnsafe(target)143 if (mask === alphabetLen - 1) {144 // Power-of-two alphabets like `urlAlphabet` accept every byte,145 // so random bytes are translated in place without rejections.146 fillRandom(buffer)147 for (let i = 0; i < target; i++) {148 buffer[i] = charCodes[buffer[i] & mask]149 }150 } else {151 // Rejection sampling accepts `alphabetLen` of every `mask + 1`152 // random bytes. `1.6` requests extra bytes to cover153 // unlucky streaks in most fills.154 let randomBytes = Buffer.allocUnsafe(155 Math.ceil((1.6 * (mask + 1) * target) / alphabetLen)156 )157 let accepted = 0158 while (accepted < target) {159 fillRandom(randomBytes)160 for (let i = 0; i < randomBytes.length; i++) {161 let index = randomBytes[i] & mask162 if (index < alphabetLen) {163 buffer[accepted++] = charCodes[index]164 if (accepted === target) break165 }166 }167 }168 }169 pool = buffer.toString('latin1')170 poolOffset = 0171 }172 poolOffset += size173 return pool.substring(poolOffset - size, poolOffset)174 }

Update size limitAndrey Sitnikbefore adoptioncdc3edc

line 175why, one step back
175}

Port amazing nope-id optimizations (#602)Andrey Sitnikbefore adoptionb1bb75f

lines 176–177why, one step back
176
177export const nanoid = customAlphabet(urlAlphabet)