From 437852d18e0643206e21bcdc49af9373c0fd425f Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Mon, 26 Oct 2015 09:52:01 +0100 Subject: [PATCH] add `CCFormat.{ksprintf,string_quoted}` --- src/core/CCFormat.ml | 9 +++++++++ src/core/CCFormat.mli | 19 ++++++++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/core/CCFormat.ml b/src/core/CCFormat.ml index 419569ce..c294d91a 100644 --- a/src/core/CCFormat.ml +++ b/src/core/CCFormat.ml @@ -46,6 +46,7 @@ let char = Format.pp_print_char let int32 fmt n = Format.fprintf fmt "%ld" n let int64 fmt n = Format.fprintf fmt "%Ld" n let nativeint fmt n = Format.fprintf fmt "%nd" n +let string_quoted fmt s = Format.fprintf fmt "\"%s\"" s let list ?(start="[") ?(stop="]") ?(sep=", ") pp fmt l = let rec pp_list l = match l with @@ -132,6 +133,14 @@ let sprintf format = let fprintf = Format.fprintf + +let ksprintf ~f fmt = + let buf = Buffer.create 32 in + let out = Format.formatter_of_buffer buf in + Format.kfprintf + (fun _ -> Format.pp_print_flush out (); f (Buffer.contents buf)) + out fmt + let stdout = Format.std_formatter let stderr = Format.err_formatter diff --git a/src/core/CCFormat.mli b/src/core/CCFormat.mli index a53185e8..3e836ad8 100644 --- a/src/core/CCFormat.mli +++ b/src/core/CCFormat.mli @@ -49,6 +49,9 @@ val int32 : int32 printer (** @since NEXT_RELEASE *) val int64 : int64 printer (** @since NEXT_RELEASE *) val nativeint : nativeint printer (** @since NEXT_RELEASE *) +val string_quoted : string printer +(** Similar to {!CCString.print}. + @since NEXT_RELEASE *) val list : ?start:string -> ?stop:string -> ?sep:string -> 'a printer -> 'a list printer val array : ?start:string -> ?stop:string -> ?sep:string -> 'a printer -> 'a array printer @@ -73,11 +76,25 @@ val stdout : t val stderr : t val sprintf : ('a, t, unit, string) format4 -> 'a -(** print into a string *) +(** Print into a string any format string that would usually be compatible + with {!fprintf}. Similar to {!Format.asprintf}. *) val fprintf : t -> ('a, t, unit ) format -> 'a (** Alias to {!Format.fprintf} @since NEXT_RELEASE *) +val ksprintf : + f:(string -> 'b) -> + ('a, Format.formatter, unit, 'b) format4 -> + 'a +(** [ksprintf fmt ~f] formats using [fmt], in a way similar to {!sprintf}, + and then calls [f] on the resulting string. + @since NEXT_RELEASE *) + +(*$= & ~printer:CCFormat.(to_string (opt string)) + (Some "hello world") \ + (ksprintf "hello %a" CCFormat.string "world" ~f:(fun s -> Some s)) +*) + val to_file : string -> ('a, t, unit, unit) format4 -> 'a (** Print to the given file *)