1 (* Copyright (C) 2005, HELM Team.
3 * This file is part of HELM, an Hypertextual, Electronic
4 * Library of Mathematics, developed at the Computer Science
5 * Department, University of Bologna, Italy.
7 * HELM is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * HELM is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with HELM; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
28 exception Corrupt_file of string
29 exception Format_mismatch of string
30 exception Version_mismatch of string
32 let ensure_path_exists fname = HExtlib.mkdir (Filename.dirname fname)
33 let marshal_flags = []
35 let save ~fmt ~version ~fname data =
36 ensure_path_exists fname;
37 let oc = open_out fname in
38 let marshalled = Marshal.to_string data marshal_flags in
39 output_binary_int oc (Hashtbl.hash fmt); (* field 1 *)
40 output_binary_int oc version; (* field 2 *)
41 output_string oc fmt; (* field 3 *)
42 output_string oc (string_of_int version); (* field 4 *)
43 output_binary_int oc (Hashtbl.hash marshalled); (* field 5 *)
44 output_string oc marshalled; (* field 6 *)
46 HExtlib.chmod 0o664 fname
48 let expect ic fname s =
49 let len = String.length s in
50 let buf = String.create len in
51 really_input ic buf 0 len;
52 if buf <> s then raise (Corrupt_file fname)
54 let load ~fmt ~version ~fname =
55 let ic = open_in fname in
57 (fun () -> close_in ic)
60 let fmt' = input_binary_int ic in (* field 1 *)
61 if fmt' <> Hashtbl.hash fmt then raise (Format_mismatch fname);
62 let version' = input_binary_int ic in (* field 2 *)
63 if version' <> version then raise (Version_mismatch fname);
64 expect ic fname fmt; (* field 3 *)
65 expect ic fname (string_of_int version); (* field 4 *)
66 let checksum' = input_binary_int ic in (* field 5 *)
67 let marshalled' = HExtlib.input_all ic in (* field 6 *)
68 if checksum' <> Hashtbl.hash marshalled' then
69 raise (Corrupt_file fname);
70 Marshal.from_string marshalled' 0
71 with End_of_file -> raise (Corrupt_file fname))