Skip to content

Commit

Permalink
tls-lwt: read add an optional ?off argument (#510)
Browse files Browse the repository at this point in the history
* tls-lwt: read has an optional ?off argument
* add a check for off, as proposed by @reynir
  • Loading branch information
hannesm authored Aug 29, 2024
1 parent 64547f9 commit b8dad2f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
10 changes: 6 additions & 4 deletions lwt/tls_lwt.ml
Original file line number Diff line number Diff line change
Expand Up @@ -153,12 +153,14 @@ module Unix = struct
handle tls (String.sub (Bytes.unsafe_to_string t.recv_buf) 0 n)
| `Closed -> Lwt.return `Eof

let rec read t buf =
let rec read t ?(off = 0) buf =
if off < 0 || off >= Bytes.length buf then
invalid_arg "offset must be >= 0 and < Bytes.length buf";

let writeout res =
let rlen = String.length res in
let n = min (Bytes.length buf) rlen in
Bytes.blit_string res 0 buf 0 n ;
let n = min (Bytes.length buf - off) rlen in
Bytes.blit_string res 0 buf off n ;
t.linger <-
(if n < rlen then Some (String.sub res n (rlen - n)) else None) ;
Lwt.return n in
Expand All @@ -168,7 +170,7 @@ module Unix = struct
| None ->
read_react t >>= function
| `Eof -> Lwt.return 0
| `Ok None -> read t buf
| `Ok None -> read t ~off buf
| `Ok (Some res) -> writeout res

let writev t css =
Expand Down
8 changes: 4 additions & 4 deletions lwt/tls_lwt.mli
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@ module Unix : sig

(** {2 Common stream operations} *)

(** [read t buffer] is [length], the number of bytes read into
[buffer]. *)
val read : t -> bytes -> int Lwt.t
(** [read t ~off buffer] is [length], the number of bytes read into
[buffer]. It fills [buffer] starting at [off] (default is 0). *)
val read : t -> ?off:int -> bytes -> int Lwt.t

(** [write t buffer] writes the [buffer] to the session. *)
val write : t -> string -> unit Lwt.t
val write : t -> string -> unit Lwt.t

(** [writev t buffers] writes the [buffers] to the session. *)
val writev : t -> string list -> unit Lwt.t
Expand Down

0 comments on commit b8dad2f

Please sign in to comment.