Skip to content

fix negative number decoding #1

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 3 commits into from
Jun 27, 2017
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
24 changes: 4 additions & 20 deletions lib/src/unpacker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -284,27 +284,11 @@ class Unpacker {
}

int unpackS16() {
var bytes = [
unpackU8(),
unpackU8()
];
var negate = (bytes[0] & 0x20) != 0;
var x = 0;
var o = 0;
var carry = 1;
for (var i = 1, m = 1; i >= 0; i--, m *= 256) {
var v = bytes[o + i];
int num = unpackU8() * 256 + unpackU8();
if (num > 0x7FFF)
return num - 0x10000;

if (negate) {
v = (v ^ 0xff) + carry;
carry = v >> 8;
v &= 0xff;
}

x += v * m;
}

return negate ? -x : x;
return num;
}

int unpackS8() {
Expand Down
29 changes: 27 additions & 2 deletions test/msgpack_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,13 @@ void main() {
test("Pack 5-character string", packString5);
test("Pack 22-character string", packString22);
test("Pack 256-character string", packString256);
test("Pack .NET SDK Test", packDSA);
test("Pack negative number -24577", packNegative1);
test("Pack negative number -245778641", packNegative2);
test("Pack string array", packStringArray);
test("Pack int-to-string map", packIntToStringMap);
test("Pack 3-field message", packMessage);
test("Pack nested message", packNestedMessage);
//test("Pack 3-field message", packMessage);
//test("Pack nested message", packNestedMessage);

test("Unpack 5-character string", unpackString5);
test("Unpack 22-character string", unpackString22);
Expand All @@ -58,6 +61,28 @@ void packString5() {
expect(encoded, orderedEquals([165, 104, 101, 108, 108, 111]));
}

void packDSA() {
// Use http://kawanet.github.io/msgpack-lite/ to test decode
// 81 A3 6D 73 67 D1 00 EB
List<int> testObjData = [0x81, 0xA3, 0x6D, 0x73, 0x67, 0xD1, 0x00, 0xEB];
Object obj=unpack(testObjData);
expect(unpack(testObjData)["msg"], 235);
}

void packNegative1() {
List<int> encoded = pack(-24577);
expect(encoded, orderedEquals([0xd1,0x9f,0xff]));
Object decoded = unpack(encoded);
expect(decoded, -24577);
}

void packNegative2() {
List<int> encoded = pack(-245778641);
expect(encoded, orderedEquals([0xd2,0xf1,0x59,0xb7,0x2f]));
Object decoded = unpack(encoded);
expect(decoded, -245778641);
}

void packString22() {
List<int> encoded = pack("hello there, everyone!");
expect(encoded, orderedEquals([
Expand Down