Added integer matching test.
[ocaml-bitstring.git] / tests / 11_match_ints.ml
1 (* Match random bits with integers.
2  * $Id$
3  *)
4
5 open Printf
6
7 let rec range a b =
8   if a <= b then
9     a :: range (a+1) b
10   else
11     []
12
13 let () =
14   Random.self_init ();
15
16   for len = 1 to 99 do
17     for bitlen = 1 to 63 do
18       (* Create a random string of ints. *)
19       let expected =
20         List.map (fun _ ->
21                     Random.int64 (Int64.sub (Int64.shift_left 1L bitlen) 1L))
22           (range 0 (len-1)) in
23
24       let bits = Bitmatch.Buffer.create () in
25       List.iter (fun i ->
26                    Bitmatch.construct_int64_be_unsigned bits i bitlen
27                      (Failure "constructing string"))
28         expected;
29       let bits = Bitmatch.Buffer.contents bits in
30
31       (* Now read the bitstring as integers.
32        * In each case check the result against what we generated ('expected').
33        *)
34       let actual =
35         let rec loop bits =
36           bitmatch bits with
37           | { i : bitlen; rest : -1 : bitstring } ->
38               if Bitmatch.bitstring_length rest > 0 then
39                 i :: loop rest
40               else
41                 [i]
42           | { _ } ->
43               failwith (sprintf "loop failed with len = %d, bitlen = %d"
44                           len bitlen)
45         in
46         loop bits in
47       if actual <> expected then
48         failwith (sprintf "match bits: failed on 1 bit test, len = %d" len)
49     done
50   done