lwt_pipe: better output to buffer/string

This commit is contained in:
Simon Cruanes 2015-02-20 17:37:38 +01:00
parent f9d32d0af2
commit 1be3bcf766
2 changed files with 27 additions and 19 deletions

View file

@ -53,6 +53,7 @@ module LwtErr = struct
) x
end
let (>>>=) = LwtErr.(>>=)
let (>>|=) = LwtErr.(>|=)
let ret_end = Lwt.return `End
@ -341,21 +342,24 @@ let to_list_exn r =
| `Error msg -> Lwt.fail (Failure msg)
| `Ok x -> Lwt.return x
let to_buffer buf =
let p = create () in
keep p (
Reader.iter ~f:(fun c -> Buffer.add_char buf c) p >>= fun _ ->
Lwt.return_unit
);
p
let to_buffer buf r =
Reader.iter ~f:(fun c -> Buffer.add_char buf c) r
let to_buffer_str buf =
let p = create () in
keep p (
Reader.iter ~f:(fun s -> Buffer.add_string buf s) p >>= fun _ ->
Lwt.return_unit
);
p
let to_buffer_str ?(sep="") buf r =
let first = ref true in
Reader.iter r
~f:(fun s ->
if !first then first:= false else Buffer.add_string buf sep;
Buffer.add_string buf s
)
let to_string r =
let buf = Buffer.create 128 in
to_buffer buf r >>>= fun () -> LwtErr.return (Buffer.contents buf)
let join_strings ?sep r =
let buf = Buffer.create 128 in
to_buffer_str ?sep buf r >>>= fun () -> LwtErr.return (Buffer.contents buf)
(** {2 Basic IO wrappers} *)

View file

@ -170,17 +170,21 @@ val of_array : 'a array -> 'a Reader.t
val of_string : string -> char Reader.t
val to_list_rev : 'a Reader.t -> 'a list LwtErr.t
val to_list_rev : ('a,[>`r]) t -> 'a list LwtErr.t
val to_list : 'a Reader.t -> 'a list LwtErr.t
val to_list : ('a,[>`r]) t -> 'a list LwtErr.t
val to_list_exn : 'a Reader.t -> 'a list Lwt.t
val to_list_exn : ('a,[>`r]) t -> 'a list Lwt.t
(** Same as {!to_list}, but can fail with
@raise Failure if some error is met *)
val to_buffer : Buffer.t -> char Writer.t
val to_buffer : Buffer.t -> (char ,[>`r]) t -> unit LwtErr.t
val to_buffer_str : Buffer.t -> string Writer.t
val to_buffer_str : ?sep:string -> Buffer.t -> (string, [>`r]) t -> unit LwtErr.t
val to_string : (char, [>`r]) t -> string LwtErr.t
val join_strings : ?sep:string -> (string, [>`r]) t -> string LwtErr.t
(** {2 Basic IO wrappers} *)