Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Save state before using BinaryWriter #674

Closed
wants to merge 1 commit into from
Closed
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
30 changes: 30 additions & 0 deletions packages/protobuf-test/src/msg-message.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@

import { expect, test } from "@jest/globals";
import type { JsonValue, PlainMessage } from "@bufbuild/protobuf";
import { BinaryWriter } from "@bufbuild/protobuf";
import { MessageFieldMessage as TS_MessageFieldMessage } from "./gen/ts/extra/msg-message_pb.js";
import { MessageFieldMessage as JS_MessageFieldMessage } from "./gen/js/extra/msg-message_pb.js";
import { describeMT } from "./helpers.js";
import assert from "node:assert";

describeMT(
{ ts: TS_MessageFieldMessage, js: JS_MessageFieldMessage },
Expand Down Expand Up @@ -102,5 +104,33 @@ describeMT(
}),
);
});
test("example binary encodes and decodes using same writer instance", () => {
const msg = new messageType(exampleFields);
const writer = new BinaryWriter();

let runs = 10;
let enc;
while (runs > 0) {
enc = msg.toBinary({
writerFactory: () => writer,
});
runs--;
}
assert(enc !== undefined);

const got = messageType.fromBinary(enc);
expect(got.messageField?.name).toStrictEqual(
exampleFields.messageField.name,
);
expect(got.repeatedMessageField.length).toStrictEqual(
exampleFields.repeatedMessageField.length,
);
expect(got.repeatedMessageField[0].name).toStrictEqual(
exampleFields.repeatedMessageField[0].name,
);
expect(got.repeatedMessageField[1].name).toStrictEqual(
exampleFields.repeatedMessageField[1].name,
);
});
},
);
28 changes: 18 additions & 10 deletions packages/protobuf/src/binary-encoding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ export interface IBinaryReader {

export interface IBinaryWriter {
/**
* Return all bytes written and reset this writer.
* Return all bytes written and return to the previous state.
*/
finish(): Uint8Array;

Expand Down Expand Up @@ -314,6 +314,8 @@ export class BinaryWriter implements IBinaryWriter {
this.textEncoder = textEncoder ?? new TextEncoder();
this.chunks = [];
this.buf = [];

this.fork();
}

/**
Expand All @@ -329,15 +331,28 @@ export class BinaryWriter implements IBinaryWriter {
bytes.set(this.chunks[i], offset);
offset += this.chunks[i].length;
}
this.chunks = [];

this.restore();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The documentation states that the method "resets this writer". It looks like the function does not reset the property buf . It makes sense to me to fix this up, and add this.buf = [] here.

From what I see, this change would be sufficient for your use case, and it would improve the behavior of the writer. I do not think that any other changes should be made for this fix, at least not without adding significant test coverage first and taking a close look at the impact on performance.


return bytes;
}

/*
* Restore the previous stack entry.
*/
restore(): IBinaryWriter {
let prev = this.stack.pop();
if (!prev) throw new Error("invalid state, fork stack empty");
this.chunks = prev.chunks;
this.buf = prev.buf;
return this;
}

/**
* Start a new fork for length-delimited data like a message
* or a packed repeated field.
*
* Must be joined later with `join()`.
* Must be joined later with `join()` or flushed with `finish()`.
*/
fork(): IBinaryWriter {
this.stack.push({ chunks: this.chunks, buf: this.buf });
Expand All @@ -353,13 +368,6 @@ export class BinaryWriter implements IBinaryWriter {
join(): IBinaryWriter {
// get chunk of fork
let chunk = this.finish();

// restore previous state
let prev = this.stack.pop();
if (!prev) throw new Error("invalid state, fork stack empty");
this.chunks = prev.chunks;
this.buf = prev.buf;

// write length of chunk as varint
this.uint32(chunk.byteLength);
return this.raw(chunk);
Expand Down
1 change: 1 addition & 0 deletions packages/protobuf/src/extension-accessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export function setExtension<E extends Message<E>, V>(
}
}
const writer = writeOpt.writerFactory();
writer.fork();
extension.runtime.bin.writeField(extension.field, value, writer, writeOpt);
const reader = readOpt.readerFactory(writer.finish());
while (reader.pos < reader.len) {
Expand Down
1 change: 1 addition & 0 deletions packages/protobuf/src/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ export class Message<T extends Message<T> = AnyMessage> {
bin = type.runtime.bin,
opt = bin.makeWriteOptions(options),
writer = opt.writerFactory();
writer.fork();
bin.writeMessage(this, writer, opt);
return writer.finish();
}
Expand Down
2 changes: 1 addition & 1 deletion packages/protobuf/src/proto-delimited.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const protoDelimited = {
*/
enc(message: Message, options?: BinaryWriteOptions): Uint8Array {
const opt = makeBinaryFormatCommon().makeWriteOptions(options);
return opt.writerFactory().bytes(message.toBinary(opt)).finish();
return opt.writerFactory().fork().bytes(message.toBinary(opt)).finish();
},

/**
Expand Down
Loading