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 * @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 eventxx::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 eventxx::event for C-style callbacks.
315 * @see eventxx::event
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 eventxx::timer for C-style callbacks.
381 * @note This event can't EV_PERSIST.
385 struct timer< ccallback_type >: 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 eventxx::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 >
492 /// Shortcut to C-style event.
493 typedef eventxx::event< ccallback_type > cevent;
495 /// Shortcut to C-style timer.
496 typedef eventxx::timer< ccallback_type > ctimer;
498 /// Shortcut to C-style signal handler.
499 typedef eventxx::signal< ccallback_type > csignal;
508 * This class is the responsable for looping and dispatching events.
514 * Creates a default dispatcher (with just 1 prioriority).
516 * @see dispatcher(int) if you want to create a dispatcher with more
521 _event_base = static_cast< internal::event_base* >(internal::event_init());
525 * Creates a dispatcher with npriorities prioriorities.
527 * @param npriorities Number of priority queues to use.
529 dispatcher(int npriorities) throw(std::bad_alloc)
531 _event_base = static_cast< internal::event_base* >(internal::event_init());
532 if (!_event_base) throw std::bad_alloc();
533 // Can't fail because there is no way that it has active events
534 internal::event_base_priority_init(_event_base, npriorities);
537 #ifdef EVENT_BASE_FREE_FIX
538 ~dispatcher() throw() { event_base_free(_event_base); }
542 * Adds an event to the dispatcher.
544 * @param e Event to add.
546 void add(basic_event& e) throw()
548 internal::event_base_set(_event_base, &e);
549 internal::event_add(&e, 0);
553 * Adds an event to the dispatcher with a timeout.
555 * The event is fired when there is activity on e or when to is elapsed,
556 * whatever come first.
558 * @param e Event to add.
561 void add(basic_event& e, const time& to) throw()
563 internal::event_base_set(_event_base, &e);
564 internal::event_add(&e, const_cast< time* >(&to)); // XXX HACK libevent don't use const
568 * Adds a temporary event.
570 * Adds a temporary event, without the need of instantiating a new event
571 * object. Events added this way can't EV_PERSIST.
573 * @param fd File descriptor to monitor for events.
574 * @param ev Type of events to monitor.
575 * @param handler Callback function.
577 template < typename F >
578 void add_once(int fd, short ev, F& handler)
580 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
581 reinterpret_cast< void* >(&handler), 0);
585 * Adds a temporary event to with a C-style callback.
587 * Adds a temporary event, without the need of instantiating a new event
588 * object. Events added this way can't EV_PERSIST.
590 * @param fd File descriptor to monitor for events.
591 * @param ev Type of events to monitor.
592 * @param handler Callback function.
593 * @param arg Arbitrary pointer to pass to the handler as argument.
595 void add_once(int fd, short ev, ccallback_type handler, void* arg)
597 internal::event_once(fd, ev, handler, arg, 0);
601 * Adds a temporary event.
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.
611 template < typename F >
612 void add_once(int fd, short ev, F& handler, const time& to)
614 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
615 reinterpret_cast< void* >(&handler),
616 const_cast< time* >(&to)); // XXX HACK libevent don't use const
620 * Adds a temporary event with a C-style callback.
622 * Adds a temporary event, without the need of instantiating a new event
623 * object. Events added this way can't EV_PERSIST.
625 * @param fd File descriptor to monitor for events.
626 * @param ev Type of events to monitor.
627 * @param handler Callback function.
628 * @param arg Arbitrary pointer to pass to the handler as argument.
631 void add_once(int fd, short ev, ccallback_type handler, void* arg, const time& to)
633 internal::event_once(fd, ev, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
637 * Adds a temporary timer.
639 * Adds a temporary timer, without the need of instantiating a new timer
642 * @param handler Callback function.
643 * @param to Timer's timeout.
645 template < typename F >
646 void add_once_timer(F& handler, const time& to)
648 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
649 reinterpret_cast< void* >(&handler),
650 const_cast< time* >(&to)); // XXX HACK libevent don't use const
654 * Adds a temporary timer with a C-style callback.
656 * Adds a temporary timer, without the need of instantiating a new timer
659 * @param handler Callback function.
660 * @param arg Arbitrary pointer to pass to the handler as argument.
661 * @param to Timer's timeout.
663 void add_once_timer(ccallback_type handler, void* arg, const time& to)
665 internal::event_once(-1, EV_TIMEOUT, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
671 * The event e will be no longer monitored by this dispatcher.
673 * @param e Event to remove.
675 void del(basic_event& e) throw()
677 internal::event_del(&e);
681 * Main dispatcher loop.
683 * This function takes the control of the program, waiting for event and
684 * calling it's callbacks when they are fired. It only returns under
686 * - exit() was called.
687 * - All events were del()eted.
688 * - Another internal error.
689 * - LOOP_ONCE flag was set.
690 * - LOOP_NONBLOCK flag was set.
692 * @param flags If EVLOOP_ONCE is specified, then just one event is
693 * processed, if EVLOOP_NONBLOCK is specified, then this
694 * function returns whenever as an event or not.
696 int dispatch(int flags = 0) // TODO throw(exception)
698 return internal::event_base_loop(_event_base, flags);
702 * Exit the dispatch() loop.
704 * @param to If a timeout is given, the loop exits after to is passed.
706 int exit(const time& to = time())
708 return internal::event_base_loopexit(_event_base, const_cast< time* >(&to)); // XXX HACK libevent don't use const
712 internal::event_base* _event_base;
713 template < typename F >
714 static void wrapper(int fd, short ev, void* h)
716 F& handler = *reinterpret_cast< F* >(h);
720 }; // struct dispatcher
725 #endif // _EVENTXX_HPP_
727 // vim: set filetype=cpp :