| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- // uuid.js (适用于 Vue 3 和 uni-app 的模块格式)
- 'use strict';
- const _byteToHex = [];
- const _hexToByte = {};
- for (let i = 0; i < 256; i++) {
- _byteToHex[i] = (i + 0x100).toString(16).substr(1);
- _hexToByte[_byteToHex[i]] = i;
- }
- // Math.random() fallback
- function mathRNG() {
- const rnds = new Array(16);
- for (let i = 0, r; i < 16; i++) {
- if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
- rnds[i] = (r >>> ((i & 0x03) << 3)) & 0xff;
- }
- return rnds;
- }
- // 使用 uni-app 跨平台方式获取随机数生成器
- let rng = mathRNG;
- // #ifdef H5
- // H5环境下尝试使用 crypto API
- try {
- const _crypto = globalThis.crypto || globalThis.msCrypto;
- if (_crypto && _crypto.getRandomValues) {
- const rnds8 = new Uint8Array(16);
- rng = function () {
- _crypto.getRandomValues(rnds8);
- return rnds8;
- };
- }
- } catch (e) {
- // fallback to mathRNG
- console.log('Crypto API not available, using Math.random()');
- }
- // #endif
- // #ifndef H5
- // 非H5环境使用 Math.random()
- rng = mathRNG;
- // #endif
- // UUID v4
- function v4(options = {}, buf, offset = 0) {
- let rnds = options.random || (options.rng || rng)();
- rnds[6] = (rnds[6] & 0x0f) | 0x40;
- rnds[8] = (rnds[8] & 0x3f) | 0x80;
- if (buf) {
- for (let i = 0; i < 16; i++) {
- buf[offset + i] = rnds[i];
- }
- return buf;
- }
- return unparse(rnds);
- }
- // UUID stringifier
- function unparse(buf, offset = 0) {
- const bth = _byteToHex;
- return (
- bth[buf[offset++]] + bth[buf[offset++]] +
- bth[buf[offset++]] + bth[buf[offset++]] + '-' +
- bth[buf[offset++]] + bth[buf[offset++]] + '-' +
- bth[buf[offset++]] + bth[buf[offset++]] + '-' +
- bth[buf[offset++]] + bth[buf[offset++]] + '-' +
- bth[buf[offset++]] + bth[buf[offset++]] +
- bth[buf[offset++]] + bth[buf[offset++]] +
- bth[buf[offset++]] + bth[buf[offset++]]
- );
- }
- // UUID parser
- function parse(s, buf = [], offset = 0) {
- let ii = 0;
- s.toLowerCase().replace(/[0-9a-f]{2}/g, function (oct) {
- if (ii < 16) {
- buf[offset + ii++] = _hexToByte[oct];
- }
- });
- while (ii < 16) buf[offset + ii++] = 0;
- return buf;
- }
- // 默认导出 v4,同时附带辅助函数
- export default {
- v4,
- parse,
- unparse
- };
|