@@ -80,6 +80,10 @@ module Forest = Tree.Forest
80
80
module Json = Json
81
81
82
82
module Io_utils = struct
83
+ (* * [with_open_*] are resource safe wrappers around opening and closing
84
+ channels. They are equivalent to the same functions in OCaml 4.14's
85
+ [In_channel] and [Out_channel]. *)
86
+
83
87
let _with_resource res ~close f =
84
88
Fun. protect ~finally: (fun () -> close res) (fun () -> f res)
85
89
@@ -89,6 +93,7 @@ module Io_utils = struct
89
93
let with_open_in_bin fname f =
90
94
_with_resource (open_in_bin fname) ~close: close_in_noerr f
91
95
96
+ (* * Read a file line-by-line by folding [f]. *)
92
97
let fold_lines fname f acc =
93
98
_with_resource (open_in fname) ~close: close_in_noerr (fun ic ->
94
99
let rec loop acc =
@@ -98,6 +103,7 @@ module Io_utils = struct
98
103
in
99
104
loop acc)
100
105
106
+ (* * Read a file as a list of lines. *)
101
107
let read_lines fname =
102
108
List. rev (fold_lines fname (fun line acc -> line :: acc) [] )
103
109
@@ -107,16 +113,15 @@ module Io_utils = struct
107
113
let with_open_out_bin fname f =
108
114
_with_resource (open_out_bin fname) ~close: close_out_noerr f
109
115
116
+ (* * Like [with_open_out] but operate on a [Format] buffer. *)
110
117
let with_formatter_out fname f =
111
118
with_open_out fname (fun oc -> f (Format. formatter_of_out_channel oc))
112
119
120
+ (* * Shortcuts for composing [with_open_*] functions and [Marshal]. *)
113
121
let marshal fname v =
114
- _with_resource (open_out_bin fname) ~close: close_out_noerr (fun oc ->
115
- Marshal. to_channel oc v [] )
122
+ with_open_out_bin fname (fun oc -> Marshal. to_channel oc v [] )
116
123
117
- let unmarshal fname =
118
- _with_resource (open_in_bin fname) ~close: close_in_noerr
119
- Marshal. from_channel
124
+ let unmarshal fname = with_open_in_bin fname Marshal. from_channel
120
125
end
121
126
122
127
include Astring
0 commit comments