1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- import crypto from 'crypto'
- import { urlAlphabet } from './url-alphabet/index.js'
- const POOL_SIZE_MULTIPLIER = 32
- let pool, poolOffset
- let random = bytes => {
- if (!pool || pool.length < bytes) {
- pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
- crypto.randomFillSync(pool)
- poolOffset = 0
- } else if (poolOffset + bytes > pool.length) {
- crypto.randomFillSync(pool)
- poolOffset = 0
- }
- let res = pool.subarray(poolOffset, poolOffset + bytes)
- poolOffset += bytes
- return res
- }
- let customRandom = (alphabet, size, getRandom) => {
-
-
-
-
- let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
-
-
-
-
-
-
-
-
-
-
- let step = Math.ceil((1.6 * mask * size) / alphabet.length)
- return () => {
- let id = ''
- while (true) {
- let bytes = getRandom(step)
-
- let i = step
- while (i--) {
-
- id += alphabet[bytes[i] & mask] || ''
- if (id.length === size) return id
- }
- }
- }
- }
- let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random)
- let nanoid = (size = 21) => {
- let bytes = random(size)
- let id = ''
-
- while (size--) {
-
-
-
-
-
- id += urlAlphabet[bytes[size] & 63]
- }
- return id
- }
- export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
|