index.js 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import crypto from 'crypto'
  2. import { urlAlphabet } from './url-alphabet/index.js'
  3. // It is best to make fewer, larger requests to the crypto module to
  4. // avoid system call overhead. So, random numbers are generated in a
  5. // pool. The pool is a Buffer that is larger than the initial random
  6. // request size by this multiplier. The pool is enlarged if subsequent
  7. // requests exceed the maximum buffer size.
  8. const POOL_SIZE_MULTIPLIER = 32
  9. let pool, poolOffset
  10. let random = bytes => {
  11. if (!pool || pool.length < bytes) {
  12. pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
  13. crypto.randomFillSync(pool)
  14. poolOffset = 0
  15. } else if (poolOffset + bytes > pool.length) {
  16. crypto.randomFillSync(pool)
  17. poolOffset = 0
  18. }
  19. let res = pool.subarray(poolOffset, poolOffset + bytes)
  20. poolOffset += bytes
  21. return res
  22. }
  23. let customRandom = (alphabet, size, getRandom) => {
  24. // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
  25. // values closer to the alphabet size. The bitmask calculates the closest
  26. // `2^31 - 1` number, which exceeds the alphabet size.
  27. // For example, the bitmask for the alphabet size 30 is 31 (00011111).
  28. let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
  29. // Though, the bitmask solution is not perfect since the bytes exceeding
  30. // the alphabet size are refused. Therefore, to reliably generate the ID,
  31. // the random bytes redundancy has to be satisfied.
  32. // Note: every hardware random generator call is performance expensive,
  33. // because the system call for entropy collection takes a lot of time.
  34. // So, to avoid additional system calls, extra bytes are requested in advance.
  35. // Next, a step determines how many random bytes to generate.
  36. // The number of random bytes gets decided upon the ID size, mask,
  37. // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
  38. // according to benchmarks).
  39. let step = Math.ceil((1.6 * mask * size) / alphabet.length)
  40. return () => {
  41. let id = ''
  42. while (true) {
  43. let bytes = getRandom(step)
  44. // A compact alternative for `for (let i = 0; i < step; i++)`.
  45. let i = step
  46. while (i--) {
  47. // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
  48. id += alphabet[bytes[i] & mask] || ''
  49. if (id.length === size) return id
  50. }
  51. }
  52. }
  53. }
  54. let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random)
  55. let nanoid = (size = 21) => {
  56. let bytes = random(size)
  57. let id = ''
  58. // A compact alternative for `for (let i = 0; i < size; i++)`.
  59. while (size--) {
  60. // It is incorrect to use bytes exceeding the alphabet size.
  61. // The following mask reduces the random byte in the 0-255 value
  62. // range to the 0-63 value range. Therefore, adding hacks, such
  63. // as empty string fallback or magic numbers, is unneccessary because
  64. // the bitmask trims bytes down to the alphabet size.
  65. id += urlAlphabet[bytes[size] & 63]
  66. }
  67. return id
  68. }
  69. export { nanoid, customAlphabet, customRandom, urlAlphabet, random }