MCPcopy
hub / github.com/uuidjs/uuid / updateV1State

Function updateV1State

src/v1.ts:93–143  ·  view source on GitHub ↗
(state: V1State, now: number, rnds: Uint8Array)

Source from the content-addressed store, hash-verified

91// (Private!) Do not use. This method is only exported for testing purposes
92// and may change without notice.
93export function updateV1State(state: V1State, now: number, rnds: Uint8Array) {
94 state.msecs ??= -Infinity;
95 state.nsecs ??= 0;
96
97 // Update timestamp
98 if (now === state.msecs) {
99 // Same msec-interval = simulate higher clock resolution by bumping `nsecs`
100 // https://www.rfc-editor.org/rfc/rfc9562.html#section-6.1-2.6
101 state.nsecs++;
102
103 // Check for `nsecs` overflow (nsecs is capped at 10K intervals / msec)
104 if (state.nsecs >= 10000) {
105 // Prior to uuid@11 this would throw an error, however the RFCs allow for
106 // changing the node in this case. This slightly breaks monotonicity at
107 // msec granularity, but that's not a significant concern.
108 // https://www.rfc-editor.org/rfc/rfc9562.html#section-6.1-2.16
109 state.node = undefined;
110 state.nsecs = 0;
111 }
112 } else if (now > state.msecs) {
113 // Reset nsec counter when clock advances to a new msec interval
114 state.nsecs = 0;
115 } else if (now < state.msecs) {
116 // Handle clock regression
117 // https://www.rfc-editor.org/rfc/rfc9562.html#section-6.1-2.7
118 //
119 // Note: Unsetting node here causes both it and clockseq to be randomized,
120 // below.
121 state.node = undefined;
122 }
123
124 // Init node and clock sequence (do this after timestamp update which may
125 // reset the node) https://www.rfc-editor.org/rfc/rfc9562.html#section-5.1-7
126 //
127 // Note:
128 if (!state.node) {
129 state.node = rnds.slice(10, 16);
130
131 // Set multicast bit
132 // https://www.rfc-editor.org/rfc/rfc9562.html#section-6.10-3
133 state.node[0] |= 0x01; // Set multicast bit
134
135 // Clock sequence must be randomized
136 // https://www.rfc-editor.org/rfc/rfc9562.html#section-5.1-8
137 state.clockseq = ((rnds[8] << 8) | rnds[9]) & 0x3fff;
138 }
139
140 state.msecs = now;
141
142 return state;
143}
144
145function v1Bytes(
146 rnds: Uint8Array,

Callers 2

v1Function · 0.85
v1.test.tsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected