From ae6d81a9a428d885c5ba70cf9bff8c81d301d17f Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Tue, 7 Mar 2017 09:24:10 +0100 Subject: [PATCH] add `CCFormat.of_chan` --- src/core/CCFormat.ml | 12 ++++++++++++ src/core/CCFormat.mli | 10 ++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/core/CCFormat.ml b/src/core/CCFormat.ml index d68f53d3..03e68bb1 100644 --- a/src/core/CCFormat.ml +++ b/src/core/CCFormat.ml @@ -135,6 +135,18 @@ let fprintf = Format.fprintf let stdout = Format.std_formatter let stderr = Format.err_formatter +let of_chan = Format.formatter_of_out_channel + +let with_out_chan oc f = + let fmt = of_chan oc in + try + let x = f fmt in + Format.pp_print_flush fmt (); + x + with e -> + Format.pp_print_flush fmt (); + raise e + let tee a b = let fa = Format.pp_get_formatter_out_functions a () in let fb = Format.pp_get_formatter_out_functions b () in diff --git a/src/core/CCFormat.mli b/src/core/CCFormat.mli index 02be1976..fdbe2be5 100644 --- a/src/core/CCFormat.mli +++ b/src/core/CCFormat.mli @@ -184,6 +184,16 @@ val with_color_sf : string -> ('a, t, unit, string) format4 -> 'a val output : t -> 'a printer -> 'a -> unit val to_string : 'a printer -> 'a -> string +val of_chan : out_channel -> t +(** Alias to {!Format.formatter_of_out_channel} + @since NEXT_RELEASE *) + +val with_out_chan : out_channel -> (t -> 'a) -> 'a +(** [with_out_chan oc f] turns [oc] into a formatter [fmt], and call [f fmt]. + Behaves like [f fmt] from then on, but whether the call to [f] fails + or returns, [fmt] is flushed before the call terminates. + @since NEXT_RELEASE *) + val stdout : t val stderr : t