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: public 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: public std::invalid_argument, public 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: public std::invalid_argument, public 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< eventxx::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 * @pre The event must be added to some dispatcher.
237 * @see dispatcher::dispatcher(int)
239 void priority(int priority) const throw(invalid_event, invalid_priority)
241 if (ev_flags & EVLIST_ACTIVE)
242 throw invalid_event("can't change the priority of an "
244 // HACK libevent don't use const
245 if (event_priority_set(const_cast< basic_event* >(this),
247 throw invalid_priority();
251 * Event's file descriptor.
253 * @return Event's file descriptor.
255 int fd() const throw()
257 return EVENT_FD(this);
260 /// @note This is an abstract class, you can't instantiate it.
262 basic_event() throw() {}
263 basic_event(const basic_event&);
264 basic_event& operator= (const basic_event&);
266 }; // struct basic_event
270 * Generic event object.
272 * This object stores all the information about an event, incluiding a callback
273 * functor, which is called when the event is fired. The template parameter
274 * must be a functor (callable object or function) that can take 2 parameters:
275 * an integer (the file descriptor of the fired event) and a short (the type of
276 * the fired event: EV_TIMEOUT, EV_SIGNAL, EV_READ, EV_WRITE). There is a
277 * specialized version of this class which takes as the template parameter a C
278 * function with the ccallback_type signature, just like C libevent API does.
280 * @see eventxx::event< ccallback_type >
282 template < typename F >
283 struct event: basic_event
287 * Creates a new event.
289 * @param fd File descriptor to monitor for events.
290 * @param ev Type of events to monitor.
291 * @param handler Callback functor.
293 event(int fd, short ev, F& handler) throw()
295 event_set(this, fd, ev, &wrapper, reinterpret_cast< void* >(&handler));
300 static void wrapper(int fd, short ev, void* h)
302 F& handler = *reinterpret_cast< F* >(h);
306 }; // struct event< F >
310 * This is the specialization of eventxx::event for C-style callbacks.
312 * @see eventxx::event
315 struct event< ccallback_type >: basic_event
319 * Creates a new event.
321 * @param fd File descriptor to monitor for events.
322 * @param ev Type of events to monitor.
323 * @param handler C-style callback function.
324 * @param arg Arbitrary pointer to pass to the handler as argument.
326 event(int fd, short ev, ccallback_type handler, void* arg) throw()
328 event_set(this, fd, ev, handler, arg);
334 }; // struct event< ccallback_type >
338 * Timer event object.
340 * This is just a special case of event that is fired only when a timeout is
341 * reached. It's just a shortcut to event(-1, 0, handler).
343 * @note This event can't EV_PERSIST.
344 * @see timer< ccallback_type >
346 template < typename F >
347 struct timer: event< F >
351 * Creates a new timer event.
353 * @param handler Callback functor.
355 timer(F& handler) throw()
357 evtimer_set(this, &event< F >::wrapper,
358 reinterpret_cast< void* >(&handler));
361 }; // struct timer< F >
365 * This is the specialization of eventxx::timer for C-style callbacks.
367 * @note This event can't EV_PERSIST.
371 struct timer< ccallback_type >: event< ccallback_type >
375 * Creates a new timer event.
377 * @param handler C-style callback function.
378 * @param arg Arbitrary pointer to pass to the handler as argument.
380 timer(ccallback_type handler, void* arg) throw()
382 evtimer_set(this, handler, arg);
385 }; // struct timer< ccallback_type >
389 * Signal event object.
391 * This is just a special case of event that is fired when a signal is raised
392 * (instead of a file descriptor being active). It's just a shortcut to
393 * event(signal, EV_SIGNAL, handler).
395 * @note This event always EV_PERSIST.
396 * @see signal< ccallback_type >
398 template < typename F >
399 struct signal: event< F >
403 * Creates a new singal event.
405 * @param signum Signal number to monitor.
406 * @param handler Callback functor.
408 signal(int signum, F& handler) throw()
410 signal_set(this, signum, &event< F >::wrapper,
411 reinterpret_cast< void* >(&handler));
415 * Event's signal number.
417 * @return Event's signal number.
421 return EVENT_SIGNAL(this);
424 }; // struct signal<F>
428 * This is the specialization of eventxx::signal for C-style callbacks.
430 * @note This event always EV_PERSIST.
434 struct signal< ccallback_type >: event< ccallback_type >
438 * Creates a new signal event.
440 * @param signum Signal number to monitor.
441 * @param handler C-style callback function.
442 * @param arg Arbitrary pointer to pass to the handler as argument.
444 signal(int signum, ccallback_type handler, void* arg) throw()
446 signal_set(this, signum, handler, arg);
450 * Event's signal number.
452 * @return Event's signal number.
456 return EVENT_SIGNAL(this);
459 }; // struct signal< ccallback_type >
462 /// Shortcut to C-style event.
463 typedef eventxx::event< ccallback_type > cevent;
465 /// Shortcut to C-style timer.
466 typedef eventxx::timer< ccallback_type > ctimer;
468 /// Shortcut to C-style signal handler.
469 typedef eventxx::signal< ccallback_type > csignal;
478 * This class is the responsable for looping and dispatching events.
484 * Creates a default dispatcher (with just 1 priority).
486 * @see dispatcher(int) if you want to create a dispatcher with more
491 _event_base = static_cast< internal::event_base* >(internal::event_init());
495 * Creates a dispatcher with npriorities priorities.
497 * @param npriorities Number of priority queues to use.
499 dispatcher(int npriorities) throw(std::bad_alloc)
501 _event_base = static_cast< internal::event_base* >(internal::event_init());
502 if (!_event_base) throw std::bad_alloc();
503 // Can't fail because there is no way that it has active events
504 internal::event_base_priority_init(_event_base, npriorities);
507 #ifdef EVENT_BASE_FREE_FIX
508 ~dispatcher() throw() { event_base_free(_event_base); }
512 * Adds an event to the dispatcher.
514 * @param e Event to add.
515 * @param priority Priority of the event.
517 void add(basic_event& e, int priority = DEFAULT_PRIORITY)
518 throw(invalid_priority)
520 internal::event_base_set(_event_base, &e);
521 if (priority != DEFAULT_PRIORITY
522 && internal::event_priority_set(&e, priority))
523 throw invalid_priority();
524 internal::event_add(&e, 0);
528 * Adds an event to the dispatcher with a timeout.
530 * The event is fired when there is activity on e or when to has elapsed,
531 * whatever come first.
533 * @param e Event to add.
535 * @param priority Priority of the event.
537 void add(basic_event& e, const time& to,
538 int priority = DEFAULT_PRIORITY)
539 throw(invalid_priority)
541 internal::event_base_set(_event_base, &e);
542 if (priority != DEFAULT_PRIORITY
543 && internal::event_priority_set(&e, priority))
544 throw invalid_priority();
545 internal::event_add(&e, const_cast< time* >(&to)); // XXX HACK libevent don't use const
549 * Adds a temporary event.
551 * Adds a temporary event, without the need of instantiating a new event
552 * object. Events added this way can't EV_PERSIST.
554 * @param fd File descriptor to monitor for events.
555 * @param ev Type of events to monitor.
556 * @param handler Callback function.
558 template < typename F >
559 void add_once(int fd, short ev, F& handler)
561 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
562 reinterpret_cast< void* >(&handler), 0);
566 * Adds a temporary event to with a C-style callback.
568 * Adds a temporary event, without the need of instantiating a new event
569 * object. Events added this way can't EV_PERSIST.
571 * @param fd File descriptor to monitor for events.
572 * @param ev Type of events to monitor.
573 * @param handler Callback function.
574 * @param arg Arbitrary pointer to pass to the handler as argument.
576 void add_once(int fd, short ev, ccallback_type handler, void* arg)
578 internal::event_once(fd, ev, handler, arg, 0);
582 * Adds a temporary event.
584 * Adds a temporary event, without the need of instantiating a new event
585 * object. Events added this way can't EV_PERSIST.
587 * @param fd File descriptor to monitor for events.
588 * @param ev Type of events to monitor.
589 * @param handler Callback function.
592 template < typename F >
593 void add_once(int fd, short ev, F& handler, const time& to)
595 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
596 reinterpret_cast< void* >(&handler),
597 const_cast< time* >(&to)); // XXX HACK libevent don't use const
601 * Adds a temporary event with a C-style callback.
603 * Adds a temporary event, without the need of instantiating a new event
604 * object. Events added this way can't EV_PERSIST.
606 * @param fd File descriptor to monitor for events.
607 * @param ev Type of events to monitor.
608 * @param handler Callback function.
609 * @param arg Arbitrary pointer to pass to the handler as argument.
612 void add_once(int fd, short ev, ccallback_type handler, void* arg, const time& to)
614 internal::event_once(fd, ev, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
618 * Adds a temporary timer.
620 * Adds a temporary timer, without the need of instantiating a new timer
623 * @param handler Callback function.
624 * @param to Timer's timeout.
626 template < typename F >
627 void add_once_timer(F& handler, const time& to)
629 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
630 reinterpret_cast< void* >(&handler),
631 const_cast< time* >(&to)); // XXX HACK libevent don't use const
635 * Adds a temporary timer with a C-style callback.
637 * Adds a temporary timer, without the need of instantiating a new timer
640 * @param handler Callback function.
641 * @param arg Arbitrary pointer to pass to the handler as argument.
642 * @param to Timer's timeout.
644 void add_once_timer(ccallback_type handler, void* arg, const time& to)
646 internal::event_once(-1, EV_TIMEOUT, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
652 * The event e will be no longer monitored by this dispatcher.
654 * @param e Event to remove.
656 void del(basic_event& e) throw()
658 internal::event_del(&e);
662 * Main dispatcher loop.
664 * This function takes the control of the program, waiting for an event
665 * and calling its callbacks when it's fired. It only returns under
667 * - exit() was called.
668 * - All events were del()eted.
669 * - Another internal error.
670 * - LOOP_ONCE flag was set.
671 * - LOOP_NONBLOCK flag was set.
673 * @param flags If EVLOOP_ONCE is specified, then just one event is
674 * processed, if EVLOOP_NONBLOCK is specified, then this
675 * function returns even if there are no pending events.
677 int dispatch(int flags = 0) // TODO throw(exception)
679 return internal::event_base_loop(_event_base, flags);
683 * Exit the dispatch() loop.
685 * @param to If a timeout is given, the loop exits after the specified
688 int exit(const time& to = time())
690 return internal::event_base_loopexit(_event_base, const_cast< time* >(&to)); // XXX HACK libevent don't use const
694 internal::event_base* _event_base;
695 template < typename F >
696 static void wrapper(int fd, short ev, void* h)
698 F& handler = *reinterpret_cast< F* >(h);
702 }; // struct dispatcher
707 #endif // _EVENTXX_HPP_
709 // vim: set filetype=cpp :