From 3f80e794ba57481895eb829db3ae28e83b05e9ee Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Wed, 11 Jan 2017 18:38:37 +0100 Subject: [PATCH] add `CCFormat.tee` --- src/core/CCFormat.ml | 20 ++++++++++++++++++++ src/core/CCFormat.mli | 4 ++++ 2 files changed, 24 insertions(+) diff --git a/src/core/CCFormat.ml b/src/core/CCFormat.ml index 85ec6bfc..3ec8956a 100644 --- a/src/core/CCFormat.ml +++ b/src/core/CCFormat.ml @@ -130,6 +130,26 @@ let fprintf = Format.fprintf let stdout = Format.std_formatter let stderr = Format.err_formatter +let tee a b = + let fa = Format.pp_get_formatter_out_functions a () in + let fb = Format.pp_get_formatter_out_functions b () in + Format.make_formatter + (fun str i len -> + fa.Format.out_string str i len; + fb.Format.out_string str i len) + (fun () -> fa.Format.out_flush (); fb.Format.out_flush ()) + +(*$R + let buf1 = Buffer.create 42 in + let buf2 = Buffer.create 42 in + let f1 = Format.formatter_of_buffer buf1 in + let f2 = Format.formatter_of_buffer buf2 in + let fmt = tee f1 f2 in + Format.fprintf fmt "coucou@."; + assert_equal ~printer:CCFun.id "coucou\n" (Buffer.contents buf1); + assert_equal ~printer:CCFun.id "coucou\n" (Buffer.contents buf2); + *) + let to_file filename format = let oc = open_out filename in let fmt = Format.formatter_of_out_channel oc in diff --git a/src/core/CCFormat.mli b/src/core/CCFormat.mli index 9b6546a5..dce09267 100644 --- a/src/core/CCFormat.mli +++ b/src/core/CCFormat.mli @@ -155,6 +155,10 @@ val to_string : 'a printer -> 'a -> string val stdout : t val stderr : t +val tee : t -> t -> t +(** [tee a b] makes a new formatter that writes in both [a] and [b]. + @since NEXT_RELEASE *) + val sprintf : ('a, t, unit, string) format4 -> 'a (** Print into a string any format string that would usually be compatible with {!fprintf}. Similar to {!Format.asprintf}. *)