Fix string_of_bitstring/add_bits handling of non-multiple-of-8-bit length strings...
[ocaml-bitstring.git] / tests / 30_bitbuffer.ml
1 (* Test the Bitmatch.Buffer module and string_of_bitstring in
2  * nasty non-aligned corner cases.
3  * $Id$
4  *)
5
6 open Printf
7
8 let () =
9   Random.self_init ();
10
11   let str1 = "012345678" in
12
13   for offset = 0 to 65 do
14     for len = 1 to 65 do
15       let expected =
16         let strlen = (len+7) lsr 3 in
17         let expected = String.create strlen in
18         for i = 0 to strlen-1 do
19           expected.[i] <- Char.chr (Random.int 256)
20         done;
21         let last = Char.code expected.[strlen-1] in
22         let last = last land (0xff lsl (8 - (len land 7))) in
23         expected.[strlen-1] <- Char.chr last;
24         expected in
25
26       (* Create a random bitstring:
27        * +-------------+-------------------------------------------+
28        * | (random)    | bits that we check (expected)             |
29        * +-------------+-------------------------------------------+
30        * 0           offset                                    offset+len
31        *                <---------------- len bits --------------->
32        *)
33       let bits =
34         let bits = Bitmatch.Buffer.create () in
35         Bitmatch.Buffer.add_bits bits str1 offset;
36         Bitmatch.Buffer.add_bits bits expected len;
37         Bitmatch.Buffer.contents bits in
38
39       (* Create a sub bitstring corresponding to what we want to check. *)
40       let subbits =
41         let bits, bitoffset, bitlen = bits in
42         (bits, bitoffset+offset, bitlen-offset) in
43
44       assert (Bitmatch.bitstring_length subbits = len);
45
46       (* Now try to read out the substring using string_of_bitstring. *)
47       let actual = Bitmatch.string_of_bitstring subbits in
48       if actual <> expected then (
49         eprintf "MISMATCH between actual and expected, offset=%d, len=%d\n"
50           offset len;
51         eprintf "EXPECTED string:\n";
52         for i = 0 to String.length expected-1 do
53           eprintf " %02x" (Char.code expected.[i])
54         done;
55         eprintf "\nACTUAL string:\n";
56         for i = 0 to String.length actual-1 do
57           eprintf " %02x" (Char.code actual.[i])
58         done;
59         eprintf "\nBITS:\n";
60         Bitmatch.hexdump_bitstring stderr bits;
61         eprintf "SUBBITS:\n";
62         Bitmatch.hexdump_bitstring stderr subbits;
63         exit 1
64       );
65     done
66   done