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 return static_cast< type >(r);
209 * Basic event from which all events derive.
211 * All events derive from this class, so it's useful for use in containers,
214 * std::list< eventxx::basic_event* > events;
217 struct basic_event: internal::event
221 * Checks if there is an event pending.
223 * @param ev Type of event to check.
225 * @return true if there is a pending event, false if not.
227 bool pending(type ev) const throw()
229 // HACK libevent don't use const
230 return event_pending(const_cast< basic_event* >(this), ev, 0);
234 * Timeout of the event.
236 * @return Timeout of the event.
238 time timeout() const throw()
241 // HACK libevent don't use const
242 event_pending(const_cast< basic_event* >(this), EV_TIMEOUT, &tv);
247 * Sets the event's priority.
249 * @param priority New event priority.
251 * @pre The event must be added to some dispatcher.
253 * @see dispatcher::dispatcher(int)
255 void priority(int priority) const throw(invalid_event, invalid_priority)
257 if (ev_flags & EVLIST_ACTIVE)
258 throw invalid_event("can't change the priority of an "
260 // HACK libevent don't use const
261 if (event_priority_set(const_cast< basic_event* >(this),
263 throw invalid_priority();
267 * Event's file descriptor.
269 * @return Event's file descriptor.
271 int fd() const throw()
273 return EVENT_FD(this);
276 /// @note This is an abstract class, you can't instantiate it.
278 basic_event() throw() {}
279 basic_event(const basic_event&);
280 basic_event& operator= (const basic_event&);
282 }; // struct basic_event
286 * Generic event object.
288 * This object stores all the information about an event, including a callback
289 * functor, which is called when the event is fired. The template parameter
290 * must be a functor (callable object or function) that can take 2 parameters:
291 * an integer (the file descriptor of the fired event) and an event::type (the
292 * type of event being fired).
293 * There is a specialized version of this class which takes as the template
294 * parameter a C function with the eventxx::ccallback_type signature, just like
295 * C @libevent API does.
297 * @see eventxx::event< ccallback_type >
299 template < typename F >
300 struct event: basic_event
304 * Creates a new event.
306 * @param fd File descriptor to monitor for events.
307 * @param ev Type of events to monitor (see eventxx::type).
308 * @param handler Callback functor.
310 event(int fd, type ev, F& handler) throw()
312 event_set(this, fd, static_cast< short >(ev), &wrapper,
313 reinterpret_cast< void* >(&handler));
318 static void wrapper(int fd, short ev, void* h)
320 F& handler = *reinterpret_cast< F* >(h);
321 // Hackish, but this way the handler can get a clean
323 short* pev = &ev; // Avoid some weird warning about
324 // dereferencing type-punned pointer
325 // will break strict-aliasing rules
326 handler(fd, *reinterpret_cast< type* >(pev));
329 }; // struct event< F >
333 * This is the specialization of eventxx::event for C-style callbacks.
335 * @see eventxx::event
338 struct event< ccallback_type >: basic_event
342 * Creates a new event.
344 * @param fd File descriptor to monitor for events.
345 * @param ev Type of events to monitor (see eventxx::type).
346 * @param handler C-style callback function.
347 * @param arg Arbitrary pointer to pass to the handler as argument.
349 event(int fd, type ev, ccallback_type handler, void* arg = 0) throw()
351 event_set(this, fd, static_cast< short >(ev), handler, arg);
357 }; // struct event< ccallback_type >
361 * Timer event object.
363 * This is just a special case of event that is fired only when a timeout is
364 * reached. It's just a shortcut to:
366 * event(-1, 0, handler);
369 * @note This event can't eventxx::PERSIST.
370 * @see timer< ccallback_type >
372 template < typename F >
373 struct timer: event< F >
377 * Creates a new timer event.
379 * @param handler Callback functor.
381 timer(F& handler) throw()
383 evtimer_set(this, &event< F >::wrapper,
384 reinterpret_cast< void* >(&handler));
387 }; // struct timer< F >
391 * This is the specialization of eventxx::timer for C-style callbacks.
393 * @note This event can't eventxx::PERSIST.
397 struct timer< ccallback_type >: event< ccallback_type >
401 * Creates a new timer event.
403 * @param handler C-style callback function.
404 * @param arg Arbitrary pointer to pass to the handler as argument.
406 timer(ccallback_type handler, void* arg = 0) throw()
408 evtimer_set(this, handler, arg);
411 }; // struct timer< ccallback_type >
415 * Signal event object.
417 * This is just a special case of event that is fired when a signal is raised
418 * (instead of a file descriptor being active). It's just a shortcut to:
420 * event(signum, eventxx::SIGNAL, handler);
423 * @note This event always eventxx::PERSIST.
424 * @see signal< ccallback_type >
426 template < typename F >
427 struct signal: event< F >
431 * Creates a new signal event.
433 * @param signum Signal number to monitor.
434 * @param handler Callback functor.
436 signal(int signum, F& handler) throw()
438 signal_set(this, signum, &event< F >::wrapper,
439 reinterpret_cast< void* >(&handler));
443 * Event's signal number.
445 * @return Event's signal number.
449 return EVENT_SIGNAL(this);
452 }; // struct signal<F>
456 * This is the specialization of eventxx::signal for C-style callbacks.
458 * @note This event always eventxx::PERSIST.
462 struct signal< ccallback_type >: event< ccallback_type >
466 * Creates a new signal event.
468 * @param signum Signal number to monitor.
469 * @param handler C-style callback function.
470 * @param arg Arbitrary pointer to pass to the handler as argument.
472 signal(int signum, ccallback_type handler, void* arg = 0) throw()
474 signal_set(this, signum, handler, arg);
478 * Event's signal number.
480 * @return Event's signal number.
484 return EVENT_SIGNAL(this);
487 }; // struct signal< ccallback_type >
490 /// Shortcut to C-style event.
491 typedef eventxx::event< ccallback_type > cevent;
493 /// Shortcut to C-style timer.
494 typedef eventxx::timer< ccallback_type > ctimer;
496 /// Shortcut to C-style signal handler.
497 typedef eventxx::signal< ccallback_type > csignal;
500 * Helper functor to use an arbitrary member function as an event handler.
502 * With this wrapper, you can use any object method, which accepts the right
503 * parameters (int, short) and returns void, as an event handler. This way you
504 * don't have to overload the operator() which can be confusing depending on the
507 * You can see an usage example in the Examples Section.
509 template < typename O, typename M >
514 * Member function callback constructor.
516 * It expects to receive a class as the first parameter (O), and a
517 * member function (of that class O) as the second parameter.
519 * When this instance is called with fd and ev as function arguments,
520 * object.method(fd, ev) will be called.
522 * @param object Object to be used.
523 * @param method Method to be called.
525 mem_cb(O& object, M method) throw():
526 _object(object), _method(method) {}
528 void operator() (int fd, type ev) { (_object.*_method)(fd, ev); }
541 * This class is the responsible for looping and dispatching events. Every time
542 * you need an event loop you should create an instance of this class.
544 * You can @link dispatcher::add add @endlink events to the dispatcher, and you
545 * can @link dispatcher::del remove @endlink them later or you can @link
546 * dispatcher::add_once add events to be processed just once @endlink. You can
547 * @link dispatcher::dispatch loop once or forever @endlink (well, of course you
548 * can break that forever removing all the events or by @link dispatcher::exit
549 * exiting the loop @endlink).
555 * Creates a default dispatcher (with just 1 priority).
557 * @see dispatcher(int) if you want to create a dispatcher with more
562 _event_base = static_cast< internal::event_base* >(
563 internal::event_init());
567 * Creates a dispatcher with npriorities priorities.
569 * @param npriorities Number of priority queues to use.
571 dispatcher(int npriorities) throw(std::bad_alloc)
573 _event_base = static_cast< internal::event_base* >(
574 internal::event_init());
575 if (!_event_base) throw std::bad_alloc();
576 // Can't fail because there is no way that it has active events
577 internal::event_base_priority_init(_event_base, npriorities);
580 #ifndef EVENTXX_NO_EVENT_BASE_FREE
581 /// Free dispatcher resources, see @ref Status section for details.
582 ~dispatcher() throw() { event_base_free(_event_base); }
586 * Adds an event to the dispatcher.
588 * @param e Event to add.
589 * @param priority Priority of the event.
591 void add(basic_event& e, int priority = DEFAULT_PRIORITY)
592 throw(invalid_priority)
594 internal::event_base_set(_event_base, &e);
595 if (priority != DEFAULT_PRIORITY
596 && internal::event_priority_set(&e, priority))
597 throw invalid_priority();
598 internal::event_add(&e, 0);
602 * Adds an event to the dispatcher with a timeout.
604 * The event is fired when there is activity on e or when to has elapsed,
605 * whatever come first.
607 * @param e Event to add.
609 * @param priority Priority of the event.
611 void add(basic_event& e, const time& to,
612 int priority = DEFAULT_PRIORITY)
613 throw(invalid_priority)
615 internal::event_base_set(_event_base, &e);
616 if (priority != DEFAULT_PRIORITY
617 && internal::event_priority_set(&e, priority))
618 throw invalid_priority();
619 // XXX HACK libevent don't use const
620 internal::event_add(&e, const_cast< time* >(&to));
624 * Adds a temporary event.
626 * Adds a temporary event, without the need of instantiating a new event
627 * object. Events added this way can't eventxx::PERSIST.
629 * @param fd File descriptor to monitor for events.
630 * @param ev Type of events to monitor.
631 * @param handler Callback function.
633 template < typename F >
634 void add_once(int fd, type ev, F& handler)
636 internal::event_once(fd, static_cast< short>(ev),
637 &dispatcher::wrapper< F >,
638 reinterpret_cast< void* >(&handler), 0);
642 * Adds a temporary event to with a C-style callback.
644 * Adds a temporary event, without the need of instantiating a new event
645 * object. Events added this way can't eventxx::PERSIST.
647 * @param fd File descriptor to monitor for events.
648 * @param ev Type of events to monitor.
649 * @param handler Callback function.
650 * @param arg Arbitrary pointer to pass to the handler as argument.
652 void add_once(int fd, type ev, ccallback_type handler, void* arg)
654 internal::event_once(fd, static_cast< short >(ev), handler,
659 * Adds a temporary event.
661 * Adds a temporary event, without the need of instantiating a new event
662 * object. Events added this way can't eventxx::PERSIST.
664 * @param fd File descriptor to monitor for events.
665 * @param ev Type of events to monitor.
666 * @param handler Callback function.
669 template < typename F >
670 void add_once(int fd, type ev, F& handler, const time& to)
672 internal::event_once(fd, static_cast< short >(ev),
673 &dispatcher::wrapper< F >,
674 reinterpret_cast< void* >(&handler),
675 // XXX HACK libevent don't use const
676 const_cast< time* >(&to));
680 * Adds a temporary event with a C-style callback.
682 * Adds a temporary event, without the need of instantiating a new event
683 * object. Events added this way can't eventxx::PERSIST.
685 * @param fd File descriptor to monitor for events.
686 * @param ev Type of events to monitor.
687 * @param handler Callback function.
688 * @param arg Arbitrary pointer to pass to the handler as argument.
691 void add_once(int fd, type ev, ccallback_type handler, void* arg,
694 internal::event_once(fd, static_cast< short >(ev), handler, arg,
695 // XXX HACK libevent don't use const
696 const_cast< time* >(&to));
700 * Adds a temporary timer.
702 * Adds a temporary timer, without the need of instantiating a new timer
705 * @param handler Callback function.
706 * @param to Timer's timeout.
708 template < typename F >
709 void add_once_timer(F& handler, const time& to)
711 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
712 reinterpret_cast< void* >(&handler),
713 // XXX HACK libevent don't use const
714 const_cast< time* >(&to));
718 * Adds a temporary timer with a C-style callback.
720 * Adds a temporary timer, without the need of instantiating a new timer
723 * @param handler Callback function.
724 * @param arg Arbitrary pointer to pass to the handler as argument.
725 * @param to Timer's timeout.
727 void add_once_timer(ccallback_type handler, void* arg, const time& to)
729 // XXX HACK libevent don't use const
730 internal::event_once(-1, EV_TIMEOUT, handler, arg,
731 const_cast< time* >(&to));
737 * The event e will be no longer monitored by this dispatcher.
739 * @param e Event to remove.
741 void del(basic_event& e) throw()
743 internal::event_del(&e);
747 * Main dispatcher loop.
749 * This function takes the control of the program, waiting for an event
750 * and calling its callbacks when it's fired. It only returns under
752 * - exit() was called.
753 * - All events were del()eted.
754 * - Another internal error.
755 * - eventxx::ONCE flag was set.
756 * - eventxx::NONBLOCK flag was set.
758 * @param flags If eventxx::ONCE is specified, then just one event is
759 * processed, if eventxx::NONBLOCK is specified, then this
760 * function returns even if there are no pending events.
762 * @return 0 if eventxx::NONBLOCK or eventxx::ONCE is set, 1 if there
763 * are no more events registered and EINTR if you use the
764 * @libevent's @c event_gotsig and return -1 in your
765 * @c event_sigcb callback.
767 int dispatch(int flags = 0) throw()
769 return internal::event_base_loop(_event_base, flags);
773 * Exit the dispatch() loop.
775 * @param to If a timeout is given, the loop exits after the specified
778 * @return Not very well specified by @libevent :-/ that's why it
779 * doesn't throw an exception either.
781 int exit(const time& to = time()) throw() // TODO throw(exception)
783 // XXX HACK libevent don't use const
784 return internal::event_base_loopexit(_event_base,
785 const_cast< time* >(&to));
789 internal::event_base* _event_base;
790 template < typename F >
791 static void wrapper(int fd, short ev, void* h)
793 F& handler = *reinterpret_cast< F* >(h);
794 handler(fd, *reinterpret_cast< type* >(&ev));
797 }; // struct dispatcher
799 } // namespace eventxx
801 #endif // _EVENTXX_HPP_
803 // vim: set filetype=cpp :