File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff 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+
944export function fromBuffer ( buffer : Buffer ) : string {
1045 const hex = buffer . toString ( "hex" ) ;
1146 return (
You can’t perform that action at this time.
0 commit comments