Source file ipaddr_cstruct.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
let need_more x = Ipaddr.Parse_error ("not enough data", x)
let try_with_result fn a =
try Ok (fn a)
with Ipaddr.Parse_error (msg, _) -> Error (`Msg ("Ipaddr: " ^ msg))
module V4 = struct
let of_cstruct_exn cs =
let len = Cstruct.length cs in
if len < 4 then raise (need_more (Cstruct.to_string cs));
Ipaddr.V4.of_int32 (Cstruct.BE.get_uint32 cs 0)
let of_cstruct cs = try_with_result of_cstruct_exn cs
let write_cstruct_exn i cs =
let len = Cstruct.length cs in
if len < 4 then raise (need_more (Cstruct.to_string cs));
Cstruct.BE.set_uint32 cs 0 (Ipaddr.V4.to_int32 i)
let to_cstruct ?(allocator = Cstruct.create) i =
let cs = allocator 4 in
write_cstruct_exn i cs;
cs
end
module V6 = struct
open Ipaddr.V6
let of_cstruct_exn cs =
let len = Cstruct.length cs in
if len < 16 then raise (need_more (Cstruct.to_string cs));
of_octets_exn (Cstruct.to_string ~len:16 cs)
let of_cstruct cs = try_with_result of_cstruct_exn cs
let write_cstruct_exn i cs =
let len = Cstruct.length cs in
if len < 16 then raise (need_more (Cstruct.to_string cs));
Cstruct.blit_from_string (to_octets i) 0 cs 0 16
let to_cstruct ?(allocator = Cstruct.create) i =
let cs = allocator 16 in
write_cstruct_exn i cs;
cs
end