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) {
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_attach(&q->source, context);
97 void flx_time_event_queue_free(flxTimeEventQueue *q) {
100 while (q->prioq->root)
101 flx_time_event_queue_remove(q, q->prioq->root->data);
102 flx_prio_queue_free(q->prioq);
104 g_source_destroy(&q->source);
105 g_source_unref(&q->source);
108 flxTimeEvent* flx_time_event_queue_add(flxTimeEventQueue *q, const GTimeVal *timeval, void (*callback)(flxTimeEvent *e, void *userdata), void *userdata) {
116 e = g_new(flxTimeEvent, 1);
118 e->expiry = *timeval;
119 e->callback = callback;
120 e->userdata = userdata;
122 e->node = flx_prio_queue_put(q->prioq, e);
127 void flx_time_event_queue_remove(flxTimeEventQueue *q, flxTimeEvent *e) {
130 g_assert(e->queue == q);
132 flx_prio_queue_remove(q->prioq, e->node);
136 void flx_time_event_queue_update(flxTimeEventQueue *q, flxTimeEvent *e, const GTimeVal *timeval) {
139 g_assert(e->queue == q);
141 e->expiry = *timeval;
143 flx_prio_queue_shuffle(q->prioq, e->node);
146 flxTimeEvent* flx_time_event_queue_root(flxTimeEventQueue *q) {
149 return q->prioq->root ? q->prioq->root->data : NULL;
152 flxTimeEvent* flx_time_event_next(flxTimeEvent *e) {
155 return e->node->next->data;