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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
open! Import
let src = Logs.Src.create "irmin.layers.io" ~doc:"IO for irmin-layers"
module Log = (val Logs.src_log src : Logs.LOG)
module type S = sig
type t
val v : string -> t Lwt.t
val close : t -> unit Lwt.t
val read_flip : t -> bool Lwt.t
val write_flip : bool -> t -> unit Lwt.t
end
module IO = struct
type t = { file : string; fd : Lwt_unix.file_descr }
let lseek ~offset t =
let* off = Lwt_unix.lseek t.fd offset Lwt_unix.SEEK_SET in
if off <> offset then Lwt.fail_with "invalid lseek" else Lwt.return_unit
let write ~offset t buf =
lseek ~offset t >>= fun () ->
let len = Bytes.length buf in
let* n = Lwt_unix.write t.fd buf 0 len in
if n <> len then Lwt.fail_with "invalid write" else Lwt.return_unit
let read ~offset t buf =
lseek ~offset t >>= fun () ->
let len = Bytes.length buf in
let* n = Lwt_unix.read t.fd buf 0 len in
if n <> len then Lwt.fail_with "invalid read" else Lwt.return_unit
let close t = Lwt_unix.close t.fd
let read_flip t =
let buf = Bytes.create 1 in
read ~offset:0 t buf >>= fun () ->
let ch = Bytes.get buf 0 in
match int_of_char ch with
| 0 -> Lwt.return_false
| 1 -> Lwt.return_true
| d -> Lwt.fail_with ("corrupted flip file " ^ string_of_int d)
let write_flip flip t =
let buf = Bytes.make 1 (char_of_int (if flip then 1 else 0)) in
write ~offset:0 t buf
let v file =
match Sys.file_exists file with
| false ->
let* fd =
Lwt_unix.openfile file Lwt_unix.[ O_CREAT; O_RDWR; O_CLOEXEC ] 0o644
in
let t = { file; fd } in
write_flip true t >|= fun () -> t
| true ->
Lwt_unix.openfile file Lwt_unix.[ O_EXCL; O_RDWR; O_CLOEXEC ] 0o644
>|= fun fd -> { file; fd }
end
module Lock = struct
type t = { file : string; fd : Lwt_unix.file_descr }
let v file =
let pid = string_of_int (Unix.getpid ()) in
let* fd =
Lwt_unix.openfile file Unix.[ O_CREAT; O_WRONLY; O_TRUNC ] 0o644
in
let* n = Lwt_unix.write_string fd pid 0 (String.length pid) in
if n <> String.length pid then Lwt.fail_with "invalid write for lock file"
else Lwt.return { file; fd }
let test = Sys.file_exists
let unlink = Lwt_unix.unlink
let close { fd; file } = Lwt_unix.close fd >>= fun () -> unlink file
end