Remove CVS $Id$ strings.
[ocaml-ancient.git] / test_ancient_dict_read.ml
1 (* Read shared dictionary. *)
2
3 open Printf
4 open Unix
5
6 let argv = Array.to_list Sys.argv
7
8 let datafile =
9   match argv with
10   | [_; datafile] ->
11       datafile
12   | _ ->
13       failwith (sprintf "usage: %s datafile"
14                   Sys.executable_name)
15
16 let md =
17   let fd = openfile datafile [O_RDWR] 0o644 in
18   Ancient.attach fd 0n
19
20 let arraysize = 256 (* one element for each character *)
21
22 type t = Not_Found | Exists of t array | Not_Exists of t array;;
23 let tree : t array Ancient.ancient = Ancient.get md 0
24 let tree = Ancient.follow tree
25
26 let word_exists word =
27   try
28     let tree = ref tree in
29     let len = String.length word in
30     for i = 0 to len-2; do
31       let c = word.[i] in
32       let c = Char.code c in
33       match (!tree).(c) with
34       | Not_Found -> raise Not_found
35       | Exists tree'
36       | Not_Exists tree' -> tree := tree'
37     done;
38
39     (* Final character. *)
40     let c = word.[len-1] in
41     let c = Char.code c in
42     match (!tree).(c) with
43     | Not_Found
44     | Not_Exists _ -> false
45     | Exists _ -> true
46   with
47     Not_found -> false
48
49 let () =
50   let rec loop () =
51     printf "Enter a word to check (q = quit program): ";
52     let word = read_line () in
53     if word <> "q" then (
54       printf "'%s' exists? %B\n%!" word (word_exists word);
55       loop ()
56     )
57   in
58   loop ();
59
60   Ancient.detach md;
61
62   (* Garbage collect - good way to check we haven't broken anything. *)
63   Gc.compact ();
64
65   printf "Program finished.\n"