Improved 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               when Bitmatch.bitstring_length rest = 0 -> [i]
39           | { i : bitlen; rest : -1 : bitstring } -> i :: loop rest
40           | { _ } ->
41               failwith (sprintf "loop failed with len = %d, bitlen = %d"
42                           len bitlen)
43         in
44         loop bits in
45       if actual <> expected then
46         failwith (sprintf "match ints: failed on test, len = %d, bitlen = %d"
47                     len bitlen)
48     done
49   done