4 #include <sys/types.h> // timeval
5 #include <stdexcept> // std::exception, std::invalid_argument,
6 // std::runtime_error, std::bad_alloc
9 * Namespace for all symbols libevent C++ wrapper defines.
15 // All libevent C API symbols and other internal stuff goes here.
22 /** @defgroup exceptions Exceptions
24 * eventxx makes a heavy use of exceptions. Each function has it's exceptions
25 * specified, so it's very easy to find out what exceptions to expect.
27 * Exceptions are mostly thrown when there is a programming error. So if you get
28 * an exception check your code.
34 * Base class for all libevent exceptions.
36 struct exception: public std::exception
42 * Invalid event exception.
44 * This exception is thrown when passing an invalid event to a function, the
45 * reason is given in the what() description but it usually means that the you
46 * are making some restricted operation with an active event.
48 * If you hit this exception, you probably got a programming error.
50 struct invalid_event: public std::invalid_argument, public exception
54 * Creates an invalid event exception with a reason.
56 * @param what Reason why the event is invalid).
58 explicit invalid_event(const std::string& what) throw():
59 std::invalid_argument(what)
63 }; // struct invalid_event
67 * Invalid priority exception.
69 * This exception is thrown when passing an invalid priority to a function. This
70 * usually means you don't have enough priority queues in your dispatcher, so
71 * you should have allocated more in the constructor.
73 * If you hit this exception, you probably got a programming error.
75 * @see dispatcher::dispatcher(int) to allocate more priority queues.
77 struct invalid_priority: public std::invalid_argument, public exception
81 * Creates an invalid priority exception with a reason.
83 * @param what Reason why the priority is invalid).
85 explicit invalid_priority(const std::string& what
86 = "invalid priority value") throw():
87 std::invalid_argument(what)
91 }; // struct invalid_priority
96 /// Miscellaneous constants
99 DEFAULT_PRIORITY = -1, ///< Default priority (the middle value).
100 ONCE = EVLOOP_ONCE, ///< Loop just once.
101 NONBLOCK = EVLOOP_NONBLOCK ///< Don't block the event loop.
106 * Time used for timeout values.
108 * This timeout is compose of seconds and microseconds.
110 struct time: ::timeval
114 * Creates a new time with @p sec seconds and @p usec microseconds.
116 * @param sec Number of seconds.
117 * @param usec Number of microseconds.
119 time(long sec = 0l, long usec = 0l) throw()
120 { tv_sec = sec; tv_usec = usec; }
123 * Gets the number of seconds.
125 * @return Number of seconds.
127 long sec() const throw() { return tv_sec; };
130 * Gets the number of microseconds.
132 * @return Number of microseconds.
134 long usec() const throw() { return tv_usec; };
137 * Sets the number of seconds.
139 * @param s Number of seconds.
141 void sec(long s) throw() { tv_sec = s; };
144 * Sets the number of microseconds.
146 * @param u Number of microseconds.
148 void usec(long u) throw() { tv_usec = u; };
153 /** @defgroup events Events
155 * There are many ways to specify how to handle an event. You can use use the
156 * same plain functions callbacks (see eventxx::cevent, eventxx::ctimer and
157 * eventxx::csignal) like in C or the other kind of more advanced, stateful
158 * function objects (see eventxx::event, eventxx::timer and eventxx::signal
159 * templates). The former are just typedef'ed specialization of the later.
161 * A member function wrapper functor (eventxx::mem_cb) is also included,
162 * so you can use any member function (method) as an event handler.
164 * Please note that C-like function callback take a short as the type of event,
165 * while functors (or member functions) use eventxx::type.
167 * All events derive from a plain class (not template) eventxx::basic_event, one
168 * of the main utilities of it (besides containing common code ;) is to be used
171 * Please see each class documentation for details and examples.
176 /// C function used as callback in the C API.
177 typedef void (*ccallback_type)(int, short, void*);
183 * There are 4 kind of events: eventxx::TIMEOUT, eventxx::READ, eventxx::WRITE
184 * or eventxx::SIGNAL. eventxx::PERSIST is not an event, is an event modifier
185 * flag, that tells eventxx that this event should live until dispatcher::del()
186 * is called. You can use, for example:
188 * eventxx::event(fd, eventxx::READ | eventxx::PERSIST, ...);
193 TIMEOUT = EV_TIMEOUT, ///< Timeout event.
194 READ = EV_READ, ///< Read event.
195 WRITE = EV_WRITE, ///< Write event.
196 SIGNAL = EV_SIGNAL, ///< Signal event.
197 PERSIST = EV_PERSIST ///< Not really an event, is an event modifier.
201 type operator| (const type& t1, const type& t2)
203 int r = static_cast< int >(t1) | static_cast< int >(t2);
204 int* pr = &r; // Avoid some weird warning about dereferencing
205 // type-punned pointer will break strict-aliasing rules
206 return *reinterpret_cast< type* >(pr);
211 * Basic event from which all events derive.
213 * All events derive from this class, so it's useful for use in containers,
216 * std::list< eventxx::basic_event* > events;
219 struct basic_event: internal::event
223 * Checks if there is an event pending.
225 * @param ev Type of event to check.
227 * @return true if there is a pending event, false if not.
229 bool pending(type ev) const throw()
231 // HACK libevent don't use const
232 return event_pending(const_cast< basic_event* >(this), ev, 0);
236 * Timeout of the event.
238 * @return Timeout of the event.
240 time timeout() const throw()
243 // HACK libevent don't use const
244 event_pending(const_cast< basic_event* >(this), EV_TIMEOUT, &tv);
249 * Sets the event's priority.
251 * @param priority New event priority.
253 * @pre The event must be added to some dispatcher.
255 * @see dispatcher::dispatcher(int)
257 void priority(int priority) const throw(invalid_event, invalid_priority)
259 if (ev_flags & EVLIST_ACTIVE)
260 throw invalid_event("can't change the priority of an "
262 // HACK libevent don't use const
263 if (event_priority_set(const_cast< basic_event* >(this),
265 throw invalid_priority();
269 * Event's file descriptor.
271 * @return Event's file descriptor.
273 int fd() const throw()
275 return EVENT_FD(this);
278 /// @note This is an abstract class, you can't instantiate it.
280 basic_event() throw() {}
281 basic_event(const basic_event&);
282 basic_event& operator= (const basic_event&);
284 }; // struct basic_event
288 * Generic event object.
290 * This object stores all the information about an event, including a callback
291 * functor, which is called when the event is fired. The template parameter
292 * must be a functor (callable object or function) that can take 2 parameters:
293 * an integer (the file descriptor of the fired event) and an event::type (the
294 * type of event being fired).
295 * There is a specialized version of this class which takes as the template
296 * parameter a C function with the eventxx::ccallback_type signature, just like
297 * C @libevent API does.
299 * @see eventxx::event< ccallback_type >
301 template < typename F >
302 struct event: basic_event
306 * Creates a new event.
308 * @param fd File descriptor to monitor for events.
309 * @param ev Type of events to monitor (see eventxx::type).
310 * @param handler Callback functor.
312 event(int fd, type ev, F& handler) throw()
314 event_set(this, fd, static_cast< short >(ev), &wrapper,
315 reinterpret_cast< void* >(&handler));
320 static void wrapper(int fd, short ev, void* h)
322 F& handler = *reinterpret_cast< F* >(h);
323 // Hackish, but this way the handler can get a clean
325 short* pev = &ev; // Avoid some weird warning about
326 // dereferencing type-punned pointer
327 // will break strict-aliasing rules
328 handler(fd, *reinterpret_cast< type* >(pev));
331 }; // struct event< F >
335 * This is the specialization of eventxx::event for C-style callbacks.
337 * @see eventxx::event
340 struct event< ccallback_type >: basic_event
344 * Creates a new event.
346 * @param fd File descriptor to monitor for events.
347 * @param ev Type of events to monitor (see eventxx::type).
348 * @param handler C-style callback function.
349 * @param arg Arbitrary pointer to pass to the handler as argument.
351 event(int fd, type ev, ccallback_type handler, void* arg = 0) throw()
353 event_set(this, fd, static_cast< short >(ev), handler, arg);
359 }; // struct event< ccallback_type >
363 * Timer event object.
365 * This is just a special case of event that is fired only when a timeout is
366 * reached. It's just a shortcut to:
368 * event(-1, 0, handler);
371 * @note This event can't eventxx::PERSIST.
372 * @see timer< ccallback_type >
374 template < typename F >
375 struct timer: event< F >
379 * Creates a new timer event.
381 * @param handler Callback functor.
383 timer(F& handler) throw()
385 evtimer_set(this, &event< F >::wrapper,
386 reinterpret_cast< void* >(&handler));
389 }; // struct timer< F >
393 * This is the specialization of eventxx::timer for C-style callbacks.
395 * @note This event can't eventxx::PERSIST.
399 struct timer< ccallback_type >: event< ccallback_type >
403 * Creates a new timer event.
405 * @param handler C-style callback function.
406 * @param arg Arbitrary pointer to pass to the handler as argument.
408 timer(ccallback_type handler, void* arg = 0) throw()
410 evtimer_set(this, handler, arg);
413 }; // struct timer< ccallback_type >
417 * Signal event object.
419 * This is just a special case of event that is fired when a signal is raised
420 * (instead of a file descriptor being active). It's just a shortcut to:
422 * event(signum, eventxx::SIGNAL, handler);
425 * @note This event always eventxx::PERSIST.
426 * @see signal< ccallback_type >
428 template < typename F >
429 struct signal: event< F >
433 * Creates a new signal event.
435 * @param signum Signal number to monitor.
436 * @param handler Callback functor.
438 signal(int signum, F& handler) throw()
440 signal_set(this, signum, &event< F >::wrapper,
441 reinterpret_cast< void* >(&handler));
445 * Event's signal number.
447 * @return Event's signal number.
451 return EVENT_SIGNAL(this);
454 }; // struct signal<F>
458 * This is the specialization of eventxx::signal for C-style callbacks.
460 * @note This event always eventxx::PERSIST.
464 struct signal< ccallback_type >: event< ccallback_type >
468 * Creates a new signal event.
470 * @param signum Signal number to monitor.
471 * @param handler C-style callback function.
472 * @param arg Arbitrary pointer to pass to the handler as argument.
474 signal(int signum, ccallback_type handler, void* arg = 0) throw()
476 signal_set(this, signum, handler, arg);
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;
502 * Helper functor to use an arbitrary member function as an event handler.
504 * With this wrapper, you can use any object method, which accepts the right
505 * parameters (int, short) and returns void, as an event handler. This way you
506 * don't have to overload the operator() which can be confusing depending on the
509 * You can see an usage example in the Examples Section.
511 template < typename O, typename M >
516 * Member function callback constructor.
518 * It expects to receive a class as the first parameter (O), and a
519 * member function (of that class O) as the second parameter.
521 * When this instance is called with fd and ev as function arguments,
522 * object.method(fd, ev) will be called.
524 * @param object Object to be used.
525 * @param method Method to be called.
527 mem_cb(O& object, M method) throw():
528 _object(object), _method(method) {}
530 void operator() (int fd, type ev) { (_object.*_method)(fd, ev); }
543 * This class is the responsible for looping and dispatching events. Every time
544 * you need an event loop you should create an instance of this class.
546 * You can @link dispatcher::add add @endlink events to the dispatcher, and you
547 * can @link dispatcher::del remove @endlink them later or you can @link
548 * dispatcher::add_once add events to be processed just once @endlink. You can
549 * @link dispatcher::dispatch loop once or forever @endlink (well, of course you
550 * can break that forever removing all the events or by @link dispatcher::exit
551 * exiting the loop @endlink).
557 * Creates a default dispatcher (with just 1 priority).
559 * @see dispatcher(int) if you want to create a dispatcher with more
564 _event_base = static_cast< internal::event_base* >(
565 internal::event_init());
569 * Creates a dispatcher with npriorities priorities.
571 * @param npriorities Number of priority queues to use.
573 dispatcher(int npriorities) throw(std::bad_alloc)
575 _event_base = static_cast< internal::event_base* >(
576 internal::event_init());
577 if (!_event_base) throw std::bad_alloc();
578 // Can't fail because there is no way that it has active events
579 internal::event_base_priority_init(_event_base, npriorities);
582 #ifndef EVENTXX_NO_EVENT_BASE_FREE
583 /// Free dispatcher resources, see @ref Status section for details.
584 ~dispatcher() throw() { event_base_free(_event_base); }
588 * Adds an event to the dispatcher.
590 * @param e Event to add.
591 * @param priority Priority of the event.
593 void add(basic_event& e, int priority = DEFAULT_PRIORITY)
594 throw(invalid_priority)
596 internal::event_base_set(_event_base, &e);
597 if (priority != DEFAULT_PRIORITY
598 && internal::event_priority_set(&e, priority))
599 throw invalid_priority();
600 internal::event_add(&e, 0);
604 * Adds an event to the dispatcher with a timeout.
606 * The event is fired when there is activity on e or when to has elapsed,
607 * whatever come first.
609 * @param e Event to add.
611 * @param priority Priority of the event.
613 void add(basic_event& e, const time& to,
614 int priority = DEFAULT_PRIORITY)
615 throw(invalid_priority)
617 internal::event_base_set(_event_base, &e);
618 if (priority != DEFAULT_PRIORITY
619 && internal::event_priority_set(&e, priority))
620 throw invalid_priority();
621 // XXX HACK libevent don't use const
622 internal::event_add(&e, const_cast< time* >(&to));
626 * Adds a temporary event.
628 * Adds a temporary event, without the need of instantiating a new event
629 * object. Events added this way can't eventxx::PERSIST.
631 * @param fd File descriptor to monitor for events.
632 * @param ev Type of events to monitor.
633 * @param handler Callback function.
635 template < typename F >
636 void add_once(int fd, type ev, F& handler)
638 internal::event_once(fd, static_cast< short>(ev),
639 &dispatcher::wrapper< F >,
640 reinterpret_cast< void* >(&handler), 0);
644 * Adds a temporary event to with a C-style callback.
646 * Adds a temporary event, without the need of instantiating a new event
647 * object. Events added this way can't eventxx::PERSIST.
649 * @param fd File descriptor to monitor for events.
650 * @param ev Type of events to monitor.
651 * @param handler Callback function.
652 * @param arg Arbitrary pointer to pass to the handler as argument.
654 void add_once(int fd, type ev, ccallback_type handler, void* arg)
656 internal::event_once(fd, static_cast< short >(ev), handler,
661 * Adds a temporary event.
663 * Adds a temporary event, without the need of instantiating a new event
664 * object. Events added this way can't eventxx::PERSIST.
666 * @param fd File descriptor to monitor for events.
667 * @param ev Type of events to monitor.
668 * @param handler Callback function.
671 template < typename F >
672 void add_once(int fd, type ev, F& handler, const time& to)
674 internal::event_once(fd, static_cast< short >(ev),
675 &dispatcher::wrapper< F >,
676 reinterpret_cast< void* >(&handler),
677 // XXX HACK libevent don't use const
678 const_cast< time* >(&to));
682 * Adds a temporary event with a C-style callback.
684 * Adds a temporary event, without the need of instantiating a new event
685 * object. Events added this way can't eventxx::PERSIST.
687 * @param fd File descriptor to monitor for events.
688 * @param ev Type of events to monitor.
689 * @param handler Callback function.
690 * @param arg Arbitrary pointer to pass to the handler as argument.
693 void add_once(int fd, type ev, ccallback_type handler, void* arg,
696 internal::event_once(fd, static_cast< short >(ev), handler, arg,
697 // XXX HACK libevent don't use const
698 const_cast< time* >(&to));
702 * Adds a temporary timer.
704 * Adds a temporary timer, without the need of instantiating a new timer
707 * @param handler Callback function.
708 * @param to Timer's timeout.
710 template < typename F >
711 void add_once_timer(F& handler, const time& to)
713 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
714 reinterpret_cast< void* >(&handler),
715 // XXX HACK libevent don't use const
716 const_cast< time* >(&to));
720 * Adds a temporary timer with a C-style callback.
722 * Adds a temporary timer, without the need of instantiating a new timer
725 * @param handler Callback function.
726 * @param arg Arbitrary pointer to pass to the handler as argument.
727 * @param to Timer's timeout.
729 void add_once_timer(ccallback_type handler, void* arg, const time& to)
731 // XXX HACK libevent don't use const
732 internal::event_once(-1, EV_TIMEOUT, handler, arg,
733 const_cast< time* >(&to));
739 * The event e will be no longer monitored by this dispatcher.
741 * @param e Event to remove.
743 void del(basic_event& e) throw()
745 internal::event_del(&e);
749 * Main dispatcher loop.
751 * This function takes the control of the program, waiting for an event
752 * and calling its callbacks when it's fired. It only returns under
754 * - exit() was called.
755 * - All events were del()eted.
756 * - Another internal error.
757 * - eventxx::ONCE flag was set.
758 * - eventxx::NONBLOCK flag was set.
760 * @param flags If eventxx::ONCE is specified, then just one event is
761 * processed, if eventxx::NONBLOCK is specified, then this
762 * function returns even if there are no pending events.
764 * @return 0 if eventxx::NONBLOCK or eventxx::ONCE is set, 1 if there
765 * are no more events registered and EINTR if you use the
766 * @libevent's @c event_gotsig and return -1 in your
767 * @c event_sigcb callback.
769 int dispatch(int flags = 0) throw()
771 return internal::event_base_loop(_event_base, flags);
775 * Exit the dispatch() loop.
777 * @param to If a timeout is given, the loop exits after the specified
780 * @return Not very well specified by @libevent :-/ that's why it
781 * doesn't throw an exception either.
783 int exit(const time& to = time()) throw() // TODO throw(exception)
785 // XXX HACK libevent don't use const
786 return internal::event_base_loopexit(_event_base,
787 const_cast< time* >(&to));
791 internal::event_base* _event_base;
792 template < typename F >
793 static void wrapper(int fd, short ev, void* h)
795 F& handler = *reinterpret_cast< F* >(h);
796 handler(fd, *reinterpret_cast< type* >(&ev));
799 }; // struct dispatcher
801 } // namespace eventxx
803 #endif // _EVENTXX_HPP_
805 // vim: set filetype=cpp :