Skip to content

Instantly share code, notes, and snippets.

@intech
Created July 30, 2020 10:14
Show Gist options
  • Save intech/210cf01ed083de1d4fc6ab3af6e383c0 to your computer and use it in GitHub Desktop.
Save intech/210cf01ed083de1d4fc6ab3af6e383c0 to your computer and use it in GitHub Desktop.
{
"name": "uuidv1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"level": "^6.0.1",
"level-rocksdb": "^4.0.0",
"uuid": "^8.3.0"
}
}
const {v1} = require("uuid");
const rocksdb = require("level-rocksdb");
const rdb = rocksdb("./rocksdb", { keyEncoding: "binary", valueEncoding: "utf-8" });
const level = require("level");
const db = level("./codes", { keyEncoding: "binary", valueEncoding: "utf-8" });
const start = 5;
for(let i = start; i < start+3; i++) {
const key = Buffer.alloc(20, "code");
v1(null, key, 4);
console.log(i, key.toString("ascii", 0, 4), new Date(v1time(key, 4)));
rdb.put(key, i, err => err ? console.error(err) : console.log(`rocks write ${i}`));
db.put(key, i, err => err ? console.error(err) : console.log(`level write ${i}`));
}
setTimeout(async() => {
console.log("leveldb");
const stream = db.createReadStream({ limit: 1000 });
for await (const data of stream) {
console.log(data.key, new Date(v1time(data.key, 4)), data.value);
}
console.log("rocksdb");
const stream2 = rdb.createReadStream({ limit: 1000 });
for await (const data of stream2) {
console.log(data.key, new Date(v1time(data.key, 4)), data.value);
}
}, 1000);
function v1time(buf, offset) {
let msec = 0, nsec = 0;
let i = buf && offset || 0;
let b = buf||[];
// inspect version at offset 6
if ((b[i+6]&0x10) !== 0x10)
throw new Error("uuid version 1 expected");
// 'time_low'
let tl = 0;
tl |= ( b[i++] & 0xff ) << 24;
tl |= ( b[i++] & 0xff ) << 16;
tl |= ( b[i++] & 0xff ) << 8;
tl |= b[i++] & 0xff ;
// `time_mid`
let tmh = 0;
tmh |= ( b[i++] & 0xff ) << 8;
tmh |= b[i++] & 0xff;
// `time_high_minus_version`
tmh |= ( b[i++] & 0xf ) << 24;
tmh |= ( b[i++] & 0xff ) << 16;
// account for the sign bit
msec = ((tl >>> 1) * 2 + ((tl & 0x7fffffff) % 2)) / 10000.0;
msec += ((tmh >>> 1) * 2 + ((tmh & 0x7fffffff) % 2)) * 0x100000000 / 10000.0;
// Per 4.1.4 - Convert from Gregorian epoch to unix epoch
msec -= 12219292800000;
// getting the nsec. they are not needed now though
// nsec = ( tl & 0xfffffff ) % 10000;
return msec;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment