Skip to content

Commit

Permalink
fix(generate): fix incorrect rollover handling (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
babiabeo authored Aug 11, 2024
1 parent 63126a7 commit be64975
Showing 1 changed file with 13 additions and 13 deletions.
26 changes: 13 additions & 13 deletions src/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ import { stringify } from "./_stringify.ts";
*/
export function generate(timestamp?: number): string {
const uuid = new Uint8Array(16);
const tm = timestamp ?? Date.now();
const now = timestamp ?? Date.now();
const rand = crypto.getRandomValues(new Uint8Array(10));
const seq = getSeq(tm, rand);
const [seq, tm] = getState(now, rand);

// [octets 0-5]: timestamp (48 bits)
uuid[0] = (tm / 0x10000000000) & 0xff;
Expand Down Expand Up @@ -65,23 +65,23 @@ export function generate(timestamp?: number): string {
}

// The last time the function was called
let _lastTime = -Infinity;
let lastTime = -Infinity;
// The sequence number (18 bits)
let _seq = 0;
let seq = 0;

function getSeq(now: number, rand: Uint8Array): number {
if (now > _lastTime) {
_seq = ((rand[7] & 0x03) << 16) | (rand[8] << 8) | rand[9];
_lastTime = now;
function getState(now: number, rand: Uint8Array): [number, number] {
if (now > lastTime) {
seq = ((rand[7] & 0x03) << 16) | (rand[8] << 8) | (rand[9]);
lastTime = now;

return _seq;
return [seq, lastTime];
}

_seq = (_seq + 1) & 0x3ffff;
seq = (seq + 1) & 0x3ffff;

if (_seq === 0) {
++_lastTime;
if (seq === 0) {
++lastTime;
}

return _seq;
return [seq, lastTime];
}

0 comments on commit be64975

Please sign in to comment.