UNPKG

@thi.ng/ksuid

Version:

Configurable K-sortable unique IDs, ULIDs, binary & base-N encoded, 32/48/64bit time resolutions

39 lines (38 loc) 884 B
import { AKSUID } from "./aksuid.js"; class KSUID64 extends AKSUID { constructor(opts) { super(8, { epoch: 16e11, bytes: 12, ...opts }); } timeOnlyBinary(epoch = Date.now(), buf) { buf = buf || new Uint8Array(this.size); const t = this.ensureTime(epoch - this.epoch); const h = t / 4294967296 >>> 0; const l = (t & 4294967295) >>> 0; buf[0] = h >>> 24; buf[1] = h >> 16 & 255; buf[2] = h >> 8 & 255; buf[3] = h & 255; buf[4] = l >>> 24; buf[5] = l >> 16 & 255; buf[6] = l >> 8 & 255; buf[7] = l & 255; return buf; } parse(id) { const buf = this.tmp; this.base.decodeBytes(id, buf); return { epoch: this.u32(buf) * 4294967296 + this.u32(buf, 4) + this.epoch, id: buf.slice(8) }; } } const defKSUID64 = (opts) => new KSUID64(opts); export { KSUID64, defKSUID64 };