index.js 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 = 128
  9. let pool, poolOffset
  10. let fillPool = 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. poolOffset += bytes
  20. }
  21. let random = bytes => {
  22. // `|=` convert `bytes` to number to prevent `valueOf` abusing and pool pollution
  23. fillPool((bytes |= 0))
  24. return pool.subarray(poolOffset - bytes, poolOffset)
  25. }
  26. let customRandom = (alphabet, defaultSize, getRandom) => {
  27. // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
  28. // values closer to the alphabet size. The bitmask calculates the closest
  29. // `2^31 - 1` number, which exceeds the alphabet size.
  30. // For example, the bitmask for the alphabet size 30 is 31 (00011111).
  31. let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
  32. // Though, the bitmask solution is not perfect since the bytes exceeding
  33. // the alphabet size are refused. Therefore, to reliably generate the ID,
  34. // the random bytes redundancy has to be satisfied.
  35. // Note: every hardware random generator call is performance expensive,
  36. // because the system call for entropy collection takes a lot of time.
  37. // So, to avoid additional system calls, extra bytes are requested in advance.
  38. // Next, a step determines how many random bytes to generate.
  39. // The number of random bytes gets decided upon the ID size, mask,
  40. // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
  41. // according to benchmarks).
  42. let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
  43. return (size = defaultSize) => {
  44. let id = ''
  45. while (true) {
  46. let bytes = getRandom(step)
  47. // A compact alternative for `for (let i = 0; i < step; i++)`.
  48. let i = step
  49. while (i--) {
  50. // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
  51. id += alphabet[bytes[i] & mask] || ''
  52. if (id.length === size) return id
  53. }
  54. }
  55. }
  56. }
  57. let customAlphabet = (alphabet, size = 21) =>
  58. customRandom(alphabet, size, random)
  59. let nanoid = (size = 21) => {
  60. // `|=` convert `size` to number to prevent `valueOf` abusing and pool pollution
  61. fillPool((size |= 0))
  62. let id = ''
  63. // We are reading directly from the random pool to avoid creating new array
  64. for (let i = poolOffset - size; i < poolOffset; i++) {
  65. // It is incorrect to use bytes exceeding the alphabet size.
  66. // The following mask reduces the random byte in the 0-255 value
  67. // range to the 0-63 value range. Therefore, adding hacks, such
  68. // as empty string fallback or magic numbers, is unneccessary because
  69. // the bitmask trims bytes down to the alphabet size.
  70. id += urlAlphabet[pool[i] & 63]
  71. }
  72. return id
  73. }
  74. export { nanoid, customAlphabet, customRandom, urlAlphabet, random }