Source file current_plugin.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
open Ctypes

type t = unit ptr
type memory_block = { offs : Unsigned.UInt64.t; len : Unsigned.UInt64.t }

let memory ?(offs = Unsigned.UInt64.zero) t =
  Bindings.extism_current_plugin_memory t +@ Unsigned.UInt64.to_int offs

let find t offs =
  let len = Bindings.extism_current_plugin_memory_length t offs in
  if Unsigned.UInt64.(equal zero len) then None else Some { offs; len }

let alloc t len =
  let len = Unsigned.UInt64.of_int len in
  let offs = Bindings.extism_current_plugin_memory_alloc t len in
  { offs; len }

let free t { offs; _ } = Bindings.extism_current_plugin_memory_free t offs

module Memory_block = struct
  let of_val t v =
    match Types.Val.to_i64 v with
    | None -> None
    | Some v ->
        let offs = Unsigned.UInt64.of_int64 v in
        find t offs

  let of_val_exn t v =
    match of_val t v with
    | None -> invalid_arg "Memory_block.of_val_exn"
    | Some v -> v

  let to_val { offs; len = _ } =
    Types.Val.of_i64 (Unsigned.UInt64.to_int64 offs)

  let get_bigstring t { offs; len } : Bigstringaf.t =
    let p = memory t ~offs in
    bigarray_of_ptr array1
      (Unsigned.UInt64.to_int len)
      Bigarray.Char
      (coerce (ptr uint8_t) (ptr char) p)

  let get_string t { offs; len } =
    let p = memory t ~offs in
    Ctypes.string_from_ptr
      (coerce (ptr uint8_t) (ptr char) p)
      ~length:(Unsigned.UInt64.to_int len)

  let set_bigstring t { offs; len } bs =
    let length = min (Unsigned.UInt64.to_int @@ len) (Bigstringaf.length bs) in
    let p = coerce (ptr uint8_t) (ptr char) @@ memory t ~offs in
    for i = 0 to length - 1 do
      p +@ i <-@ Bigstringaf.unsafe_get bs i
    done

  let set_string t { offs; len } s =
    let length = min (Unsigned.UInt64.to_int @@ len) (String.length s) in
    let p = coerce (ptr uint8_t) (ptr char) @@ memory t ~offs in
    for i = 0 to length - 1 do
      p +@ i <-@ String.unsafe_get s i
    done
end