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 handler(fd, static_cast< type >(ev));
326 }; // struct event< F >
330 * This is the specialization of eventxx::event for C-style callbacks.
332 * @see eventxx::event
335 struct event< ccallback_type >: basic_event
339 * Creates a new event.
341 * @param fd File descriptor to monitor for events.
342 * @param ev Type of events to monitor (see eventxx::type).
343 * @param handler C-style callback function.
344 * @param arg Arbitrary pointer to pass to the handler as argument.
346 event(int fd, type ev, ccallback_type handler, void* arg = 0) throw()
348 event_set(this, fd, static_cast< short >(ev), handler, arg);
354 }; // struct event< ccallback_type >
358 * Timer event object.
360 * This is just a special case of event that is fired only when a timeout is
361 * reached. It's just a shortcut to:
363 * event(-1, 0, handler);
366 * @note This event can't eventxx::PERSIST.
367 * @see timer< ccallback_type >
369 template < typename F >
370 struct timer: event< F >
374 * Creates a new timer event.
376 * @param handler Callback functor.
378 timer(F& handler) throw()
380 evtimer_set(this, &event< F >::wrapper,
381 reinterpret_cast< void* >(&handler));
384 }; // struct timer< F >
388 * This is the specialization of eventxx::timer for C-style callbacks.
390 * @note This event can't eventxx::PERSIST.
394 struct timer< ccallback_type >: event< ccallback_type >
398 * Creates a new timer event.
400 * @param handler C-style callback function.
401 * @param arg Arbitrary pointer to pass to the handler as argument.
403 timer(ccallback_type handler, void* arg = 0) throw()
405 evtimer_set(this, handler, arg);
408 }; // struct timer< ccallback_type >
412 * Signal event object.
414 * This is just a special case of event that is fired when a signal is raised
415 * (instead of a file descriptor being active). It's just a shortcut to:
417 * event(signum, eventxx::SIGNAL, handler);
420 * @note This event always eventxx::PERSIST.
421 * @see signal< ccallback_type >
423 template < typename F >
424 struct signal: event< F >
428 * Creates a new signal event.
430 * @param signum Signal number to monitor.
431 * @param handler Callback functor.
433 signal(int signum, F& handler) throw()
435 signal_set(this, signum, &event< F >::wrapper,
436 reinterpret_cast< void* >(&handler));
440 * Event's signal number.
442 * @return Event's signal number.
446 return EVENT_SIGNAL(this);
449 }; // struct signal<F>
453 * This is the specialization of eventxx::signal for C-style callbacks.
455 * @note This event always eventxx::PERSIST.
459 struct signal< ccallback_type >: event< ccallback_type >
463 * Creates a new signal event.
465 * @param signum Signal number to monitor.
466 * @param handler C-style callback function.
467 * @param arg Arbitrary pointer to pass to the handler as argument.
469 signal(int signum, ccallback_type handler, void* arg = 0) throw()
471 signal_set(this, signum, handler, arg);
475 * Event's signal number.
477 * @return Event's signal number.
481 return EVENT_SIGNAL(this);
484 }; // struct signal< ccallback_type >
487 /// Shortcut to C-style event.
488 typedef eventxx::event< ccallback_type > cevent;
490 /// Shortcut to C-style timer.
491 typedef eventxx::timer< ccallback_type > ctimer;
493 /// Shortcut to C-style signal handler.
494 typedef eventxx::signal< ccallback_type > csignal;
497 * Helper functor to use an arbitrary member function as an event handler.
499 * With this wrapper, you can use any object method, which accepts the right
500 * parameters (int, short) and returns void, as an event handler. This way you
501 * don't have to overload the operator() which can be confusing depending on the
504 * You can see an usage example in the Examples Section.
506 template < typename O, typename M >
511 * Member function callback constructor.
513 * It expects to receive a class as the first parameter (O), and a
514 * member function (of that class O) as the second parameter.
516 * When this instance is called with fd and ev as function arguments,
517 * object.method(fd, ev) will be called.
519 * @param object Object to be used.
520 * @param method Method to be called.
522 mem_cb(O& object, M method) throw():
523 _object(object), _method(method) {}
525 void operator() (int fd, type ev) { (_object.*_method)(fd, ev); }
538 * This class is the responsible for looping and dispatching events. Every time
539 * you need an event loop you should create an instance of this class.
541 * You can @link dispatcher::add add @endlink events to the dispatcher, and you
542 * can @link dispatcher::del remove @endlink them later or you can @link
543 * dispatcher::add_once add events to be processed just once @endlink. You can
544 * @link dispatcher::dispatch loop once or forever @endlink (well, of course you
545 * can break that forever removing all the events or by @link dispatcher::exit
546 * exiting the loop @endlink).
552 * Creates a default dispatcher (with just 1 priority).
554 * @see dispatcher(int) if you want to create a dispatcher with more
559 _event_base = static_cast< internal::event_base* >(
560 internal::event_init());
564 * Creates a dispatcher with npriorities priorities.
566 * @param npriorities Number of priority queues to use.
568 dispatcher(int npriorities) throw(std::bad_alloc)
570 _event_base = static_cast< internal::event_base* >(
571 internal::event_init());
572 if (!_event_base) throw std::bad_alloc();
573 // Can't fail because there is no way that it has active events
574 internal::event_base_priority_init(_event_base, npriorities);
577 #ifndef EVENTXX_NO_EVENT_BASE_FREE
578 /// Free dispatcher resources, see @ref Status section for details.
579 ~dispatcher() throw() { event_base_free(_event_base); }
583 * Adds an event to the dispatcher.
585 * @param e Event to add.
586 * @param priority Priority of the event.
588 void add(basic_event& e, int priority = DEFAULT_PRIORITY)
589 throw(invalid_priority)
591 internal::event_base_set(_event_base, &e);
592 if (priority != DEFAULT_PRIORITY
593 && internal::event_priority_set(&e, priority))
594 throw invalid_priority();
595 internal::event_add(&e, 0);
599 * Adds an event to the dispatcher with a timeout.
601 * The event is fired when there is activity on e or when to has elapsed,
602 * whatever come first.
604 * @param e Event to add.
606 * @param priority Priority of the event.
608 void add(basic_event& e, const time& to,
609 int priority = DEFAULT_PRIORITY)
610 throw(invalid_priority)
612 internal::event_base_set(_event_base, &e);
613 if (priority != DEFAULT_PRIORITY
614 && internal::event_priority_set(&e, priority))
615 throw invalid_priority();
616 // XXX HACK libevent don't use const
617 internal::event_add(&e, const_cast< time* >(&to));
621 * Adds a temporary event.
623 * Adds a temporary event, without the need of instantiating a new event
624 * object. Events added this way can't eventxx::PERSIST.
626 * @param fd File descriptor to monitor for events.
627 * @param ev Type of events to monitor.
628 * @param handler Callback function.
630 template < typename F >
631 void add_once(int fd, type ev, F& handler)
633 internal::event_once(fd, static_cast< short>(ev),
634 &dispatcher::wrapper< F >,
635 reinterpret_cast< void* >(&handler), 0);
639 * Adds a temporary event to with a C-style callback.
641 * Adds a temporary event, without the need of instantiating a new event
642 * object. Events added this way can't eventxx::PERSIST.
644 * @param fd File descriptor to monitor for events.
645 * @param ev Type of events to monitor.
646 * @param handler Callback function.
647 * @param arg Arbitrary pointer to pass to the handler as argument.
649 void add_once(int fd, type ev, ccallback_type handler, void* arg)
651 internal::event_once(fd, static_cast< short >(ev), handler,
656 * Adds a temporary event.
658 * Adds a temporary event, without the need of instantiating a new event
659 * object. Events added this way can't eventxx::PERSIST.
661 * @param fd File descriptor to monitor for events.
662 * @param ev Type of events to monitor.
663 * @param handler Callback function.
666 template < typename F >
667 void add_once(int fd, type ev, F& handler, const time& to)
669 internal::event_once(fd, static_cast< short >(ev),
670 &dispatcher::wrapper< F >,
671 reinterpret_cast< void* >(&handler),
672 // XXX HACK libevent don't use const
673 const_cast< time* >(&to));
677 * Adds a temporary event with a C-style callback.
679 * Adds a temporary event, without the need of instantiating a new event
680 * object. Events added this way can't eventxx::PERSIST.
682 * @param fd File descriptor to monitor for events.
683 * @param ev Type of events to monitor.
684 * @param handler Callback function.
685 * @param arg Arbitrary pointer to pass to the handler as argument.
688 void add_once(int fd, type ev, ccallback_type handler, void* arg,
691 internal::event_once(fd, static_cast< short >(ev), handler, arg,
692 // XXX HACK libevent don't use const
693 const_cast< time* >(&to));
697 * Adds a temporary timer.
699 * Adds a temporary timer, without the need of instantiating a new timer
702 * @param handler Callback function.
703 * @param to Timer's timeout.
705 template < typename F >
706 void add_once_timer(F& handler, const time& to)
708 internal::event_once(-1, EV_TIMEOUT, &dispatcher::wrapper< F >,
709 reinterpret_cast< void* >(&handler),
710 // XXX HACK libevent don't use const
711 const_cast< time* >(&to));
715 * Adds a temporary timer with a C-style callback.
717 * Adds a temporary timer, without the need of instantiating a new timer
720 * @param handler Callback function.
721 * @param arg Arbitrary pointer to pass to the handler as argument.
722 * @param to Timer's timeout.
724 void add_once_timer(ccallback_type handler, void* arg, const time& to)
726 // XXX HACK libevent don't use const
727 internal::event_once(-1, EV_TIMEOUT, handler, arg,
728 const_cast< time* >(&to));
734 * The event e will be no longer monitored by this dispatcher.
736 * @param e Event to remove.
738 void del(basic_event& e) throw()
740 internal::event_del(&e);
744 * Main dispatcher loop.
746 * This function takes the control of the program, waiting for an event
747 * and calling its callbacks when it's fired. It only returns under
749 * - exit() was called.
750 * - All events were del()eted.
751 * - Another internal error.
752 * - eventxx::ONCE flag was set.
753 * - eventxx::NONBLOCK flag was set.
755 * @param flags If eventxx::ONCE is specified, then just one event is
756 * processed, if eventxx::NONBLOCK is specified, then this
757 * function returns even if there are no pending events.
759 * @return 0 if eventxx::NONBLOCK or eventxx::ONCE is set, 1 if there
760 * are no more events registered and EINTR if you use the
761 * @libevent's @c event_gotsig and return -1 in your
762 * @c event_sigcb callback.
764 int dispatch(int flags = 0) throw()
766 return internal::event_base_loop(_event_base, flags);
770 * Exit the dispatch() loop.
772 * @param to If a timeout is given, the loop exits after the specified
775 * @return Not very well specified by @libevent :-/ that's why it
776 * doesn't throw an exception either.
778 int exit(const time& to = time()) throw() // TODO throw(exception)
780 // XXX HACK libevent don't use const
781 return internal::event_base_loopexit(_event_base,
782 const_cast< time* >(&to));
786 internal::event_base* _event_base;
787 template < typename F >
788 static void wrapper(int fd, short ev, void* h)
790 F& handler = *reinterpret_cast< F* >(h);
791 handler(fd, *reinterpret_cast< type* >(&ev));
795 // Hide nonsense copy-constructor and operator=
796 dispatcher(const dispatcher&);
797 dispatcher& operator=(const dispatcher&);
799 }; // struct dispatcher
801 } // namespace eventxx
803 #endif // _EVENTXX_HPP_
805 // vim: set filetype=cpp :