提交学习笔记专用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.4 KiB

3 weeks ago
3 weeks ago
3 weeks ago
3 weeks ago
3 weeks ago
3 weeks ago
3 weeks ago
3 weeks ago
3 weeks ago
3 weeks ago
  1. import { webcrypto as crypto } from 'node:crypto'
  2. import { urlAlphabet as scopedUrlAlphabet } from './url-alphabet/index.js'
  3. export { urlAlphabet } from './url-alphabet/index.js'
  4. const POOL_SIZE_MULTIPLIER = 128
  5. let pool, poolOffset
  6. function fillPool(bytes) {
  7. if (!pool || pool.length < bytes) {
  8. pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
  9. crypto.getRandomValues(pool)
  10. poolOffset = 0
  11. } else if (poolOffset + bytes > pool.length) {
  12. crypto.getRandomValues(pool)
  13. poolOffset = 0
  14. }
  15. poolOffset += bytes
  16. }
  17. export function random(bytes) {
  18. fillPool((bytes |= 0))
  19. return pool.subarray(poolOffset - bytes, poolOffset)
  20. }
  21. export function customRandom(alphabet, defaultSize, getRandom) {
  22. let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
  23. let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
  24. return (size = defaultSize) => {
  25. if (!size) return ''
  26. let id = ''
  27. while (true) {
  28. let bytes = getRandom(step)
  29. let i = step
  30. while (i--) {
  31. id += alphabet[bytes[i] & mask] || ''
  32. if (id.length >= size) return id
  33. }
  34. }
  35. }
  36. }
  37. export function customAlphabet(alphabet, size = 21) {
  38. return customRandom(alphabet, size, random)
  39. }
  40. export function nanoid(size = 21) {
  41. fillPool((size |= 0))
  42. let id = ''
  43. for (let i = poolOffset - size; i < poolOffset; i++) {
  44. id += scopedUrlAlphabet[pool[i] & 63]
  45. }
  46. return id
  47. }