Source file decode.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
open Decoders
module M = Msgpck

module Msgpck_decodeable : Decode.Decodeable with type value = Msgpck.t = struct
  type value = Msgpck.t

  let pp fmt t = Format.fprintf fmt "@[%a@]" Msgpck.pp t

  let of_string (input : string) : (value, string) result =
    try Ok (snd @@ M.StringBuf.read input) with Invalid_argument s -> Error s


  let of_file (file : string) : (value, string) result =
    try
      Ok
        (Util.with_file_in file (fun chan ->
             Util.read_all chan |> M.StringBuf.read |> snd ) )
    with
    | e ->
        Error (Printexc.to_string e)


  let get_string = function M.String str | M.Bytes str -> Some str | _ -> None

  (* note: the other int constructors are only used for values that do
     not fit in [int]. *)
  let get_int = function M.Int int -> Some int | _ -> None

  let get_float = function
    | M.Float float ->
        Some float
    | M.Float32 f ->
        Some (Int32.float_of_bits f)
    | _ ->
        None


  let get_null = function M.Nil -> Some () | _ -> None

  let get_bool = function M.Bool bool -> Some bool | _ -> None

  let get_list = function M.List a -> Some a | _ -> None

  let get_key_value_pairs = function M.Map assoc -> Some assoc | _ -> None

  let to_list vs = M.List vs
end

include Decode.Make (Msgpck_decodeable)

let string_strict : string decoder = function
  | M.String b ->
      Ok b
  | m ->
      (fail "Expected string (strict)") m


let bytes : string decoder = function
  | M.Bytes b ->
      Ok b
  | m ->
      (fail "Expected bytes") m


let int32 : _ decoder = function
  | M.Int32 i ->
      Ok i
  | m ->
      (fail "Expected int32") m


let int64 : _ decoder = function
  | M.Int64 i ->
      Ok i
  | m ->
      (fail "Expected int64") m


let uint32 : _ decoder = function
  | M.Uint32 i ->
      Ok i
  | m ->
      (fail "Expected uint32") m


let uint64 : _ decoder = function
  | M.Uint64 i ->
      Ok i
  | m ->
      (fail "Expected uint64") m


let ext : (int * string) decoder = function
  | M.Ext (i, s) ->
      Ok (i, s)
  | m ->
      (fail "Expected extension") m