bf78d1fcc2ac28494fa4f501a5a5ed08067bdb26
[tinc] / rt / edge.c
1 /*
2     edge.c -- edge management
3
4     Copyright (C) 2003-2004 Guus Sliepen <guus@tinc-vpn.org>,
5                   2003-2004 Ivo Timmermans <ivo@tinc-vpn.org>
6
7     This program is free software; you can redistribute it and/or modify
8     it under the terms of the GNU General Public License as published by
9     the Free Software Foundation; either version 2 of the License, or
10     (at your option) any later version.
11
12     This program is distributed in the hope that it will be useful,
13     but WITHOUT ANY WARRANTY; without even the implied warranty of
14     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15     GNU General Public License for more details.
16
17     You should have received a copy of the GNU General Public License
18     along with this program; if not, write to the Free Software
19     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
21     $Id$
22 */
23
24 #include "system.h"
25
26 #include "rt/edge.h"
27 #include "rt/node.h"
28 #include "support/avl.h"
29 #include "support/xalloc.h"
30
31 avl_tree_t *edges;
32
33 static int edge_compare(const edge_t *a, const edge_t *b) {
34         return strcmp(a->to->name, b->to->name);
35 }
36
37 static int edge_weight_compare(const edge_t *a, const edge_t *b) {
38         return (a->weight - b->weight) ?: strcmp(a->from->name, b->from->name) ?: strcmp(a->to->name, b->to->name);
39 }
40
41 bool edge_init(void) {
42         edges = avl_tree_new((avl_compare_t)edge_weight_compare, NULL);
43
44         return true;
45 }
46
47 bool edge_exit(void) {
48         avl_tree_free(edges);
49
50         return true;
51 }
52
53 avl_tree_t *edge_tree_new(void) {
54         return avl_tree_new((avl_compare_t)edge_compare, (avl_action_t)edge_free);
55 }
56
57 void edge_tree_free(avl_tree_t *edge_tree) {
58         avl_tree_free(edge_tree);
59 }
60
61 edge_t *edge_new(void) {
62         edge_t *edge;
63
64         return clear(new(edge));
65 }
66
67 void edge_free(edge_t *edge) {
68         free(edge);
69 }
70
71 void edge_add(edge_t *edge) {
72         avl_add(edge->from->edges, edge);
73         avl_add(edges, edge);
74
75         edge->reverse = edge_get(edge->to, edge->from);
76
77         if(edge->reverse)
78                 edge->reverse->reverse = edge;
79 }
80
81 void edge_del(edge_t *edge) {
82         if(edge->reverse)
83                 edge->reverse->reverse = NULL;
84
85         avl_del(edges, edge);
86         avl_del(edge->from->edges, edge);
87 }
88
89 edge_t *edge_get(node_t *from, node_t *to) {
90         edge_t search = {0};
91         
92         search.from = from;
93         search.to = to;
94
95         return avl_get(from->edges, &search);
96 }
97