Skip to content

Commit ee3f54c

Browse files
committed
✨ uuidv7 support
1 parent 631f41d commit ee3f54c

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/uuid.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,41 @@ export function v4(): string {
66
return crypto.randomUUID();
77
}
88

9+
// https://www.ietf.org/archive/id/draft-peabody-dispatch-new-uuid-format-04.html#name-uuid-version-7
10+
/**
11+
* unix_ts_ms:
12+
* 48 bit big-endian unsigned number of Unix epoch timestamp as per Section 6.1.
13+
* ver:
14+
* 4 bit UUIDv7 version set as per Section 4
15+
* rand_a:
16+
* 12 bits pseudo-random data to provide uniqueness as per Section 6.2 and Section 6.6.
17+
* var:
18+
* The 2 bit variant defined by Section 4.
19+
* rand_b:
20+
* The final 62 bits of pseudo-random data to provide uniqueness as per Section 6.2 and Section 6.6.
21+
*/
22+
let seq = 0;
23+
export function v7(): string {
24+
const timeComponent = Date.now().toString(16).padStart(12, "0");
25+
26+
const rndBuf = crypto.randomBytes(8);
27+
// set 10 as first 2 bits for RFC 4122 variant
28+
rndBuf[0] = (rndBuf[0] & 0x3f) | 0x80;
29+
const rndArrHex = rndBuf.toString("hex");
30+
31+
return (
32+
timeComponent.slice(0, 8) +
33+
"-" +
34+
timeComponent.slice(8, 12) +
35+
"-7" +
36+
(seq++).toString(16).padStart(3, "0") +
37+
"-" +
38+
rndArrHex.slice(0, 4) +
39+
"-" +
40+
rndArrHex.slice(4, 16)
41+
);
42+
}
43+
944
export function fromBuffer(buffer: Buffer): string {
1045
const hex = buffer.toString("hex");
1146
return (

0 commit comments

Comments
 (0)