add CCIO.read_all_bytes, reading a whole file into a Bytes.t

This commit is contained in:
Simon Cruanes 2015-06-26 14:02:14 +02:00
parent d817ec8d02
commit 0ac0f89e93
2 changed files with 24 additions and 4 deletions

View file

@ -116,7 +116,14 @@ let read_lines_l ic =
with End_of_file -> with End_of_file ->
List.rev !l 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 buf = ref (Bytes.create size) in
let len = ref 0 in let len = ref 0 in
try try
@ -132,7 +139,13 @@ let read_all ?(size=1024) ic =
done; done;
assert false (* never reached*) assert false (* never reached*)
with Exit -> 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 with_out ?(mode=0o644) ?(flags=[Open_creat; Open_trunc; Open_text]) filename f =
let oc = open_out_gen (Open_wronly::flags) mode filename in let oc = open_out_gen (Open_wronly::flags) mode filename in

View file

@ -56,7 +56,8 @@ Examples:
@since 0.6 @since 0.6
in 'containers' (rather than 'containers.io') 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 val read_all : ?size:int -> in_channel -> string
(** Read the whole channel into a buffer, then converted into a 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} *) (** {6 Output} *)