aboutsummaryrefslogtreecommitdiffstats
path: root/lib/protocols/Handle.ml
blob: 9fd1f29a031a7ac4600333fc61b5bc681cb0777c (plain) (blame)
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
type protocol = ..

class type obj = object
  method reference : bool
  method release : unit
  method protocols : protocol list
end

type t = { valid : bool ref; refers_to : obj }

type 'a interface = { handle : t; interface : 'a }

let object_of { valid; refers_to } =
  if !valid then
    refers_to
  else
    failwith "Attempt to dereference an invalid handle!"

let interface_of handle interface = { handle; interface }

let make o = { valid = ref true; refers_to = (o :> obj) }

let into handle f =
  List.find_map f (object_of handle)#protocols
  |> Option.map (interface_of handle)

let invoke { handle; interface } f =
  let _ = object_of handle in
  f interface

let copy handle =
  let o = object_of handle in
  if o#reference then
    Some (make o)
  else
    None

let release ({ valid; _ } as handle) =
  let o = object_of handle in
  valid := false;
  o#release