Release notes and some test programs.
[ocaml-ancient.git] / test_ancient_dict_verify.ml
1 (* Verify shared dictionary.
2  * $Id: test_ancient_dict_verify.ml,v 1.1 2006-10-06 15:03:47 rich Exp $
3  *)
4
5 open Printf
6 open Unix
7
8 let argv = Array.to_list Sys.argv
9
10 let wordsfile, datafile =
11   match argv with
12   | [_; wordsfile; datafile] ->
13       wordsfile, datafile
14   | _ ->
15       failwith (sprintf "usage: %s wordsfile datafile"
16                   Sys.executable_name)
17
18 let md =
19   let fd = openfile datafile [O_RDWR] 0o644 in
20   Ancient.attach fd 0n
21
22 let arraysize = 256 (* one element for each character *)
23
24 type t = Not_Found | Exists of t array | Not_Exists of t array;;
25 let tree : t array Ancient.ancient = Ancient.get md 0
26 let tree = Ancient.follow tree
27
28 let word_exists word =
29   try
30     let tree = ref tree in
31     let len = String.length word in
32     for i = 0 to len-2; do
33       let c = word.[i] in
34       let c = Char.code c in
35       match (!tree).(c) with
36       | Not_Found -> raise Not_found
37       | Exists tree'
38       | Not_Exists tree' -> tree := tree'
39     done;
40
41     (* Final character. *)
42     let c = word.[len-1] in
43     let c = Char.code c in
44     match (!tree).(c) with
45     | Not_Found
46     | Not_Exists _ -> false
47     | Exists _ -> true
48   with
49     Not_found -> false
50
51 let () =
52   (* Read in the words and keep in a local list. *)
53   let words = ref [] in
54   let chan = open_in wordsfile in
55   let rec loop () =
56     let word = input_line chan in
57     if word <> "" then words := word :: !words;
58     loop ()
59   in
60   (try loop () with End_of_file -> ());
61   close_in chan;
62   let words = List.rev !words in
63
64   (* Verify that the number of words in the tree is the same as the
65    * number of words in the words file.
66    *)
67   let nr_expected = List.length words in
68   let nr_actual =
69     let rec count tree =
70       let c = ref 0 in
71       for i = 0 to arraysize-1 do
72         match tree.(i) with
73         | Not_Found -> ()
74         | Exists tree ->
75             c := !c + 1 + count tree
76         | Not_Exists tree ->
77             c := !c + count tree
78       done;
79       !c
80     in
81     count tree in
82
83   if nr_expected <> nr_actual then
84     failwith (sprintf
85                 "verify failed: expected %d words but counted %d in tree"
86                 nr_expected nr_actual);
87
88   (* Check each word exists in the tree. *)
89   List.iter (
90     fun word ->
91       if not (word_exists word) then
92         failwith (sprintf "verify failed: word '%s' missing from tree" word)
93   ) words;
94
95   Ancient.detach md;
96
97   (* Garbage collect - good way to check we haven't broken anything. *)
98   Gc.compact ();
99
100   printf "Verification succeeded.\n"