add Event abstraction in Util

This commit is contained in:
Simon Cruanes 2022-07-17 20:20:46 -04:00
parent 633a658e0c
commit 833fa8e038
No known key found for this signature in database
GPG key ID: EBFFF6F283F3A2B4
2 changed files with 26 additions and 0 deletions

14
src/util/Event.ml Normal file
View file

@ -0,0 +1,14 @@
type 'a handler = 'a -> unit
type 'a t = { h: 'a handler Vec.t } [@@unboxed]
let nop_handler_ = ignore
module Emitter = struct
type nonrec 'a t = 'a t
let emit (self : _ t) x : unit = Vec.iter self.h ~f:(fun h -> h x)
let create () : _ t = { h = Vec.make 3 nop_handler_ }
end
let on self f = Vec.push self.h f
let of_emitter x = x

12
src/util/Event.mli Normal file
View file

@ -0,0 +1,12 @@
type 'a t
(** An event emitting values of type ['a] *)
module Emitter : sig
type 'a t
val emit : 'a t -> 'a -> unit
val create : unit -> 'a t
end
val on : 'a t -> ('a -> unit) -> unit
val of_emitter : 'a Emitter.t -> 'a t