| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- // uuid.js (适用于 Vue 3 的模块格式)
- '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;
- }
- // try crypto
- let rng = mathRNG;
- 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 already set
- }
- // 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
- };
|