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 *)
47 let expect ic fname s =
48 let len = String.length s in
49 let buf = String.create len in
50 really_input ic buf 0 len;
51 if buf <> s then raise (Corrupt_file fname)
53 let load ~fmt ~version ~fname =
54 let ic = open_in fname in
56 (fun () -> close_in ic)
59 let fmt' = input_binary_int ic in (* field 1 *)
60 if fmt' <> Hashtbl.hash fmt then raise (Format_mismatch fname);
61 let version' = input_binary_int ic in (* field 2 *)
62 if version' <> version then raise (Version_mismatch fname);
63 expect ic fname fmt; (* field 3 *)
64 expect ic fname (string_of_int version); (* field 4 *)
65 let checksum' = input_binary_int ic in (* field 5 *)
66 let marshalled' = HExtlib.input_all ic in (* field 6 *)
67 if checksum' <> Hashtbl.hash marshalled' then
68 raise (Corrupt_file fname);
69 Marshal.from_string marshalled' 0
70 with End_of_file -> raise (Corrupt_file fname))