Skip to content

Fix decoding of signed varint32s. #134

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

Merged
merged 2 commits into from
Sep 19, 2022
Merged
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
10 changes: 6 additions & 4 deletions binary/decoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -481,13 +481,15 @@ jspb.BinaryDecoder.prototype.readUnsignedVarint32 = function() {


/**
* The readUnsignedVarint32 above deals with signed 32-bit varints correctly,
* so this is just an alias.
* Coerces the output of readUnsignedVarint32 to an int32.
*
* @return {number} The decoded signed 32-bit varint.
*/
jspb.BinaryDecoder.prototype.readSignedVarint32 =
jspb.BinaryDecoder.prototype.readUnsignedVarint32;
jspb.BinaryDecoder.prototype.readSignedVarint32 = function() {
// The `~` operator coerces to int32, and `~~` is the shortest expression of a cast.
// This has some edge cases (e.g. NaN becomes 0) but should be okay here.
return ~~(this.readUnsignedVarint32());
}


/**
Expand Down
20 changes: 20 additions & 0 deletions binary/decoder_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -426,10 +426,20 @@ describe('binaryDecoderTest', function() {
jspb.BinaryEncoder.prototype.writeUint32,
1, 0xFFFFFFFF, Math.round);

doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUnsignedVarint32,
jspb.BinaryEncoder.prototype.writeUnsignedVarint32,
1, 0xFFFFFFFF, Math.round);

doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUint64,
jspb.BinaryEncoder.prototype.writeUint64,
1, Math.pow(2, 64) - 1025, Math.round);

doTestUnsignedValue(
jspb.BinaryDecoder.prototype.readUnsignedVarint64,
jspb.BinaryEncoder.prototype.writeUnsignedVarint64,
1, Math.pow(2, 64) - 1025, Math.round);
});


Expand All @@ -452,10 +462,20 @@ describe('binaryDecoderTest', function() {
jspb.BinaryEncoder.prototype.writeInt32,
1, -0x80000000, 0x7FFFFFFF, Math.round);

doTestSignedValue(
jspb.BinaryDecoder.prototype.readSignedVarint32,
jspb.BinaryEncoder.prototype.writeSignedVarint32,
1, -0x80000000, 0x7FFFFFFF, Math.round);

doTestSignedValue(
jspb.BinaryDecoder.prototype.readInt64,
jspb.BinaryEncoder.prototype.writeInt64,
1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);

doTestSignedValue(
jspb.BinaryDecoder.prototype.readSignedVarint64,
jspb.BinaryEncoder.prototype.writeSignedVarint64,
1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
});


Expand Down