diff --git a/src/utils/lwt_utils.ml b/src/utils/lwt_utils.ml index cee2b3f7b..399045db6 100644 --- a/src/utils/lwt_utils.ml +++ b/src/utils/lwt_utils.ml @@ -224,3 +224,36 @@ let stable_sort cmp l = if len < 2 then Lwt.return l else sort len l let sort = stable_sort + +let rec read_bytes ?(pos = 0) ?len fd buf = + let len = match len with None -> Bytes.length buf - pos | Some l -> l in + let rec inner pos len = + if len = 0 then + Lwt.return_unit + else + Lwt_unix.read fd buf pos len >>= fun nb_read -> + inner (pos + nb_read) (len - nb_read) + in + inner pos len + +let read_mbytes ?(pos=0) ?len fd buf = + let len = match len with None -> MBytes.length buf - pos | Some l -> l in + let rec inner pos len = + if len = 0 then + Lwt.return_unit + else + Lwt_bytes.read fd buf pos len >>= fun nb_read -> + inner (pos + nb_read) (len - nb_read) + in + inner pos len + +let write_mbytes ?(pos=0) ?len descr buf = + let len = match len with None -> MBytes.length buf - pos | Some l -> l in + let rec inner pos len = + if len = 0 then + Lwt.return_unit + else + Lwt_bytes.write descr buf pos len >>= fun nb_written -> + inner (pos + nb_written) (len - nb_written) in + inner pos len + diff --git a/src/utils/lwt_utils.mli b/src/utils/lwt_utils.mli index b3ddc40fa..96c77b86a 100644 --- a/src/utils/lwt_utils.mli +++ b/src/utils/lwt_utils.mli @@ -24,3 +24,12 @@ val worker: val trigger: unit -> (unit -> unit) * (unit -> unit Lwt.t) val queue: unit -> ('a -> unit) * (unit -> 'a list Lwt.t) val sort: ('a -> 'a -> int Lwt.t) -> 'a list -> 'a list Lwt.t + +val read_bytes: + ?pos:int -> ?len:int -> Lwt_unix.file_descr -> bytes -> unit Lwt.t + +val read_mbytes: + ?pos:int -> ?len:int -> Lwt_unix.file_descr -> MBytes.t -> unit Lwt.t + +val write_mbytes: + ?pos:int -> ?len:int -> Lwt_unix.file_descr -> MBytes.t -> unit Lwt.t