2 event.c -- I/O, timeout, and event handling
3 Copyright (C) 2012-2022 Guus Sliepen <guus@tinc-vpn.org>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 static int io_compare(const io_t *a, const io_t *b) {
31 if(a->event < b->event) {
35 if(a->event > b->event) {
43 static int timeout_compare(const timeout_t *a, const timeout_t *b) {
45 timersub(&a->tv, &b->tv, &diff);
55 if(diff.tv_usec < 0) {
59 if(diff.tv_usec > 0) {
63 uintptr_t ap = (uintptr_t)a;
64 uintptr_t bp = (uintptr_t)b;
77 splay_tree_t io_tree = {.compare = (splay_compare_t)io_compare};
78 splay_tree_t timeout_tree = {.compare = (splay_compare_t)timeout_compare};
80 void timeout_add(timeout_t *timeout, timeout_cb_t cb, void *data, const struct timeval *tv) {
83 timeout->node.data = timeout;
85 timeout_set(timeout, tv);
88 void timeout_set(timeout_t *timeout, const struct timeval *tv) {
89 if(timerisset(&timeout->tv)) {
90 splay_unlink_node(&timeout_tree, &timeout->node);
94 gettimeofday(&now, NULL);
97 timeradd(&now, tv, &timeout->tv);
99 if(!splay_insert_node(&timeout_tree, &timeout->node)) {
104 void timeout_del(timeout_t *timeout) {
109 splay_unlink_node(&timeout_tree, &timeout->node);
111 timeout->tv = (struct timeval) {
116 struct timeval *timeout_execute(struct timeval *diff) {
117 gettimeofday(&now, NULL);
118 struct timeval *tv = NULL;
120 while(timeout_tree.head) {
121 timeout_t *timeout = timeout_tree.head->data;
122 timersub(&timeout->tv, &now, diff);
124 if(diff->tv_sec < 0) {
125 timeout->cb(timeout->data);
127 if(timercmp(&timeout->tv, &now, <)) {
128 timeout_del(timeout);