From 0ac0f89e93d5df158364fd20cc36a8b8dfb5e025 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Fri, 26 Jun 2015 14:02:14 +0200 Subject: [PATCH] add `CCIO.read_all_bytes`, reading a whole file into a `Bytes.t` --- src/core/CCIO.ml | 17 +++++++++++++++-- src/core/CCIO.mli | 11 +++++++++-- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/core/CCIO.ml b/src/core/CCIO.ml index 20dc6ade..9f6b1123 100644 --- a/src/core/CCIO.ml +++ b/src/core/CCIO.ml @@ -116,7 +116,14 @@ let read_lines_l ic = with End_of_file -> List.rev !l -let read_all ?(size=1024) ic = +(* thanks to nicoo for this trick *) +type _ ret_type = + | Ret_string : string ret_type + | Ret_bytes : Bytes.t ret_type + +let read_all_ +: type a. op:a ret_type -> size:int -> in_channel -> a += fun ~op ~size ic -> let buf = ref (Bytes.create size) in let len = ref 0 in try @@ -132,7 +139,13 @@ let read_all ?(size=1024) ic = done; assert false (* never reached*) with Exit -> - Bytes.sub_string !buf 0 !len + match op with + | Ret_string -> Bytes.sub_string !buf 0 !len + | Ret_bytes -> Bytes.sub !buf 0 !len + +let read_all_bytes ?(size=1024) ic = read_all_ ~op:Ret_bytes ~size ic + +let read_all ?(size=1024) ic = read_all_ ~op:Ret_string ~size ic let with_out ?(mode=0o644) ?(flags=[Open_creat; Open_trunc; Open_text]) filename f = let oc = open_out_gen (Open_wronly::flags) mode filename in diff --git a/src/core/CCIO.mli b/src/core/CCIO.mli index 377e7a74..b41f6160 100644 --- a/src/core/CCIO.mli +++ b/src/core/CCIO.mli @@ -56,7 +56,8 @@ Examples: @since 0.6 in 'containers' (rather than 'containers.io') -@since NEXT_RELEASE + +@since NEXT_RELEASE *) @@ -87,7 +88,13 @@ val read_lines_l : in_channel -> string list val read_all : ?size:int -> in_channel -> string (** Read the whole channel into a buffer, then converted into a string. - @param size the internal buffer size @since 0.7 *) + @param size the internal buffer size + @since 0.7 *) + +val read_all_bytes : ?size:int -> in_channel -> Bytes.t +(** Read the whole channel into a mutable byte array + @param size the internal buffer size + @since NEXT_RELEASE *) (** {6 Output} *)