uuid.modified.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // uuid.js (适用于 Vue 3 和 uni-app 的模块格式)
  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. // 使用 uni-app 跨平台方式获取随机数生成器
  19. let rng = mathRNG;
  20. // #ifdef H5
  21. // H5环境下尝试使用 crypto API
  22. try {
  23. const _crypto = globalThis.crypto || globalThis.msCrypto;
  24. if (_crypto && _crypto.getRandomValues) {
  25. const rnds8 = new Uint8Array(16);
  26. rng = function () {
  27. _crypto.getRandomValues(rnds8);
  28. return rnds8;
  29. };
  30. }
  31. } catch (e) {
  32. // fallback to mathRNG
  33. console.log('Crypto API not available, using Math.random()');
  34. }
  35. // #endif
  36. // #ifndef H5
  37. // 非H5环境使用 Math.random()
  38. rng = mathRNG;
  39. // #endif
  40. // UUID v4
  41. function v4(options = {}, buf, offset = 0) {
  42. let rnds = options.random || (options.rng || rng)();
  43. rnds[6] = (rnds[6] & 0x0f) | 0x40;
  44. rnds[8] = (rnds[8] & 0x3f) | 0x80;
  45. if (buf) {
  46. for (let i = 0; i < 16; i++) {
  47. buf[offset + i] = rnds[i];
  48. }
  49. return buf;
  50. }
  51. return unparse(rnds);
  52. }
  53. // UUID stringifier
  54. function unparse(buf, offset = 0) {
  55. const bth = _byteToHex;
  56. return (
  57. bth[buf[offset++]] + bth[buf[offset++]] +
  58. bth[buf[offset++]] + bth[buf[offset++]] + '-' +
  59. bth[buf[offset++]] + bth[buf[offset++]] + '-' +
  60. bth[buf[offset++]] + bth[buf[offset++]] + '-' +
  61. bth[buf[offset++]] + bth[buf[offset++]] + '-' +
  62. bth[buf[offset++]] + bth[buf[offset++]] +
  63. bth[buf[offset++]] + bth[buf[offset++]] +
  64. bth[buf[offset++]] + bth[buf[offset++]]
  65. );
  66. }
  67. // UUID parser
  68. function parse(s, buf = [], offset = 0) {
  69. let ii = 0;
  70. s.toLowerCase().replace(/[0-9a-f]{2}/g, function (oct) {
  71. if (ii < 16) {
  72. buf[offset + ii++] = _hexToByte[oct];
  73. }
  74. });
  75. while (ii < 16) buf[offset + ii++] = 0;
  76. return buf;
  77. }
  78. // 默认导出 v4,同时附带辅助函数
  79. export default {
  80. v4,
  81. parse,
  82. unparse
  83. };