File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -227,9 +227,14 @@ export function encodeVarint(
227227 `Cannot encode the input into varint as it should be non-negative integer: received ${ num } ` ,
228228 ) ;
229229 }
230+ if ( num > MaxUint64 ) {
231+ throw new RangeError (
232+ `Cannot encode the input ${ num } into varint as it overflows uint64` ,
233+ ) ;
234+ }
230235 for (
231236 let i = offset ;
232- i <= Math . min ( buf . length , MaxVarintLen64 ) ;
237+ i < buf . length ;
233238 i += 1
234239 ) {
235240 if ( num < MSBN ) {
@@ -241,6 +246,6 @@ export function encodeVarint(
241246 num >>= SHIFTN ;
242247 }
243248 throw new RangeError (
244- ` Cannot encode the input ${ num } into varint as it overflows uint64` ,
249+ " Cannot encode the input into varint: the provided buffer is too small" ,
245250 ) ;
246251}
Original file line number Diff line number Diff line change @@ -113,6 +113,23 @@ Deno.test("encodeVarint() handles manual", () => {
113113Deno . test ( "encodeVarint() throws on overflow uint64" , ( ) => {
114114 assertThrows ( ( ) => encodeVarint ( 1e+30 ) , RangeError , "overflows uint64" ) ;
115115} ) ;
116+ Deno . test ( "encodeVarint() throws on overflow uint64 with default buffer" , ( ) => {
117+ // 0x1234567891234567891n is 73 bits, exceeds MaxUint64 (2^64 - 1).
118+ // The default 10-byte buffer must not silently truncate the encoding.
119+ assertThrows (
120+ ( ) => encodeVarint ( 0x1234567891234567891n ) ,
121+ RangeError ,
122+ "overflows uint64" ,
123+ ) ;
124+ } ) ;
125+ Deno . test ( "encodeVarint() throws when the buffer is too small" , ( ) => {
126+ // MaxUint64 needs 10 bytes to encode; a 5-byte buffer is too small.
127+ assertThrows (
128+ ( ) => encodeVarint ( MaxUint64 , new Uint8Array ( 5 ) ) ,
129+ RangeError ,
130+ "the provided buffer is too small" ,
131+ ) ;
132+ } ) ;
116133Deno . test ( "encodeVarint() throws on overflow with negative" , ( ) => {
117134 assertThrows (
118135 ( ) => encodeVarint ( - 1 ) ,
You can’t perform that action at this time.
0 commit comments