uuid.modified.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // uuid.js (适用于 Vue 3 的模块格式)
  2. 'use strict';
  3. const _byteToHex = [];
  4. const _hexToByte = {};
  5. for (let i = 0; i < 256; i++) {
  6. _byteToHex[i] = (i + 0x100).toString(16).substr(1);
  7. _hexToByte[_byteToHex[i]] = i;
  8. }
  9. // Math.random() fallback
  10. function mathRNG() {
  11. const rnds = new Array(16);
  12. for (let i = 0, r; i < 16; i++) {
  13. if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
  14. rnds[i] = (r >>> ((i & 0x03) << 3)) & 0xff;
  15. }
  16. return rnds;
  17. }
  18. // try crypto
  19. let rng = mathRNG;
  20. try {
  21. const _crypto = globalThis.crypto || globalThis.msCrypto;
  22. if (_crypto && _crypto.getRandomValues) {
  23. const rnds8 = new Uint8Array(16);
  24. rng = function () {
  25. _crypto.getRandomValues(rnds8);
  26. return rnds8;
  27. };
  28. }
  29. } catch (e) {
  30. // fallback already set
  31. }
  32. // UUID v4
  33. function v4(options = {}, buf, offset = 0) {
  34. let rnds = options.random || (options.rng || rng)();
  35. rnds[6] = (rnds[6] & 0x0f) | 0x40;
  36. rnds[8] = (rnds[8] & 0x3f) | 0x80;
  37. if (buf) {
  38. for (let i = 0; i < 16; i++) {
  39. buf[offset + i] = rnds[i];
  40. }
  41. return buf;
  42. }
  43. return unparse(rnds);
  44. }
  45. // UUID stringifier
  46. function unparse(buf, offset = 0) {
  47. const bth = _byteToHex;
  48. return (
  49. bth[buf[offset++]] + bth[buf[offset++]] +
  50. bth[buf[offset++]] + bth[buf[offset++]] + '-' +
  51. bth[buf[offset++]] + bth[buf[offset++]] + '-' +
  52. bth[buf[offset++]] + bth[buf[offset++]] + '-' +
  53. bth[buf[offset++]] + bth[buf[offset++]] + '-' +
  54. bth[buf[offset++]] + bth[buf[offset++]] +
  55. bth[buf[offset++]] + bth[buf[offset++]] +
  56. bth[buf[offset++]] + bth[buf[offset++]]
  57. );
  58. }
  59. // UUID parser
  60. function parse(s, buf = [], offset = 0) {
  61. let ii = 0;
  62. s.toLowerCase().replace(/[0-9a-f]{2}/g, function (oct) {
  63. if (ii < 16) {
  64. buf[offset + ii++] = _hexToByte[oct];
  65. }
  66. });
  67. while (ii < 16) buf[offset + ii++] = 0;
  68. return buf;
  69. }
  70. // 默认导出 v4,同时附带辅助函数
  71. export default {
  72. v4,
  73. parse,
  74. unparse
  75. };