Skip to content

Commit b545ac8

Browse files
authored
Merge pull request #134 from varomodt/fix-signed-varint32-decoding
Fix decoding of signed varint32s.
2 parents 314f4fb + 674f9c7 commit b545ac8

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

binary/decoder.js

+6-4
Original file line numberDiff line numberDiff line change
@@ -481,13 +481,15 @@ jspb.BinaryDecoder.prototype.readUnsignedVarint32 = function() {
481481

482482

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

492494

493495
/**

binary/decoder_test.js

+20
Original file line numberDiff line numberDiff line change
@@ -426,10 +426,20 @@ describe('binaryDecoderTest', function() {
426426
jspb.BinaryEncoder.prototype.writeUint32,
427427
1, 0xFFFFFFFF, Math.round);
428428

429+
doTestUnsignedValue(
430+
jspb.BinaryDecoder.prototype.readUnsignedVarint32,
431+
jspb.BinaryEncoder.prototype.writeUnsignedVarint32,
432+
1, 0xFFFFFFFF, Math.round);
433+
429434
doTestUnsignedValue(
430435
jspb.BinaryDecoder.prototype.readUint64,
431436
jspb.BinaryEncoder.prototype.writeUint64,
432437
1, Math.pow(2, 64) - 1025, Math.round);
438+
439+
doTestUnsignedValue(
440+
jspb.BinaryDecoder.prototype.readUnsignedVarint64,
441+
jspb.BinaryEncoder.prototype.writeUnsignedVarint64,
442+
1, Math.pow(2, 64) - 1025, Math.round);
433443
});
434444

435445

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

465+
doTestSignedValue(
466+
jspb.BinaryDecoder.prototype.readSignedVarint32,
467+
jspb.BinaryEncoder.prototype.writeSignedVarint32,
468+
1, -0x80000000, 0x7FFFFFFF, Math.round);
469+
455470
doTestSignedValue(
456471
jspb.BinaryDecoder.prototype.readInt64,
457472
jspb.BinaryEncoder.prototype.writeInt64,
458473
1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
474+
475+
doTestSignedValue(
476+
jspb.BinaryDecoder.prototype.readSignedVarint64,
477+
jspb.BinaryEncoder.prototype.writeSignedVarint64,
478+
1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
459479
});
460480

461481

0 commit comments

Comments
 (0)