Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
9 changes: 7 additions & 2 deletions encoding/varint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,9 +227,14 @@ export function encodeVarint(
`Cannot encode the input into varint as it should be non-negative integer: received ${num}`,
);
}
if (num > MaxUint64) {
throw new RangeError(
`Cannot encode the input ${num} into varint as it overflows uint64`,
);
}
for (
let i = offset;
i <= Math.min(buf.length, MaxVarintLen64);
i < buf.length;
i += 1
) {
if (num < MSBN) {
Expand All @@ -241,6 +246,6 @@ export function encodeVarint(
num >>= SHIFTN;
}
throw new RangeError(
`Cannot encode the input ${num} into varint as it overflows uint64`,
"Cannot encode the input into varint: the provided buffer is too small",
);
}
17 changes: 17 additions & 0 deletions encoding/varint_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,23 @@ Deno.test("encodeVarint() handles manual", () => {
Deno.test("encodeVarint() throws on overflow uint64", () => {
assertThrows(() => encodeVarint(1e+30), RangeError, "overflows uint64");
});
Deno.test("encodeVarint() throws on overflow uint64 with default buffer", () => {
// 0x1234567891234567891n is 73 bits, exceeds MaxUint64 (2^64 - 1).
// The default 10-byte buffer must not silently truncate the encoding.
assertThrows(
() => encodeVarint(0x1234567891234567891n),
RangeError,
"overflows uint64",
);
});
Deno.test("encodeVarint() throws when the buffer is too small", () => {
// MaxUint64 needs 10 bytes to encode; a 5-byte buffer is too small.
assertThrows(
() => encodeVarint(MaxUint64, new Uint8Array(5)),
RangeError,
"the provided buffer is too small",
);
});
Deno.test("encodeVarint() throws on overflow with negative", () => {
assertThrows(
() => encodeVarint(-1),
Expand Down
Loading