Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(generate): fix incorrect rollover handling #6

Merged
merged 1 commit into from
Aug 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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];
}