package extism

  1. Overview
  2. Docs

Source file type.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
module type S = sig
  type t

  val encode : t -> string
  val decode : Bigstringaf.t -> (t, Error.t) result
end

module Unit = struct
  type t = unit

  let encode () = ""
  let decode _ = Ok ()
end

let unit = (module Unit : S with type t = unit)

module Int32 = struct
  type t = int32

  let encode i =
    let b = Bytes.create 4 in
    Bytes.set_int32_le b 0 i;
    String.of_bytes b

  let decode bs = Ok (Bigstringaf.get_int32_le bs 0)
end

let int32 = (module Int32 : S with type t = Int32.t)

module Int64 = struct
  type t = int64

  let encode i =
    let b = Bytes.create 4 in
    Bytes.set_int64_le b 0 i;
    String.of_bytes b

  let decode bs = Ok (Bigstringaf.get_int64_le bs 0)
end

let int64 = (module Int64 : S with type t = Int64.t)

module Int = struct
  type t = int

  let encode i = Int64.encode (Stdlib.Int64.of_int i)
  let decode bs = Int64.decode bs |> Result.map Stdlib.Int64.to_int
end

let int = (module Int : S with type t = int)

module Float32 = struct
  type t = float

  let encode f = Int32.encode (Stdlib.Int32.bits_of_float f)
  let decode bs = Int32.decode bs |> Result.map Stdlib.Int32.float_of_bits
end

let float32 = (module Float32 : S with type t = float)

module Float64 = struct
  type t = float

  let encode f = Int64.encode (Stdlib.Int64.bits_of_float f)
  let decode bs = Int64.decode bs |> Result.map Stdlib.Int64.float_of_bits
end

let float64 = (module Float64 : S with type t = float)

module String = struct
  type t = string

  let encode = Fun.id
  let decode x = Ok (Bigstringaf.to_string x)
end

let string = (module String : S with type t = string)

module Bytes = struct
  type t = bytes

  let encode = Bytes.to_string

  let decode bs =
    let len = Bigstringaf.length bs in
    let bytes = Bytes.make len ' ' in
    Bigstringaf.blit_to_bytes bs ~src_off:0 bytes ~dst_off:0 ~len;
    Ok bytes
end

let bytes = (module Bytes : S with type t = bytes)

module Bigstring = struct
  type t = Bigstringaf.t

  let encode = Bigstringaf.to_string
  let decode bs = Ok bs
end

let bigstring = (module Bigstring : S with type t = Bigstringaf.t)

module Json = struct
  type t = Yojson.Safe.t

  let encode x = Yojson.Safe.to_string x

  let decode bs =
    try Ok (Yojson.Safe.from_string (Bigstringaf.to_string bs))
    with exc -> Error (`Msg (Printexc.to_string exc))
end

let json = (module Json : S with type t = Yojson.Safe.t)