Skip to content

Commit 2271dde

Browse files
committed
fix leb128 slice bug
1 parent 42c4f1c commit 2271dde

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

src/leb128/containers_leb128.ml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ module Decode = struct
1414
while !continue do
1515
if sl.len <= 0 then invalid_arg "out of bound";
1616
incr n_consumed;
17-
let b = Char.code (Bytes.get sl.bs !off) in
17+
let b = Char.code (Bytes.get sl.bs (sl.off + !off)) in
1818
let cur = b land 0x7f in
1919
if cur <> b then (
2020
(* at least one byte follows this one *)
@@ -39,7 +39,7 @@ module Decode = struct
3939
while !continue do
4040
if sl.len <= 0 then invalid_arg "out of bound";
4141
incr n_consumed;
42-
let b = Char.code (Bytes.get sl.bs !off) in
42+
let b = Char.code (Bytes.get sl.bs (sl.off + !off)) in
4343
let cur = b land 0x7f in
4444
if cur <> b then (
4545
(* at least one byte follows this one *)

tests/leb128/t_leb128.ml

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,5 +226,44 @@ assert_equal ~printer:Int64.to_string 500L v2;
226226
assert_equal ~printer:string_of_int 2 n1;
227227
assert_equal ~printer:string_of_int 2 n2;
228228
true
229+
;;
230+
231+
t @@ fun () ->
232+
(* Test decoding from a slice with non-zero offset *)
233+
let bytes = Bytes.of_string "\x00\x00\x54\x00" in
234+
let slice = Slice.create ~off:2 ~len:1 bytes in
235+
assert_equal
236+
~printer:(fun c -> Printf.sprintf "0x%02x" (Char.code c))
237+
'\x54' (Slice.get slice 0);
238+
let v, n = Leb128.Decode.int_truncate slice 0 in
239+
assert_equal ~printer:string_of_int 42 v;
240+
assert_equal ~printer:string_of_int 1 n;
241+
true
242+
;;
243+
244+
t @@ fun () ->
245+
(* Test decoding u64 from a slice with non-zero offset *)
246+
let bytes = Bytes.of_string "\xFF\xFF\x2A\x00" in
247+
let slice = Slice.create ~off:2 ~len:1 bytes in
248+
assert_equal
249+
~printer:(fun c -> Printf.sprintf "0x%02x" (Char.code c))
250+
'\x2A' (Slice.get slice 0);
251+
let v, n = Leb128.Decode.u64 slice 0 in
252+
assert_equal ~printer:Int64.to_string 42L v;
253+
assert_equal ~printer:string_of_int 1 n;
254+
true
255+
;;
256+
257+
t @@ fun () ->
258+
(* Test decoding from a sub-slice *)
259+
let buf = Buf.create () in
260+
Buf.append_string buf "padding";
261+
Leb128.Encode.int buf 42;
262+
let slice = Buf.to_slice buf in
263+
let sub_slice = Slice.sub slice 7 (Slice.len slice - 7) in
264+
let v, n = Leb128.Decode.int_truncate sub_slice 0 in
265+
assert_equal ~printer:string_of_int 42 v;
266+
assert_equal ~printer:string_of_int 1 n;
267+
true
229268

230269
let () = Containers_testlib.run_all ~descr:"test leb128" [ get () ]

0 commit comments

Comments
 (0)