4 #include <sys/types.h> // timeval (hack -> event.h don't include it)
5 #include <stdexcept> // std::exception, std::invalid_argument,
6 // std::runtime_error, std::bad_alloc
10 * @section Introduction
12 * The libevent API provides a mechanism to execute a callback function when a
13 * specific event occurs on a file descriptor or after a timeout has been
14 * reached. Furthermore, libevent also support callbacks due to signals or
17 * libevent is meant to replace the event loop found in event driven network
18 * servers. An application just needs to call dispatcher::dispatch() and then
19 * add or remove events dynamically without having to change the event loop.
21 * Currently, libevent supports /dev/poll, kqueue(2), select(2), poll(2) and
22 * epoll(4). It also has experimental support for real-time signals. The
23 * internal event mechanism is completely independent of the exposed event API,
24 * and a simple update of libevent can provide new functionality without having
25 * to redesign the applications. As a result, Libevent allows for portable
26 * application development and provides the most scalable event notification
27 * mechanism available on an operating system. Libevent should compile on Linux,
28 * *BSD, Mac OS X, Solaris and Windows.
30 * This is a simple, direct, one-header inline C++ wrapper for libevent.
31 * It's designed to be as close to use to libevent without compromising modern
32 * C++ programming techniques and efficiency (since all implementation is
33 * trivial and inline, theoretically, it imposes no overhead at all).
38 * The best way to explain how this works is by examples. TODO
40 * @author Leandro Lucarella <llucarella@integratech.com.ar>
43 * This program is under the BOLA license (see
44 * http://auriga.wearlab.de/~alb/bola/)
50 * Namespace for all symbols libevent C++ wrapper defines.
56 // All libevent C API symbols and other internal stuff goes here.
63 /// @defgroup exceptions Exceptions
68 * Base class for all libevent exceptions.
70 struct exception: std::exception
76 * Invalid event exception.
78 * This exception is thrown when passing an invalid event to a function, the
79 * reason is given in the what() description but it usually means that the you
80 * are making some restricted operation with an active event.
82 * If you hit this exception, you probably got a programming error.
84 struct invalid_event: std::invalid_argument, exception
88 * Creates an invalid event exception with a reason.
90 * @param what Reason why the event is invalid).
92 explicit invalid_event(const std::string& what) throw():
93 std::invalid_argument(what)
97 }; // struct invalid_event
101 * Invalid priority exception.
103 * This exception is thrown when passing an invalid priority to a function. This
104 * usually means you don't have enought priority queues in your dispatcher, so
105 * you should have allocated more in the constructor.
107 * If you hit this exception, you probably got a programming error.
109 * @see dispatcher::dispatcher(int) to allocate more priority queues.
111 struct invalid_priority: std::invalid_argument, exception
115 * Creates an invalid priority exception with a reason.
117 * @param what Reason why the priority is invalid).
119 explicit invalid_priority(const std::string& what
120 = "invalid priority value") throw():
121 std::invalid_argument(what)
125 }; // struct invalid_priority
130 /// Miscelaneous constants
133 DEFAULT_PRIORITY = -1 ///< Default priority (the middle value)
137 /// C function used as callback in the C API.
138 typedef void (*ccallback_type)(int, short, void*);
142 * Time used for timeout values.
144 * This timeout is compose of seconds and microseconds.
146 struct time: ::timeval
150 * Creates a new time with @p sec seconds and @p usec microseconds.
152 * @param sec Number of seconds.
153 * @param usec Number of microseconds.
155 time(long sec = 0l, long usec = 0l) throw()
156 { tv_sec = sec; tv_usec = usec; }
159 * Gets the number of seconds.
161 * @return Number of seconds.
163 long sec() const throw() { return tv_sec; };
166 * Gets the number of microseconds.
168 * @return Number of microseconds.
170 long usec() const throw() { return tv_usec; };
173 * Sets the number of seconds.
175 * @param s Number of seconds.
177 void sec(long s) throw() { tv_sec = s; };
180 * Sets the number of microseconds.
182 * @param u Number of microseconds.
184 void usec(long u) throw() { tv_usec = u; };
189 /// @defgroup events Events
193 * Basic event from which all events derive.
195 * All events derive from this class, so it's useful for use in containers,
198 * std::list< event::basic_event* > events;
201 struct basic_event: internal::event
205 * Checks if there is an event pending.
207 * @param ev Type of event to check.
209 * @return true if there is a pending event, false if not.
211 bool pending(short ev) const throw()
213 // HACK libevent don't use const
214 return event_pending(const_cast< basic_event* >(this), ev, 0);
218 * Timeout of the event.
220 * @return Timeout of the event.
222 time timeout() const throw()
225 // HACK libevent don't use const
226 event_pending(const_cast< basic_event* >(this), EV_TIMEOUT, &tv);
231 * Sets the event's priority.
233 * @param priority New event priority.
235 * @see dispatcher::dispatcher(int)
237 void priority(int priority) const throw(invalid_event, invalid_priority)
239 if (ev_flags & EVLIST_ACTIVE)
240 throw invalid_event("can't change the priority of an "
242 // HACK libevent don't use const
243 if (event_priority_set(const_cast< basic_event* >(this),
245 throw invalid_priority();
249 * Event's file descriptor.
251 * @return Event's file descriptor.
253 int fd() const throw()
255 return EVENT_FD(this);
258 /// @note This is an abstract class, you can't instantiate it.
260 basic_event() throw() {}
261 basic_event(const basic_event&);
262 basic_event& operator= (const basic_event&);
264 }; // struct basic_event
268 * Generic event object.
270 * This object stores all the information about an event, incluiding a callback
271 * functor, which is called then the event is fired. Then template parameter
272 * must be a callable object (functor) that can take 2 parameters: an integer
273 * (the file descriptor of the fired event) and a short (the type of event
274 * fired: EV_TIMEOUT, EV_SIGNAL, EV_READ, EV_WRITE). There is an specialized
275 * version of this class which takes as the template parameter a C function
276 * with the ccallback_type signature, just like C libevent API does.
278 * @see event::event< ccallback_type >
280 template < typename F >
281 struct event: basic_event
285 * Creates a new event.
287 * @param fd File descriptor to monitor for events.
288 * @param ev Type of events to monitor.
289 * @param handler Callback functor.
290 * @param priority Priority of the event.
292 event(int fd, short ev, F& handler, int priority = DEFAULT_PRIORITY)
293 throw(invalid_priority)
295 event_set(this, fd, ev, &wrapper, reinterpret_cast< void* >(&handler));
296 if (priority != DEFAULT_PRIORITY
297 && event_priority_set(this, priority))
298 throw invalid_priority();
303 static void wrapper(int fd, short ev, void* h)
305 F& handler = *reinterpret_cast< F* >(h);
309 }; // struct event< F >
313 * This is the specialization of event::event for C-style callbacks.
318 struct event< ccallback_type >: basic_event
322 * Creates a new event.
324 * @param fd File descriptor to monitor for events.
325 * @param ev Type of events to monitor.
326 * @param handler C-style callback function.
327 * @param arg Arbitrary pointer to pass to the handler as argument.
328 * @param priority Priority of the event.
330 event(int fd, short ev, ccallback_type handler, void* arg,
331 int priority = DEFAULT_PRIORITY)
332 throw(invalid_priority)
334 event_set(this, fd, ev, handler, arg);
335 if (priority != DEFAULT_PRIORITY
336 && event_priority_set(this, priority))
337 throw invalid_priority();
343 }; // struct event< ccallback_type >
347 * Timer event object.
349 * This is just a special case of event that is fired only when a timeout is
350 * reached. It's just a shortcut to event(-1, 0, handler, priority).
352 * @note This event can't EV_PERSIST.
353 * @see timer< ccallback_type >
355 template < typename F >
356 struct timer: event< F >
360 * Creates a new timer event.
362 * @param handler Callback functor.
363 * @param priority Priority of the event.
365 timer(F& handler, int priority = DEFAULT_PRIORITY)
366 throw(invalid_priority)
368 evtimer_set(this, &event< F >::wrapper,
369 reinterpret_cast< void* >(&handler));
370 if (priority != DEFAULT_PRIORITY
371 && event_priority_set(this, priority))
372 throw invalid_priority();
375 }; // struct timer< F >
379 * This is the specialization of event::timer for C-style callbacks.
381 * @note This event can't EV_PERSIST.
385 struct timer< ccallback_type >: event::event< ccallback_type >
389 * Creates a new timer event.
391 * @param handler C-style callback function.
392 * @param arg Arbitrary pointer to pass to the handler as argument.
393 * @param priority Priority of the event.
395 timer(ccallback_type handler, void* arg, int priority = DEFAULT_PRIORITY)
396 throw(invalid_priority)
398 evtimer_set(this, handler, arg);
399 if (priority != DEFAULT_PRIORITY
400 && event_priority_set(this, priority))
401 throw invalid_priority();
404 }; // struct timer< ccallback_type >
408 * Signal event object.
410 * This is just a special case of event that is fired when a signal is raised
411 * (instead of a file descriptor being active). It's just a shortcut to
412 * event(signal, EV_SIGNAL, handler, priority).
414 * @note This event allways EV_PERSIST.
415 * @see signal< ccallback_type >
417 template < typename F >
418 struct signal: event< F >
422 * Creates a new singal event.
424 * @param signum Signal number to monitor.
425 * @param handler Callback functor.
426 * @param priority Priority of the event.
428 signal(int signum, F& handler, int priority = DEFAULT_PRIORITY)
429 throw(invalid_priority)
431 signal_set(this, signum, &event< F >::wrapper,
432 reinterpret_cast< void* >(&handler));
433 if (priority != DEFAULT_PRIORITY
434 && event_priority_set(this, priority))
435 throw invalid_priority();
439 * Event's signal number.
441 * @return Event's signal number.
445 return EVENT_SIGNAL(this);
448 }; // struct signal<F>
452 * This is the specialization of event::signal for C-style callbacks.
454 * @note This event allways EV_PERSIST.
458 struct signal< ccallback_type >: event< ccallback_type >
462 * Creates a new signal event.
464 * @param signum Signal number to monitor.
465 * @param handler C-style callback function.
466 * @param arg Arbitrary pointer to pass to the handler as argument.
467 * @param priority Priority of the event.
469 signal(int signum, ccallback_type handler, void* arg,
470 int priority = DEFAULT_PRIORITY)
471 throw(invalid_priority)
473 signal_set(this, signum, handler, arg);
474 if (priority != DEFAULT_PRIORITY
475 && event_priority_set(this, priority))
476 throw invalid_priority();
480 * Event's signal number.
482 * @return Event's signal number.
486 return EVENT_SIGNAL(this);
489 }; // struct signal< ccallback_type >
498 * This class is the responsable for looping and dispatching events.
504 * Creates a default dispatcher (with just 1 prioriority).
506 * @see dispatcher(int) if you want to create a dispatcher with more
511 _event_base = static_cast< internal::event_base* >(internal::event_init());
515 * Creates a dispatcher with npriorities prioriorities.
517 * @param npriorities Number of priority queues to use.
519 dispatcher(int npriorities) throw(std::bad_alloc)
521 _event_base = static_cast< internal::event_base* >(internal::event_init());
522 if (!_event_base) throw std::bad_alloc();
523 // Can't fail because there is no way that it has active events
524 internal::event_base_priority_init(_event_base, npriorities);
527 #ifdef EVENT_BASE_FREE_FIX
528 ~dispatcher() throw() { event_base_free(_event_base); }
532 * Adds an event to the dispatcher.
534 * @param e Event to add.
536 void add(basic_event& e) throw()
538 internal::event_base_set(_event_base, &e);
539 internal::event_add(&e, 0);
543 * Adds an event to the dispatcher with a timeout.
545 * The event is fired when there is activity on e or when to is elapsed,
546 * whatever come first.
548 * @param e Event to add.
551 void add(basic_event& e, const time& to) throw()
553 internal::event_base_set(_event_base, &e);
554 internal::event_add(&e, const_cast< time* >(&to)); // XXX HACK libevent don't use const
558 * Adds a temporary event.
560 * Adds a temporary event, without the need of instantiating a new event
561 * object. Events added this way can't EV_PERSIST.
563 * @param fd File descriptor to monitor for events.
564 * @param ev Type of events to monitor.
565 * @param handler Callback function.
567 template < typename F >
568 void add_once(int fd, short ev, F& handler)
570 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
571 reinterpret_cast< void* >(&handler), 0);
575 * Adds a temporary event to with a C-style callback.
577 * Adds a temporary event, without the need of instantiating a new event
578 * object. Events added this way can't EV_PERSIST.
580 * @param fd File descriptor to monitor for events.
581 * @param ev Type of events to monitor.
582 * @param handler Callback function.
583 * @param arg Arbitrary pointer to pass to the handler as argument.
585 void add_once(int fd, short ev, ccallback_type handler, void* arg)
587 internal::event_once(fd, ev, handler, arg, 0);
591 * Adds a temporary event.
593 * Adds a temporary event, without the need of instantiating a new event
594 * object. Events added this way can't EV_PERSIST.
596 * @param fd File descriptor to monitor for events.
597 * @param ev Type of events to monitor.
598 * @param handler Callback function.
601 template < typename F >
602 void add_once(int fd, short ev, F& handler, const time& to)
604 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
605 reinterpret_cast< void* >(&handler),
606 const_cast< time* >(&to)); // XXX HACK libevent don't use const
610 * Adds a temporary event with a C-style callback.
612 * Adds a temporary event, without the need of instantiating a new event
613 * object. Events added this way can't EV_PERSIST.
615 * @param fd File descriptor to monitor for events.
616 * @param ev Type of events to monitor.
617 * @param handler Callback function.
618 * @param arg Arbitrary pointer to pass to the handler as argument.
621 void add_once(int fd, short ev, ccallback_type handler, void* arg, const time& to)
623 internal::event_once(fd, ev, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
627 * Adds a temporary timer.
629 * Adds a temporary timer, without the need of instantiating a new timer
632 * @param handler Callback function.
633 * @param to Timer's timeout.
635 template < typename F >
636 void add_once_timer(F& handler, const time& to)
638 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
639 reinterpret_cast< void* >(&handler),
640 const_cast< time* >(&to)); // XXX HACK libevent don't use const
644 * Adds a temporary timer with a C-style callback.
646 * Adds a temporary timer, without the need of instantiating a new timer
649 * @param handler Callback function.
650 * @param arg Arbitrary pointer to pass to the handler as argument.
651 * @param to Timer's timeout.
653 void add_once_timer(ccallback_type handler, void* arg, const time& to)
655 internal::event_once(-1, EV_TIMEOUT, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
661 * The event e will be no longer monitored by this dispatcher.
663 * @param e Event to remove.
665 void del(basic_event& e) throw()
667 internal::event_del(&e);
671 * Main dispatcher loop.
673 * This function takes the control of the program, waiting for event and
674 * calling it's callbacks when they are fired. It only returns under
676 * - exit() was called.
677 * - All events were del()eted.
678 * - Another internal error.
679 * - LOOP_ONCE flag was set.
680 * - LOOP_NONBLOCK flag was set.
682 * @param flags If EVLOOP_ONCE is specified, then just one event is
683 * processed, if EVLOOP_NONBLOCK is specified, then this
684 * function returns whenever as an event or not.
686 int dispatch(int flags = 0) // TODO throw(exception)
688 return internal::event_base_loop(_event_base, flags);
692 * Exit the dispatch() loop.
694 * @param to If a timeout is given, the loop exits after to is passed.
696 int exit(const time& to = time())
698 return internal::event_base_loopexit(_event_base, const_cast< time* >(&to)); // XXX HACK libevent don't use const
702 internal::event_base* _event_base;
703 template < typename F >
704 static void wrapper(int fd, short ev, void* h)
706 F& handler = *reinterpret_cast< F* >(h);
710 }; // struct dispatcher
713 /// Shortcut to C-style event.
714 typedef event::event< ccallback_type > cevent;
716 /// Shortcut to C-style timer.
717 typedef event::timer< ccallback_type > ctimer;
719 /// Shortcut to C-style signal handler.
720 typedef event::signal< ccallback_type > csignal;
725 #endif // _EVENT_HPP_
727 // vim: set filetype=cpp :