From d611d1a36089d314acfbcf283b624563e232431c Mon Sep 17 00:00:00 2001 From: extremeheat Date: Wed, 4 Dec 2024 04:22:03 +0000 Subject: [PATCH] varint128 --- example.js | 21 +++++++-------------- src/datatypes/varint.js | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/example.js b/example.js index 4a3cede..8f68bdb 100644 --- a/example.js +++ b/example.js @@ -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: [ @@ -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 } }) diff --git a/src/datatypes/varint.js b/src/datatypes/varint.js index 330816c..c5ea896 100644 --- a/src/datatypes/varint.js +++ b/src/datatypes/varint.js @@ -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] } @@ -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