readVarInt tests

This commit is contained in:
Kenny Daniel 2024-05-28 13:59:06 -07:00
parent 490d1ec800
commit f28735c0ce
No known key found for this signature in database
GPG Key ID: 90AB653A8CAD7E45
3 changed files with 32 additions and 5 deletions

@ -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

@ -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 }
}

@ -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)
})
})