diff --git a/src/thrift.js b/src/thrift.js index f97d655..9a48523 100644 --- a/src/thrift.js +++ b/src/thrift.js @@ -115,10 +115,7 @@ function readElement(reader, type) { /** * Var int, also known as Unsigned LEB128. * Var ints take 1 to 5 bytes (int32) or 1 to 10 bytes (int64). - * Takes a Big Endian unsigned integer, left-pads the bit-string to make it a - * multiple of 7 bits, splits it into 7-bit groups, prefix the most-significant - * 7-bit group with the 0 bit, prefixing the remaining 7-bit groups with the - * 1 bit and encode the resulting bit-string as Little Endian. + * Reads groups of 7 low bits until high bit is 0. * * @param {DataReader} reader * @returns {number} value diff --git a/test/helpers.js b/test/helpers.js index b35cf1a..fb575fb 100644 --- a/test/helpers.js +++ b/test/helpers.js @@ -34,3 +34,13 @@ export function fileToJson(filePath) { const buffer = fs.readFileSync(filePath) return JSON.parse(buffer.toString()) } + +/** + * Make a DataReader from bytes + * + * @param {number[]} bytes + * @returns {import('../src/types.js').DataReader} + */ +export function reader(bytes) { + return { view: new DataView(new Uint8Array(bytes).buffer), offset: 0 } +} diff --git a/test/thrift.test.js b/test/thrift.test.js index 62ce886..d947353 100644 --- a/test/thrift.test.js +++ b/test/thrift.test.js @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' -import { deserializeTCompactProtocol, toVarInt } from '../src/thrift.js' +import { deserializeTCompactProtocol, readVarInt, toVarInt } from '../src/thrift.js' +import { reader } from './helpers.js' describe('deserializeTCompactProtocol function', () => { @@ -79,3 +80,22 @@ describe('deserializeTCompactProtocol function', () => { }) }) + +describe('readVarInt', () => { + it('read single-byte varint', () => { + expect(readVarInt(reader([0x01]))).toBe(1) + expect(readVarInt(reader([0x7f]))).toBe(127) + }) + + it('read multi-byte varint', () => { + // 129 as varint (0b10000001 00000001) + expect(readVarInt(reader([0x81, 0x01]))).toBe(129) + // 16515 as varint (0b10000011 10000010 00000001) + expect(readVarInt(reader([0x83, 0x82, 0x01]))).toBe(16643) + }) + + it('read maximum int32 varint', () => { + // 2147483647 as varint (0b11111111 11111111 11111111 11111111 00000111) + expect(readVarInt(reader([0xff, 0xff, 0xff, 0xff, 0x07]))).toBe(2147483647) + }) +})