]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/extlib/hExtlib.ml
1. Parameter enable (default true) added to HExtlib.profile
[helm.git] / helm / ocaml / extlib / hExtlib.ml
1 (* Copyright (C) 2005, HELM Team.
2  * 
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.
6  * 
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.
11  * 
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.
16  *
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,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26
27 (** PROFILING *)
28
29 let profiling_enabled = true
30
31 type profiler = { profile : 'a 'b. ('a -> 'b) -> 'a -> 'b }
32 let profile ?(enable = true) =
33  if profiling_enabled && enable then
34   function s ->
35    let total = ref 0.0 in
36    let profile f x =
37     let before = Unix.gettimeofday () in
38     try
39      let res = f x in
40      let after = Unix.gettimeofday () in
41       total := !total +. (after -. before);
42       res
43     with
44      exc ->
45       let after = Unix.gettimeofday () in
46        total := !total +. (after -. before);
47        raise exc
48    in
49    at_exit
50     (fun () ->
51       print_endline
52        ("!! TOTAL TIME SPENT IN " ^ s ^ ": " ^ string_of_float !total));
53    { profile = profile }
54  else
55   function _ -> { profile = fun f x -> f x }
56
57 (** {2 Optional values} *)
58
59 let map_option f = function None -> None | Some v -> Some (f v)
60 let iter_option f = function None -> () | Some v -> f v
61 let unopt = function None -> failwith "unopt: None" | Some v -> v
62
63 (** {2 String processing} *)
64
65 let split ?(sep = ' ') s =
66   let pieces = ref [] in
67   let rec aux idx =
68     match (try Some (String.index_from s idx sep) with Not_found -> None) with
69     | Some pos ->
70         pieces := String.sub s idx (pos - idx) :: !pieces;
71         aux (pos + 1)
72     | None -> pieces := String.sub s idx (String.length s - idx) :: !pieces
73   in
74   aux 0;
75   List.rev !pieces
76
77 let trim_blanks s =
78   let rec find_left idx =
79     match s.[idx] with
80     | ' ' | '\t' | '\r' | '\n' -> find_left (idx + 1)
81     | _ -> idx
82   in
83   let rec find_right idx =
84     match s.[idx] with
85     | ' ' | '\t' | '\r' | '\n' -> find_right (idx - 1)
86     | _ -> idx
87   in
88   let s_len = String.length s in
89   let left, right = find_left 0, find_right (s_len - 1) in
90   String.sub s left (right - left + 1)
91
92 (** {2 List processing} *)
93
94 let rec list_uniq = function 
95   | [] -> []
96   | h::[] -> [h]
97   | h1::h2::tl when h1 = h2 -> list_uniq (h2 :: tl) 
98   | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq tl
99
100 let rec filter_map f =
101   function
102   | [] -> []
103   | hd :: tl ->
104       (match f hd with
105       | None -> filter_map f tl
106       | Some v -> v :: filter_map f tl)
107
108 let list_concat ?(sep = []) =
109   let rec aux acc =
110     function
111     | [] -> []
112     | [ last ] -> List.flatten (List.rev (last :: acc))
113     | hd :: tl -> aux ([sep; hd] @ acc) tl
114   in
115   aux []
116
117 (** {2 File predicates} *)
118
119 let is_dir fname =
120   try
121     (Unix.stat fname).Unix.st_kind = Unix.S_DIR
122   with Unix.Unix_error _ -> false
123
124 let is_regular fname =
125   try
126     (Unix.stat fname).Unix.st_kind = Unix.S_REG
127   with Unix.Unix_error _ -> false
128
129 let mkdir path =
130   let components = split ~sep:'/' path in
131   let rec aux where = function
132     | [] -> ()
133     | piece::tl -> 
134         let path = where ^ "/" ^ piece in
135         (try
136           Unix.mkdir path 0o755
137         with 
138         | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
139         | Unix.Unix_error (e,_,_) -> 
140             raise 
141               (Failure 
142                 ("Unix.mkdir " ^ path ^ " 0o755 :" ^ (Unix.error_message e))));
143         aux path tl
144   in
145   aux "" components
146
147 (** {2 Filesystem} *)
148
149 let input_file fname =
150   let size = (Unix.stat fname).Unix.st_size in
151   let buf = Buffer.create size in
152   let ic = open_in fname in
153   Buffer.add_channel buf ic size;
154   close_in ic;
155   Buffer.contents buf
156
157 let input_all ic =
158   let size = 10240 in
159   let buf = Buffer.create size in
160   let s = String.create size in
161   (try
162     while true do
163       let bytes = input ic s 0 size in
164       if bytes = 0 then raise End_of_file
165       else Buffer.add_substring buf s 0 bytes
166     done
167   with End_of_file -> ());
168   Buffer.contents buf
169
170 let output_file ~filename ~text = 
171   let oc = open_out filename in
172   output_string oc text;
173   close_out oc
174   
175 let find ?(test = fun _ -> true) path = 
176   let rec aux acc todo = 
177     match todo with
178     | [] -> acc
179     | path :: tl ->
180         try
181           let handle = Unix.opendir path in
182           let dirs = ref [] in
183           let matching_files = ref [] in 
184           (try 
185             while true do 
186               match Unix.readdir handle with
187               | "." | ".." -> ()
188               | entry ->
189                   let qentry = path ^ "/" ^ entry in
190                   (try
191                     if is_dir qentry then
192                       dirs := qentry :: !dirs
193                     else if test qentry then
194                       matching_files := qentry :: !matching_files;
195                   with Unix.Unix_error _ -> ())
196             done
197           with End_of_file -> Unix.closedir handle);
198           aux (!matching_files @ acc) (!dirs @ tl)
199         with Unix.Unix_error _ -> aux acc tl
200   in
201   aux [] [path]
202
203 (** {2 Exception handling} *)
204
205 let finally at_end f arg =
206   let res =
207     try f arg
208     with exn -> at_end (); raise exn
209   in
210   at_end ();
211   res
212