File: 11_match_ints.ml

package info (click to toggle)
ocaml-bitstring 2.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 1,276 kB
  • ctags: 492
  • sloc: ml: 3,360; sh: 377; makefile: 324; ansic: 113
file content (49 lines) | stat: -rw-r--r-- 1,297 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
(* Match random bits with integers.
 * $Id: 11_match_ints.ml 142 2008-07-17 15:45:56Z richard.wm.jones $
 *)

open Printf

let rec range a b =
  if a <= b then
    a :: range (a+1) b
  else
    []

let () =
  Random.self_init ();

  for len = 1 to 99 do
    for bitlen = 1 to 63 do
      (* Create a random string of ints. *)
      let expected =
	List.map (fun _ ->
		    Random.int64 (Int64.sub (Int64.shift_left 1L bitlen) 1L))
	  (range 0 (len-1)) in

      let bits = Bitstring.Buffer.create () in
      List.iter (fun i ->
		   Bitstring.construct_int64_be_unsigned bits i bitlen
		     (Failure "constructing string"))
	expected;
      let bits = Bitstring.Buffer.contents bits in

      (* Now read the bitstring as integers.
       * In each case check the result against what we generated ('expected').
       *)
      let actual =
	let rec loop bits =
	  bitmatch bits with
	  | { i : bitlen; rest : -1 : bitstring }
	      when Bitstring.bitstring_length rest = 0 -> [i]
	  | { i : bitlen; rest : -1 : bitstring } -> i :: loop rest
	  | { _ } ->
	      failwith (sprintf "loop failed with len = %d, bitlen = %d"
			  len bitlen)
	in
	loop bits in
      if actual <> expected then
	failwith (sprintf "match ints: failed on test, len = %d, bitlen = %d"
		    len bitlen)
    done
  done