* hostlong.ml: New file.
[elisp/liece.git] / dcc / hostlong.ml
1 type t = int32
2
3 let address_regexp =
4   let octet_regexp_string = "\([0-9][0-9]?[0-9]?\)" in
5   let address_regexp_string =
6     octet_regexp_string ^ "\." ^ octet_regexp_string ^ "\." ^
7     octet_regexp_string ^ "\." ^ octet_regexp_string
8   in
9   Str.regexp ("^" ^ address_regexp_string ^ "$")
10
11 let of_int32 = function n -> n
12
13 let to_int32 = function n -> n
14
15 let of_string = Int32.of_string
16
17 let to_string = Int32.to_string
18
19 let of_address_string string =
20   let n = ref Int32.zero in
21   if (Str.string_match address_regexp string 0) then
22     for i = 1 to 4 do
23       let octet = Int32.of_string (Str.matched_group i string) in
24       n := Int32.logor !n (Int32.shift_left octet (8 * (3 - i)))
25     done
26   else
27     failwith "hostlong_of_string";
28   !n
29
30 let to_address_string n =
31   let octets = ref [] in
32   let octet_mask = Int32.of_int 0xff in
33   for i = 0 to 3 do
34     let octet =
35       Int32.logand octet_mask (Int32.shift_right_logical n (i * 8))
36     in
37     octets := (Int32.to_string octet) :: !octets
38   done;
39   String.concat "." !octets