-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgsid.js
More file actions
47 lines (39 loc) · 1.21 KB
/
gsid.js
File metadata and controls
47 lines (39 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use strict';
const crypto = require('node:crypto');
const DIGITS = '0123456789';
const LOWER = 'abcdefghijklmnopqrstuvwxyz';
const UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const CHARS = DIGITS + LOWER + UPPER + '-_';
const CHARS_LENGTH = CHARS.length;
const POSSIBLE = new Uint8Array(256);
for (let i = 0; i < CHARS_LENGTH; i++) {
const char = CHARS.charCodeAt(i);
POSSIBLE[i] = char;
POSSIBLE[i + 64] = char;
POSSIBLE[i + 128] = char;
POSSIBLE[i + 192] = char;
}
const DEFAULT_LENGTH = 24;
const BUF_SIZE = DEFAULT_LENGTH * 4096;
const randomBuffer = crypto.randomBytes(BUF_SIZE);
const resultBuffer = [];
resultBuffer[DEFAULT_LENGTH] = Buffer.allocUnsafe(DEFAULT_LENGTH);
let bufferPos = 0;
const generateId = (length = DEFAULT_LENGTH) => {
let result = resultBuffer[length];
if (!result) {
result = Buffer.allocUnsafe(length);
resultBuffer[length] = result;
}
if (bufferPos + length > randomBuffer.length) {
crypto.randomFillSync(randomBuffer);
bufferPos = 0;
}
const start = bufferPos;
bufferPos += length;
for (let i = 0; i < length; i++) {
result[i] = POSSIBLE[randomBuffer[start + i] & 0x3f];
}
return result.toString('ascii');
};
module.exports = { generateId, CHARS };