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

implement Timestamp96 #88

Merged
merged 2 commits into from
Dec 21, 2020
Merged
Changes from 1 commit
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
62 changes: 60 additions & 2 deletions lib/codecs/DateCodec.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,41 @@ function encode (dt) {
var seconds = Math.floor(millis / 1000)
var nanos = (millis - seconds * 1000) * 1e6

if (nanos || seconds > 0xffffffff) {
if (seconds >> 34 !== 0) {
// Timestamp96
const encoded = Buffer.allocUnsafe(13)
encoded[0] = -1

encoded.writeUInt32BE(nanos, 1)

var hex = ''
if (seconds >= 0) {
const padhex = '0000000000000000'
hex = seconds.toString(16)
// add some padding
hex = padhex.slice(0, hex.length * -1) + hex
} else {
// encode seconds in 2's Complement 64Bit
// reverse sign
// keep all bits 0 and first 1 from right
// reverse all other bits
var bin = (seconds * -1).toString(2)
var i = bin.length - 1
while (bin[i] === '0') {
i--
}
bin = bin.slice(0, i).split('').map(function (bit) { return bit === '1' ? 0 : 1 }).join('') + bin.slice(i, bin.length)
// add some padding
const pad64 = '1111111111111111111111111111111111111111111111111111111111111111'
bin = pad64.slice(0, bin.length * -1) + bin
// convert to hex
bin.match(/.{1,8}/g).forEach(function (byte) {
hex += parseInt(byte, 2).toString(16)
})
}
encoded.write(hex, 5, 'hex')
return encoded
} else if (nanos || seconds > 0xffffffff) {
// Timestamp64
const encoded = Buffer.allocUnsafe(9)
encoded[0] = -1
Expand Down Expand Up @@ -55,7 +89,31 @@ function decode (buf) {
break

case 12:
throw new Error('timestamp 96 is not yet implemented')
// timestamp 96 stores the number of seconds and nanoseconds that have elapsed
// since 1970-01-01 00:00:00 UTC in 64-bit signed integer and 32-bit unsigned integer

// get seconds in hex
var hex = buf.toString('hex', 4, 12)
// check if seconds is a negative number
if (parseInt(buf.toString('hex', 4, 6), 16) & 0x80) {
// convert to binary
var bin = ''
const pad8 = '00000000'
hex.match(/.{1,2}/g).forEach(function (byte) {
byte = parseInt(byte, 16).toString(2)
byte = pad8.slice(0, byte.length * -1) + byte
bin += byte
})
// decode seconds from 2's Complement 64Bit
// reverse all bits
// reverse sign
// remove one
seconds = -1 * parseInt(bin.split('').map(function (bit) { return bit === '1' ? 0 : 1 }).join(''), 2) - 1
} else {
seconds = parseInt(hex, 16)
}

nanoseconds = buf.readUInt32BE(0)
}

var millis = (seconds * 1000) + Math.round(nanoseconds / 1E6)
Expand Down