Skip to content

Commit 0bc7cfa

Browse files
authored
Properly reset BinaryWriter after finish (#986)
1 parent a3e43df commit 0bc7cfa

File tree

4 files changed

+25
-12
lines changed

4 files changed

+25
-12
lines changed

packages/bundle-size/README.md

+5-5
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@ usually do. We repeat this for an increasing number of files.
1616

1717
| code generator | files | bundle size | minified | compressed |
1818
| ------------------- | ----: | ----------: | --------: | ---------: |
19-
| Protobuf-ES | 1 | 126,123 b | 65,653 b | 15,258 b |
20-
| Protobuf-ES | 4 | 128,312 b | 67,161 b | 15,970 b |
21-
| Protobuf-ES | 8 | 131,074 b | 68,932 b | 16,481 b |
22-
| Protobuf-ES | 16 | 141,524 b | 76,913 b | 18,797 b |
23-
| Protobuf-ES | 32 | 169,315 b | 98,931 b | 24,268 b |
19+
| Protobuf-ES | 1 | 126,179 b | 65,684 b | 15,268 b |
20+
| Protobuf-ES | 4 | 128,368 b | 67,192 b | 15,925 b |
21+
| Protobuf-ES | 8 | 131,130 b | 68,963 b | 16,458 b |
22+
| Protobuf-ES | 16 | 141,580 b | 76,944 b | 18,756 b |
23+
| Protobuf-ES | 32 | 169,371 b | 98,962 b | 24,290 b |
2424
| protobuf-javascript | 1 | 334,193 b | 255,820 b | 42,481 b |
2525
| protobuf-javascript | 4 | 360,861 b | 271,092 b | 43,912 b |
2626
| protobuf-javascript | 8 | 382,904 b | 283,409 b | 45,038 b |

packages/bundle-size/chart.svg

+6-6
Loading

packages/protobuf-test/src/wire/binary-encoding.test.ts

+10
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,16 @@ describe("BinaryWriter", () => {
134134
},
135135
);
136136
});
137+
it("should be completely reset after finish", () => {
138+
const writer = new BinaryWriter();
139+
// Make sure we have both a chunk and a buffer
140+
writer.raw(new Uint8Array([1, 2, 3])).int32(1);
141+
const bytes = writer.finish();
142+
// Reuse the same writer to write the same data
143+
writer.raw(new Uint8Array([1, 2, 3])).int32(1);
144+
const bytes2 = writer.finish();
145+
expect(bytes2).toStrictEqual(bytes);
146+
});
137147
});
138148

139149
describe("BinaryReader", () => {

packages/protobuf/src/wire/binary-encoding.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,10 @@ export class BinaryWriter {
133133
* Return all bytes written and reset this writer.
134134
*/
135135
finish(): Uint8Array {
136-
this.chunks.push(new Uint8Array(this.buf)); // flush the buffer
136+
if (this.buf.length) {
137+
this.chunks.push(new Uint8Array(this.buf)); // flush the buffer
138+
this.buf = [];
139+
}
137140
let len = 0;
138141
for (let i = 0; i < this.chunks.length; i++) len += this.chunks[i].length;
139142
let bytes = new Uint8Array(len);

0 commit comments

Comments
 (0)