Updating HEAD branch #4; Merging CABAL -> HEAD.
[tinc] / src / event.c
1 /*
2     event.c -- event queue
3     Copyright (C) 2002 Guus Sliepen <guus@sliepen.warande.net>,
4                   2002 Ivo Timmermans <itimmermans@bigfoot.com>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: event.c,v 1.2 2002/04/09 15:26:00 zarq Exp $
21 */
22
23 #include "config.h"
24
25 #include <stdlib.h>
26 #include <xalloc.h>
27 #include <string.h>
28 #include <utils.h>
29 #include <avl_tree.h>
30 #include <time.h>
31
32 #include "event.h"
33
34 #include "system.h"
35
36 avl_tree_t *event_tree;
37 extern time_t now;
38
39 int id;
40
41 int event_compare(event_t *a, event_t *b)
42 {
43   if(a->time > b->time)
44     return 1;
45   if(a->time < b->time)
46     return -1;
47   return a->id - b->id; 
48 }
49
50 void init_events(void)
51 {
52 cp
53   event_tree = avl_alloc_tree((avl_compare_t)event_compare, NULL);
54 cp
55 }
56
57 void exit_events(void)
58 {
59 cp
60   avl_delete_tree(event_tree);
61 cp
62 }
63
64 event_t *new_event(void)
65 {
66   event_t *event;
67 cp
68   event = (event_t *)xmalloc_and_zero(sizeof(*event));
69 cp
70   return event;
71 }
72
73 void free_event(event_t *event)
74 {
75 cp
76   free(event);
77 cp
78 }
79
80 void event_add(event_t *event)
81 {
82 cp
83   event->id = ++id;
84   avl_insert(event_tree, event);
85 cp
86 }
87
88 void event_del(event_t *event)
89 {
90 cp
91   avl_delete(event_tree, event);
92 cp
93 }
94
95 event_t *get_expired_event(void)
96 {
97   event_t *event;
98 cp
99   if(event_tree->head)
100   {
101     event = (event_t *)event_tree->head->data;
102     if(event->time < now)
103     {
104       avl_delete(event_tree, event);
105       return event;
106     }
107   }
108 cp  
109   return NULL;
110 }