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.
291 event(int fd, short ev, F& handler) throw()
293 event_set(this, fd, ev, &wrapper, reinterpret_cast< void* >(&handler));
298 static void wrapper(int fd, short ev, void* h)
300 F& handler = *reinterpret_cast< F* >(h);
304 }; // struct event< F >
308 * This is the specialization of eventxx::event for C-style callbacks.
310 * @see eventxx::event
313 struct event< ccallback_type >: basic_event
317 * Creates a new event.
319 * @param fd File descriptor to monitor for events.
320 * @param ev Type of events to monitor.
321 * @param handler C-style callback function.
322 * @param arg Arbitrary pointer to pass to the handler as argument.
324 event(int fd, short ev, ccallback_type handler, void* arg) throw()
326 event_set(this, fd, ev, handler, arg);
332 }; // struct event< ccallback_type >
336 * Timer event object.
338 * This is just a special case of event that is fired only when a timeout is
339 * reached. It's just a shortcut to event(-1, 0, handler).
341 * @note This event can't EV_PERSIST.
342 * @see timer< ccallback_type >
344 template < typename F >
345 struct timer: event< F >
349 * Creates a new timer event.
351 * @param handler Callback functor.
353 timer(F& handler) throw()
355 evtimer_set(this, &event< F >::wrapper,
356 reinterpret_cast< void* >(&handler));
359 }; // struct timer< F >
363 * This is the specialization of eventxx::timer for C-style callbacks.
365 * @note This event can't EV_PERSIST.
369 struct timer< ccallback_type >: event< ccallback_type >
373 * Creates a new timer event.
375 * @param handler C-style callback function.
376 * @param arg Arbitrary pointer to pass to the handler as argument.
378 timer(ccallback_type handler, void* arg) throw()
380 evtimer_set(this, handler, arg);
383 }; // struct timer< ccallback_type >
387 * Signal event object.
389 * This is just a special case of event that is fired when a signal is raised
390 * (instead of a file descriptor being active). It's just a shortcut to
391 * event(signal, EV_SIGNAL, handler).
393 * @note This event allways EV_PERSIST.
394 * @see signal< ccallback_type >
396 template < typename F >
397 struct signal: event< F >
401 * Creates a new singal event.
403 * @param signum Signal number to monitor.
404 * @param handler Callback functor.
406 signal(int signum, F& handler) throw()
408 signal_set(this, signum, &event< F >::wrapper,
409 reinterpret_cast< void* >(&handler));
413 * Event's signal number.
415 * @return Event's signal number.
419 return EVENT_SIGNAL(this);
422 }; // struct signal<F>
426 * This is the specialization of eventxx::signal for C-style callbacks.
428 * @note This event allways EV_PERSIST.
432 struct signal< ccallback_type >: event< ccallback_type >
436 * Creates a new signal event.
438 * @param signum Signal number to monitor.
439 * @param handler C-style callback function.
440 * @param arg Arbitrary pointer to pass to the handler as argument.
442 signal(int signum, ccallback_type handler, void* arg) throw()
444 signal_set(this, signum, handler, arg);
448 * Event's signal number.
450 * @return Event's signal number.
454 return EVENT_SIGNAL(this);
457 }; // struct signal< ccallback_type >
460 /// Shortcut to C-style event.
461 typedef eventxx::event< ccallback_type > cevent;
463 /// Shortcut to C-style timer.
464 typedef eventxx::timer< ccallback_type > ctimer;
466 /// Shortcut to C-style signal handler.
467 typedef eventxx::signal< ccallback_type > csignal;
476 * This class is the responsable for looping and dispatching events.
482 * Creates a default dispatcher (with just 1 prioriority).
484 * @see dispatcher(int) if you want to create a dispatcher with more
489 _event_base = static_cast< internal::event_base* >(internal::event_init());
493 * Creates a dispatcher with npriorities prioriorities.
495 * @param npriorities Number of priority queues to use.
497 dispatcher(int npriorities) throw(std::bad_alloc)
499 _event_base = static_cast< internal::event_base* >(internal::event_init());
500 if (!_event_base) throw std::bad_alloc();
501 // Can't fail because there is no way that it has active events
502 internal::event_base_priority_init(_event_base, npriorities);
505 #ifdef EVENT_BASE_FREE_FIX
506 ~dispatcher() throw() { event_base_free(_event_base); }
510 * Adds an event to the dispatcher.
512 * @param e Event to add.
513 * @param priority Priority of the event.
515 void add(basic_event& e, int priority = DEFAULT_PRIORITY)
516 throw(invalid_priority)
518 internal::event_base_set(_event_base, &e);
519 if (priority != DEFAULT_PRIORITY
520 && internal::event_priority_set(&e, priority))
521 throw invalid_priority();
522 internal::event_add(&e, 0);
526 * Adds an event to the dispatcher with a timeout.
528 * The event is fired when there is activity on e or when to is elapsed,
529 * whatever come first.
531 * @param e Event to add.
533 * @param priority Priority of the event.
535 void add(basic_event& e, const time& to,
536 int priority = DEFAULT_PRIORITY)
537 throw(invalid_priority)
539 internal::event_base_set(_event_base, &e);
540 if (priority != DEFAULT_PRIORITY
541 && internal::event_priority_set(&e, priority))
542 throw invalid_priority();
543 internal::event_add(&e, const_cast< time* >(&to)); // XXX HACK libevent don't use const
547 * Adds a temporary event.
549 * Adds a temporary event, without the need of instantiating a new event
550 * object. Events added this way can't EV_PERSIST.
552 * @param fd File descriptor to monitor for events.
553 * @param ev Type of events to monitor.
554 * @param handler Callback function.
556 template < typename F >
557 void add_once(int fd, short ev, F& handler)
559 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
560 reinterpret_cast< void* >(&handler), 0);
564 * Adds a temporary event to with a C-style callback.
566 * Adds a temporary event, without the need of instantiating a new event
567 * object. Events added this way can't EV_PERSIST.
569 * @param fd File descriptor to monitor for events.
570 * @param ev Type of events to monitor.
571 * @param handler Callback function.
572 * @param arg Arbitrary pointer to pass to the handler as argument.
574 void add_once(int fd, short ev, ccallback_type handler, void* arg)
576 internal::event_once(fd, ev, handler, arg, 0);
580 * Adds a temporary event.
582 * Adds a temporary event, without the need of instantiating a new event
583 * object. Events added this way can't EV_PERSIST.
585 * @param fd File descriptor to monitor for events.
586 * @param ev Type of events to monitor.
587 * @param handler Callback function.
590 template < typename F >
591 void add_once(int fd, short ev, F& handler, const time& to)
593 internal::event_once(fd, ev, &dispatcher::wrapper< F >,
594 reinterpret_cast< void* >(&handler),
595 const_cast< time* >(&to)); // XXX HACK libevent don't use const
599 * Adds a temporary event with a C-style callback.
601 * Adds a temporary event, without the need of instantiating a new event
602 * object. Events added this way can't EV_PERSIST.
604 * @param fd File descriptor to monitor for events.
605 * @param ev Type of events to monitor.
606 * @param handler Callback function.
607 * @param arg Arbitrary pointer to pass to the handler as argument.
610 void add_once(int fd, short ev, ccallback_type handler, void* arg, const time& to)
612 internal::event_once(fd, ev, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
616 * Adds a temporary timer.
618 * Adds a temporary timer, without the need of instantiating a new timer
621 * @param handler Callback function.
622 * @param to Timer's timeout.
624 template < typename F >
625 void add_once_timer(F& handler, const time& to)
627 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
628 reinterpret_cast< void* >(&handler),
629 const_cast< time* >(&to)); // XXX HACK libevent don't use const
633 * Adds a temporary timer with a C-style callback.
635 * Adds a temporary timer, without the need of instantiating a new timer
638 * @param handler Callback function.
639 * @param arg Arbitrary pointer to pass to the handler as argument.
640 * @param to Timer's timeout.
642 void add_once_timer(ccallback_type handler, void* arg, const time& to)
644 internal::event_once(-1, EV_TIMEOUT, handler, arg, const_cast< time* >(&to)); // XXX HACK libevent don't use const
650 * The event e will be no longer monitored by this dispatcher.
652 * @param e Event to remove.
654 void del(basic_event& e) throw()
656 internal::event_del(&e);
660 * Main dispatcher loop.
662 * This function takes the control of the program, waiting for event and
663 * calling it's callbacks when they are fired. It only returns under
665 * - exit() was called.
666 * - All events were del()eted.
667 * - Another internal error.
668 * - LOOP_ONCE flag was set.
669 * - LOOP_NONBLOCK flag was set.
671 * @param flags If EVLOOP_ONCE is specified, then just one event is
672 * processed, if EVLOOP_NONBLOCK is specified, then this
673 * function returns whenever as an event or not.
675 int dispatch(int flags = 0) // TODO throw(exception)
677 return internal::event_base_loop(_event_base, flags);
681 * Exit the dispatch() loop.
683 * @param to If a timeout is given, the loop exits after to is passed.
685 int exit(const time& to = time())
687 return internal::event_base_loopexit(_event_base, const_cast< time* >(&to)); // XXX HACK libevent don't use const
691 internal::event_base* _event_base;
692 template < typename F >
693 static void wrapper(int fd, short ev, void* h)
695 F& handler = *reinterpret_cast< F* >(h);
699 }; // struct dispatcher
704 #endif // _EVENTXX_HPP_
706 // vim: set filetype=cpp :