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

fix issue #38 - decode negative int32 #39

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
19 changes: 19 additions & 0 deletions pb/standard/unpack.lua
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,26 @@ local function unpack_varint64(data, off, max_off, signed)
return num, off + 1
end

local function unpack_neg_varint32(data, off, max_off)
local boff = 1
local num = 0
local bits35 = 34359738368 -- 2^(5*7)
for i = 1, 5 do
num = num + (band(data:byte(off), 0x7F) * boff)
off = off + 1
boff = boff * 128
end
while data:byte(off) >= 128 do
off = off + 1
end
return num - bits35, off + 1
end

local function unpack_varint32(data, off, max_off)
local b = data:byte(off)
local num = band(b, 0x7F)
local boff = 128
local start_off = off
while b >= 128 do
off = off + 1
if off > max_off then
Expand All @@ -129,6 +145,9 @@ local function unpack_varint32(data, off, max_off)
num = num + (band(b, 0x7F) * boff)
boff = boff * 128
end
if off - start_off + 1 == 10 then
return unpack_neg_varint32(data, start_off, max_off)
end
return num, off + 1
end

Expand Down
4 changes: 4 additions & 0 deletions protos/int32.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
message TestInt32
{
optional int32 int32_ = 1;
}
13 changes: 13 additions & 0 deletions tests/test_negative_int32.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
local pb = require"pb"
local value = -1
local integer32 = require"protos.int32"

local msg = integer32.TestInt32()
msg.int32_ = value;
binary,err = msg:Serialize();
assert(not err)

local decoded = integer32.TestInt32():Parse(binary)
assert(decoded:IsInitialized())
assert(decoded:HasField('int32_'))
assert(value == decoded.int32_)