Skip to content

Commit 40b680f

Browse files
committed
fix(browser): own bounded stderr storage
1 parent 6b52997 commit 40b680f

2 files changed

Lines changed: 18 additions & 16 deletions

File tree

extensions/browser/src/browser/bounded-utf8-tail.test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,13 @@ describe("bounded UTF-8 tail", () => {
2525
tail.clear();
2626
expect(tail.text()).toBe("");
2727
});
28+
29+
it("copies bytes out of caller-owned buffers", () => {
30+
const tail = createBoundedUtf8Tail(4);
31+
const source = Buffer.from("test");
32+
tail.append(source);
33+
source.fill(0);
34+
35+
expect(tail.text()).toBe("test");
36+
});
2837
});

extensions/browser/src/browser/bounded-utf8-tail.ts

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export function decodeBoundedUtf8Tail(buffer: Buffer, maxBytes: number): string
1717
}
1818

1919
export 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

Comments
 (0)