1 #include "timeeventq.h"
4 static gint compare(gconstpointer _a, gconstpointer _b) {
5 const AvahiTimeEvent *a = _a, *b = _b;
7 return avahi_timeval_compare(&a->expiry, &b->expiry);
10 static gboolean prepare_func(GSource *source, gint *timeout) {
11 AvahiTimeEventQueue *q = (AvahiTimeEventQueue*) source;
18 if (!q->prioq->root) {
23 e = q->prioq->root->data;
26 g_source_get_current_time(source, &now);
28 if (avahi_timeval_compare(&now, &e->expiry) >= 0) {
33 *timeout = (gint) (avahi_timeval_diff(&e->expiry, &now)/1000);
38 static gboolean check_func(GSource *source) {
39 AvahiTimeEventQueue *q = (AvahiTimeEventQueue*) source;
48 e = q->prioq->root->data;
51 g_source_get_current_time(source, &now);
53 return avahi_timeval_compare(&now, &e->expiry) >= 0;
56 static gboolean dispatch_func(GSource *source, GSourceFunc callback, gpointer user_data) {
57 AvahiTimeEventQueue *q = (AvahiTimeEventQueue*) source;
62 g_source_get_current_time(source, &now);
64 while (q->prioq->root) {
65 AvahiTimeEvent *e = q->prioq->root->data;
67 if (avahi_timeval_compare(&now, &e->expiry) < 0)
70 g_assert(e->callback);
71 e->callback(e, e->userdata);
77 AvahiTimeEventQueue* avahi_time_event_queue_new(GMainContext *context, gint priority) {
78 AvahiTimeEventQueue *q;
80 static GSourceFuncs source_funcs = {
89 q = (AvahiTimeEventQueue*) g_source_new(&source_funcs, sizeof(AvahiTimeEventQueue));
90 q->prioq = avahi_prio_queue_new(compare);
92 g_source_set_priority((GSource*) q, priority);
94 g_source_attach(&q->source, context);
99 void avahi_time_event_queue_free(AvahiTimeEventQueue *q) {
102 while (q->prioq->root)
103 avahi_time_event_queue_remove(q, q->prioq->root->data);
104 avahi_prio_queue_free(q->prioq);
106 g_source_destroy(&q->source);
107 g_source_unref(&q->source);
110 AvahiTimeEvent* avahi_time_event_queue_add(AvahiTimeEventQueue *q, const GTimeVal *timeval, void (*callback)(AvahiTimeEvent *e, void *userdata), void *userdata) {
118 e = g_new(AvahiTimeEvent, 1);
120 e->expiry = *timeval;
121 e->callback = callback;
122 e->userdata = userdata;
124 e->node = avahi_prio_queue_put(q->prioq, e);
129 void avahi_time_event_queue_remove(AvahiTimeEventQueue *q, AvahiTimeEvent *e) {
132 g_assert(e->queue == q);
134 avahi_prio_queue_remove(q->prioq, e->node);
138 void avahi_time_event_queue_update(AvahiTimeEventQueue *q, AvahiTimeEvent *e, const GTimeVal *timeval) {
141 g_assert(e->queue == q);
143 e->expiry = *timeval;
145 avahi_prio_queue_shuffle(q->prioq, e->node);
148 AvahiTimeEvent* avahi_time_event_queue_root(AvahiTimeEventQueue *q) {
151 return q->prioq->root ? q->prioq->root->data : NULL;
154 AvahiTimeEvent* avahi_time_event_next(AvahiTimeEvent *e) {
157 return e->node->next->data;