Skip to content

Commit

Permalink
varint128
Browse files Browse the repository at this point in the history
  • Loading branch information
extremeheat committed Dec 4, 2024
1 parent 07ecaeb commit d611d1a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 14 deletions.
21 changes: 7 additions & 14 deletions example.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,10 @@ const exampleProtocol = {
name: 'onGround',
type: 'bool'
},
{
name: 'longId',
type: 'varint64'
},
{
name: 'zigzagId',
type: 'zigzag32'
},
{
name: 'zigzagBig',
type: 'zigzag64'
}
{ name: 'longId', type: 'varint64' },
{ name: 'longerId', type: 'varint128' },
{ name: 'zigzagId', type: 'zigzag32' },
{ name: 'zigzagBig', type: 'zigzag64' }
]
],
packet: [
Expand Down Expand Up @@ -89,8 +81,9 @@ serializer.write({
yaw: 1,
pitch: 1,
onGround: true,
longId: 22n,
zigzagId: 66,
longId: 13n,
longerId: 2n ** 68n, // 9 bytes integer, 10 over wire
zigzagId: -3,
zigzagBig: 4294967296n
}
})
Expand Down
19 changes: 19 additions & 0 deletions src/datatypes/varint.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const { PartialReadError } = require('../utils')
module.exports = {
varint: [readVarInt, writeVarInt, sizeOfVarInt, require('../../ProtoDef/schemas/utils.json').varint],
varint64: [readVarLong, writeVarLong, sizeOfVarLong, require('../../ProtoDef/schemas/utils.json').varint],
varint128: [readVarLong128, writeVarLong, sizeOfVarLong, require('../../ProtoDef/schemas/utils.json').varint],
zigzag32: [readSignedVarInt, writeSignedVarInt, sizeOfSignedVarInt, require('../../ProtoDef/schemas/utils.json').varint],
zigzag64: [readSignedVarLong, writeSignedVarLong, sizeOfSignedVarLong, require('../../ProtoDef/schemas/utils.json').varint]
}
Expand Down Expand Up @@ -67,6 +68,24 @@ function readVarLong (buffer, offset) {
}
}

function readVarLong128 (buffer, offset) {
let result = 0n
let shift = 0n
let cursor = offset

while (true) {
if (cursor >= buffer.length) throw new Error('Unexpected buffer end while reading VarLong')
const byte = buffer.readUInt8(cursor)
result |= (BigInt(byte) & 0x7Fn) << shift // Add the bits, excluding the MSB
cursor++
if (!(byte & 0x80)) { // If MSB is not set, return result
return { value: result, size: cursor - offset }
}
shift += 7n
if (shift > 128n) throw new Error(`varint is too big: ${shift}`)
}
}

function sizeOfVarLong (value) {
value = BigInt(value)
let size = 0
Expand Down

0 comments on commit d611d1a

Please sign in to comment.