1 (***********************************************************************)
2 (* The OcamlEvent library *)
4 (* Copyright 2002, 2003 Maas-Maarten Zeeman. All rights reserved. See *)
5 (* LICENCE for details. *)
6 (***********************************************************************)
8 (* $Id: liboevent.ml,v 1.1 2009-11-26 08:49:02 maas Exp $ *)
18 let int_of_event_type = function
24 let event_type_of_int = function
28 | 6 -> READ
(* READ|WRITE *)
30 | n
-> raise
(Invalid_argument
(Printf.sprintf
"event_type %d" n
))
32 type event_callback
= Unix.file_descr
-> event_flags
-> unit
34 (* Use an internal hashtable to store the ocaml callbacks with the
36 let table = Hashtbl.create
0
38 (* Called by the c-stub, locate, and call the ocaml callback *)
39 let event_cb event_id fd etype
=
40 (Hashtbl.find
table event_id
) fd
(event_type_of_int etype
)
43 external create
: event_base
-> event
= "oc_create_event"
45 (* Return the id of an event *)
46 external event_id
: event
-> int = "oc_event_id"
48 (* Return the signal associated with the event *)
49 external signal
: event
-> int = "oc_event_fd"
51 (* Return the fd associated with the event *)
52 external fd
: event
-> Unix.file_descr
= "oc_event_fd"
54 (* Set an event (not exported) *)
55 external cset_fd
: event
-> Unix.file_descr
-> int -> unit = "oc_event_set"
56 external cset_int
: event
-> int -> int -> unit = "oc_event_set"
58 let persist_flag = function true -> 0x10 | false -> 0
61 let set event fd etype persist
(cb
: event_callback
) =
62 let rec int_of_event_type_list flag
= function
63 h
::t
-> int_of_event_type_list (flag
lor (int_of_event_type h
)) t
66 let flag = int_of_event_type_list (persist_flag persist
) etype
in
67 Hashtbl.replace
table (event_id event
) cb
;
70 let set_timer event persist
(cb
: unit -> unit) =
71 let flag = persist_flag persist
in
72 Hashtbl.replace
table (event_id event
) (fun _ _
-> cb
());
73 cset_int event
(-1) flag
75 let set_signal event signal persist
(cb
: event_callback
) =
76 let flag = (int_of_event_type SIGNAL
) lor (persist_flag persist
) in
77 Hashtbl.replace
table (event_id event
) cb
;
78 cset_int event signal
flag
81 external add
: event
-> float option -> unit = "oc_event_add"
84 external cdel
: event
-> unit = "oc_event_del"
86 Hashtbl.remove
table (event_id event
);
90 (* Not fully implemented yet *)
91 external pending
: event
-> event_flags list
-> bool = "oc_event_pending"
94 external dispatch
: event_base
-> unit = "oc_event_base_dispatch"
96 type loop_flags
= ONCE
| NONBLOCK
97 external loop
: event_base
-> loop_flags
-> unit = "oc_event_base_loop"
99 external init
: unit -> event_base
= "oc_event_base_init"
100 external reinit
: event_base
-> unit = "oc_event_base_reinit"
101 external free
: event_base
-> unit = "oc_event_base_free"
104 Callback.register
"event_cb" event_cb
107 module Global
= struct
110 let init () = reinit
base
112 let create () = create base
113 let dispatch () = dispatch base