Source file reparse_lwt_unix.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
(*-------------------------------------------------------------------------
 * Copyright (c) 2020, 2021 Bikal Gurung. All rights reserved.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License,  v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 *
 * reparse v3.0.1
 *-------------------------------------------------------------------------*)

open Lwt.Infix

module Promise = struct
  type 'a t = 'a Lwt.t

  let return = Lwt.return
  let bind f p = Lwt.bind p f
  let catch = Lwt.catch
end

module type READER = sig
  type t

  val read_into_bigstring :
    t -> Cstruct.buffer -> off:int -> len:int -> int Lwt.t
end

module Make_parser (Reader : READER) = struct
  module Input =
    Reparse.Make_buffered_input
      (Promise)
      (struct
        type t = Reader.t
        type 'a promise = 'a Lwt.t

        let read t ~len =
          let buf = Cstruct.create len in
          Reader.read_into_bigstring t buf.buffer ~off:0 ~len
          >|= fun read_count ->
          if read_count <= 0 then `Eof
          else if read_count < len then `Cstruct (Cstruct.sub buf 0 read_count)
          else `Cstruct buf
      end)

  include Reparse.Make (Promise) (Input)
end

module Fd = struct
  module Reader = struct
    type t = Lwt_unix.file_descr

    let read_into_bigstring t buf ~off ~len = Lwt_bytes.read t buf off len
  end

  include Make_parser (Reader)

  let create_input file_descr = Input.create file_descr
end

module Channel = struct
  module Reader = struct
    type t = Lwt_io.input_channel

    let read_into_bigstring t buf ~off ~len =
      Lwt_io.read_into_bigstring t buf off len
  end

  include Make_parser (Reader)

  let create_input channel = Input.create channel
end