@@ -17,7 +17,7 @@ export function decodeBoundedUtf8Tail(buffer: Buffer, maxBytes: number): string
1717}
1818
1919export function createBoundedUtf8Tail ( maxBytes : number ) {
20- let chunks : Buffer [ ] = [ ] ;
20+ const storage = Buffer . allocUnsafe ( Math . max ( 0 , maxBytes ) ) ;
2121 let totalBytes = 0 ;
2222
2323 return {
@@ -27,30 +27,23 @@ export function createBoundedUtf8Tail(maxBytes: number) {
2727 return ;
2828 }
2929 if ( buffer . length >= maxBytes ) {
30- chunks = [ buffer . subarray ( buffer . length - maxBytes ) ] ;
30+ buffer . copy ( storage , 0 , buffer . length - maxBytes ) ;
3131 totalBytes = maxBytes ;
3232 return ;
3333 }
3434
35- chunks . push ( buffer ) ;
36- totalBytes += buffer . length ;
37- while ( totalBytes > maxBytes ) {
38- const first = chunks [ 0 ] ! ;
39- const overflowBytes = totalBytes - maxBytes ;
40- if ( overflowBytes < first . length ) {
41- chunks [ 0 ] = first . subarray ( overflowBytes ) ;
42- totalBytes -= overflowBytes ;
43- break ;
44- }
45- chunks . shift ( ) ;
46- totalBytes -= first . length ;
35+ const overflowBytes = Math . max ( 0 , totalBytes + buffer . length - maxBytes ) ;
36+ if ( overflowBytes > 0 ) {
37+ storage . copyWithin ( 0 , overflowBytes , totalBytes ) ;
38+ totalBytes -= overflowBytes ;
4739 }
40+ buffer . copy ( storage , totalBytes ) ;
41+ totalBytes += buffer . length ;
4842 } ,
4943 text ( ) {
50- return decodeUtf8Tail ( Buffer . concat ( chunks , totalBytes ) ) ;
44+ return decodeUtf8Tail ( storage . subarray ( 0 , totalBytes ) ) ;
5145 } ,
5246 clear ( ) {
53- chunks = [ ] ;
5447 totalBytes = 0 ;
5548 } ,
5649 } ;
0 commit comments