1 #include "timeeventq.h"
4 static gint compare(gconstpointer _a, gconstpointer _b) {
5 const flxTimeEvent *a = _a, *b = _b;
7 return flx_timeval_compare(&a->expiry, &b->expiry);
10 static gboolean prepare_func(GSource *source, gint *timeout) {
11 flxTimeEventQueue *q = (flxTimeEventQueue*) source;
18 if (!q->prioq->root) {
23 e = q->prioq->root->data;
26 g_source_get_current_time(source, &now);
28 if (flx_timeval_compare(&now, &e->expiry) >= 0) {
33 *timeout = (gint) (flx_timeval_diff(&e->expiry, &now)/1000);
38 static gboolean check_func(GSource *source) {
39 flxTimeEventQueue *q = (flxTimeEventQueue*) source;
48 e = q->prioq->root->data;
51 g_source_get_current_time(source, &now);
53 return flx_timeval_compare(&now, &e->expiry) >= 0;
56 static gboolean dispatch_func(GSource *source, GSourceFunc callback, gpointer user_data) {
57 flxTimeEventQueue *q = (flxTimeEventQueue*) source;
62 g_source_get_current_time(source, &now);
64 while (q->prioq->root) {
65 flxTimeEvent *e = q->prioq->root->data;
67 if (flx_timeval_compare(&now, &e->expiry) < 0)
70 g_assert(e->callback);
71 e->callback(e, e->userdata);
77 flxTimeEventQueue* flx_time_event_queue_new(GMainContext *context, gint priority) {
80 static GSourceFuncs source_funcs = {
89 q = (flxTimeEventQueue*) g_source_new(&source_funcs, sizeof(flxTimeEventQueue));
90 q->prioq = flx_prio_queue_new(compare);
92 g_source_set_priority((GSource*) q, priority);
94 g_source_attach(&q->source, context);
99 void flx_time_event_queue_free(flxTimeEventQueue *q) {
102 while (q->prioq->root)
103 flx_time_event_queue_remove(q, q->prioq->root->data);
104 flx_prio_queue_free(q->prioq);
106 g_source_destroy(&q->source);
107 g_source_unref(&q->source);
110 flxTimeEvent* flx_time_event_queue_add(flxTimeEventQueue *q, const GTimeVal *timeval, void (*callback)(flxTimeEvent *e, void *userdata), void *userdata) {
118 e = g_new(flxTimeEvent, 1);
120 e->expiry = *timeval;
121 e->callback = callback;
122 e->userdata = userdata;
124 e->node = flx_prio_queue_put(q->prioq, e);
129 void flx_time_event_queue_remove(flxTimeEventQueue *q, flxTimeEvent *e) {
132 g_assert(e->queue == q);
134 flx_prio_queue_remove(q->prioq, e->node);
138 void flx_time_event_queue_update(flxTimeEventQueue *q, flxTimeEvent *e, const GTimeVal *timeval) {
141 g_assert(e->queue == q);
143 e->expiry = *timeval;
145 flx_prio_queue_shuffle(q->prioq, e->node);
148 flxTimeEvent* flx_time_event_queue_root(flxTimeEventQueue *q) {
151 return q->prioq->root ? q->prioq->root->data : NULL;
154 flxTimeEvent* flx_time_event_next(flxTimeEvent *e) {
157 return e->node->next->data;