index.native.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { getRandomBytesAsync } from 'expo-random'
  2. import { urlAlphabet } from '../url-alphabet/index.js'
  3. let random = getRandomBytesAsync
  4. let customAlphabet = (alphabet, size) => {
  5. // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
  6. // values closer to the alphabet size. The bitmask calculates the closest
  7. // `2^31 - 1` number, which exceeds the alphabet size.
  8. // For example, the bitmask for the alphabet size 30 is 31 (00011111).
  9. let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
  10. // Though, the bitmask solution is not perfect since the bytes exceeding
  11. // the alphabet size are refused. Therefore, to reliably generate the ID,
  12. // the random bytes redundancy has to be satisfied.
  13. // Note: every hardware random generator call is performance expensive,
  14. // because the system call for entropy collection takes a lot of time.
  15. // So, to avoid additional system calls, extra bytes are requested in advance.
  16. // Next, a step determines how many random bytes to generate.
  17. // The number of random bytes gets decided upon the ID size, mask,
  18. // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
  19. // according to benchmarks).
  20. let step = Math.ceil((1.6 * mask * size) / alphabet.length)
  21. let tick = id =>
  22. random(step).then(bytes => {
  23. // A compact alternative for `for (var i = 0; i < step; i++)`.
  24. let i = step
  25. while (i--) {
  26. // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
  27. id += alphabet[bytes[i] & mask] || ''
  28. if (id.length === size) return id
  29. }
  30. return tick(id)
  31. })
  32. return () => tick('')
  33. }
  34. let nanoid = (size = 21) =>
  35. random(size).then(bytes => {
  36. let id = ''
  37. // A compact alternative for `for (var i = 0; i < step; i++)`.
  38. while (size--) {
  39. // It is incorrect to use bytes exceeding the alphabet size.
  40. // The following mask reduces the random byte in the 0-255 value
  41. // range to the 0-63 value range. Therefore, adding hacks, such
  42. // as empty string fallback or magic numbers, is unneccessary because
  43. // the bitmask trims bytes down to the alphabet size.
  44. id += urlAlphabet[bytes[size] & 63]
  45. }
  46. return id
  47. })
  48. export { nanoid, customAlphabet, random }