forked from ocaml/ocaml-lsp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiber_io.ml
52 lines (41 loc) · 1.25 KB
/
fiber_io.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
open Import
open Fiber.O
module Lio = Lev_fiber.Io
type t = Lio.input Lio.t * Lio.output Lio.t * Fiber.Mutex.t
module Io =
Io.Make
(struct
include Fiber
let raise exn = raise exn
end)
(struct
type input = Lio.Reader.t
type output = Lio.Writer.t
let read_line ic =
let+ res = Lio.Reader.read_line ic in
match res with
| Ok s -> Some s
| Error (`Partial_eof _) -> None
let read_exactly ic len =
let+ res = Lio.Reader.read_exactly ic len in
match res with
| Ok s -> Some s
| Error (`Partial_eof _) -> None
let write oc strings =
Fiber.of_thunk (fun () ->
List.iter strings ~f:(Lio.Writer.add_string oc);
Fiber.return ())
end)
let send (_, oc, m) packets =
Fiber.Mutex.with_lock m ~f:(fun () ->
Lio.with_write oc ~f:(fun writer ->
let* () = Fiber.sequential_iter packets ~f:(Io.write writer) in
Lio.Writer.flush writer))
let recv (ic, _, _) = Lio.with_read ic ~f:Io.read
let make ic oc = (ic, oc, Fiber.Mutex.create ())
let close (ic, oc, _) what =
Fiber.of_thunk (fun () ->
(match what with
| `Write -> Lio.close oc
| `Read -> Lio.close ic);
Fiber.return ())