spaces
[oweals/gnunet.git] / src / util / container_heap.c
1 /*
2   This file is part of GNUnet.
3   (C) 2008, 2009 Christian Grothoff (and other contributing authors)
4   
5   GNUnet is free software; you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published
7   by the Free Software Foundation; either version 2, or (at your
8   option) any later version.
9   
10   GNUnet is distributed in the hope that it will be useful, but
11   WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   General Public License for more details.
14   
15   You should have received a copy of the GNU General Public License
16   along with GNUnet; see the file COPYING.  If not, write to the
17   Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18   Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file util/container_heap.c
23  * @brief Implementation of a heap
24  * @author Nathan Evans
25  * @author Christian Grothoff
26  */
27
28 #include "platform.h"
29 #include "gnunet_util_lib.h"
30
31
32 #define DEBUG 0
33
34 /**
35  * Node in the heap.
36  */
37 struct GNUNET_CONTAINER_HeapNode
38 {
39   /**
40    * Heap this node belongs to.
41    */
42   struct GNUNET_CONTAINER_Heap *heap;
43
44   /**
45    * Parent node.
46    */
47   struct GNUNET_CONTAINER_HeapNode *parent;
48
49   /**
50    * Left child.
51    */
52   struct GNUNET_CONTAINER_HeapNode *left_child;
53
54   /**
55    * Right child.
56    */
57   struct GNUNET_CONTAINER_HeapNode *right_child;
58
59   /**
60    * Our element.
61    */
62   void *element;
63
64   /**
65    * Cost for this element.
66    */
67   GNUNET_CONTAINER_HeapCostType cost;
68
69   /**
70    * Number of elements below this node in the heap
71    * (excluding this node itself).
72    */
73   unsigned int tree_size;
74
75 };
76
77 /**
78  * Handle to a node in a heap.
79  */
80 struct GNUNET_CONTAINER_Heap
81 {
82
83   /**
84    * Root of the heap.
85    */
86   struct GNUNET_CONTAINER_HeapNode *root;
87
88   /**
89    * Current position of our random walk.
90    */
91   struct GNUNET_CONTAINER_HeapNode *walk_pos;
92
93   /**
94    * Number of elements in the heap.
95    */
96   unsigned int size;
97   
98   /**
99    * How is the heap sorted?
100    */
101   enum GNUNET_CONTAINER_HeapOrder order;
102
103 };
104
105
106 #if DEBUG
107 /**
108  * Check if internal invariants hold for the given node.
109  *
110  * @param node subtree to check
111  */ 
112 static void
113 check (const struct GNUNET_CONTAINER_HeapNode *node)
114 {  
115   if (NULL == node)
116     return;
117   GNUNET_assert (node->tree_size ==
118                  ( (node->left_child == NULL) ? 0 : 1 + node->left_child->tree_size) +
119                  ( (node->right_child == NULL) ? 0 : 1 + node->right_child->tree_size) );
120   check (node->left_child);
121   check (node->right_child);
122 }
123
124
125 #define CHECK(n) check(n)
126 #else
127 #define CHECK(n) do {} while (0)
128 #endif
129
130
131 /**
132  * Create a new heap.
133  *
134  * @param order how should the heap be sorted?
135  * @return handle to the heap
136  */
137 struct GNUNET_CONTAINER_Heap *
138 GNUNET_CONTAINER_heap_create (enum GNUNET_CONTAINER_HeapOrder order)
139 {
140   struct GNUNET_CONTAINER_Heap *heap;
141
142   heap = GNUNET_malloc (sizeof (struct GNUNET_CONTAINER_Heap));
143   heap->order = order;
144   return heap;
145 }
146
147
148 /**
149  * Destroys the heap.  Only call on a heap that
150  * is already empty.
151  *
152  * @param heap heap to destroy
153  */
154 void
155 GNUNET_CONTAINER_heap_destroy (struct GNUNET_CONTAINER_Heap *heap)
156 {
157   GNUNET_break (heap->size == 0);
158   GNUNET_free (heap);
159 }
160
161
162 /**
163  * Get element stored at root of heap.
164  *
165  * @param heap heap to inspect
166  * @return NULL if heap is empty
167  */
168 void *
169 GNUNET_CONTAINER_heap_peek (const struct GNUNET_CONTAINER_Heap *heap)
170 {
171   if (heap->root == NULL)
172     return NULL;
173   return heap->root->element;
174 }
175
176
177 /**
178  * Get the current size of the heap
179  *
180  * @param heap the heap to get the size of
181  * @return number of elements stored
182  */
183 unsigned int
184 GNUNET_CONTAINER_heap_get_size (const struct GNUNET_CONTAINER_Heap *heap)
185 {
186   return heap->size;
187 }
188
189
190 /**
191  * Iterate over the children of the given node.
192  *
193  * @param heap argument to give to iterator
194  * @param node node to iterate over
195  * @param iterator function to call on each node
196  * @param iterator_cls closure for iterator
197  * @return GNUNET_YES to continue to iterate
198  */
199 static int
200 node_iterator (const struct GNUNET_CONTAINER_Heap *heap,
201                struct GNUNET_CONTAINER_HeapNode *node,
202                GNUNET_CONTAINER_HeapIterator iterator, 
203                void *iterator_cls)
204 {
205   if (node == NULL)
206     return GNUNET_YES;
207   if (GNUNET_YES != node_iterator (heap,
208                                    node->left_child,
209                                    iterator,
210                                    iterator_cls))
211     return GNUNET_NO;
212   if (GNUNET_YES != node_iterator (heap,
213                                    node->right_child,
214                                    iterator, 
215                                    iterator_cls))
216     return GNUNET_NO;
217   return iterator (iterator_cls,
218                    node,
219                    node->element,
220                    node->cost);
221 }
222
223
224 /**
225  * Iterate over all entries in the heap.
226  *
227  * @param heap the heap
228  * @param iterator function to call on each entry
229  * @param iterator_cls closure for iterator
230  */
231 void
232 GNUNET_CONTAINER_heap_iterate (const struct GNUNET_CONTAINER_Heap *heap,
233                                GNUNET_CONTAINER_HeapIterator iterator,
234                                void *iterator_cls)
235 {
236   (void) node_iterator (heap, heap->root, iterator, iterator_cls);
237 }
238
239
240 /**
241  * Perform a random walk of the tree.  The walk is biased
242  * towards elements closer to the root of the tree (since
243  * each walk starts at the root and ends at a random leaf).
244  * The heap internally tracks the current position of the
245  * walk.
246  *
247  * @param heap heap to walk
248  * @return data stored at the next random node in the walk;
249  *         NULL if the tree is empty.
250  */
251 void *
252 GNUNET_CONTAINER_heap_walk_get_next (struct GNUNET_CONTAINER_Heap *heap)
253 {
254   struct GNUNET_CONTAINER_HeapNode *pos;
255   void *element;
256
257   if (heap->root == NULL)
258     return NULL;
259   pos = heap->walk_pos;
260   if (pos == NULL) 
261     pos = heap->root;   
262   element = pos->element;
263   heap->walk_pos 
264     = (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 2))
265     ? pos->right_child 
266     : pos->left_child;
267   return element;
268 }
269
270
271 /**
272  * Insert the given node 'node' into the subtree starting
273  * at 'pos' (while keeping the tree somewhat balanced).
274  *
275  * @param heap heap to modify
276  * @param pos existing tree
277  * @param node node to insert (which may be a subtree itself)
278  */
279 static void
280 insert_node (struct GNUNET_CONTAINER_Heap *heap,
281              struct GNUNET_CONTAINER_HeapNode *pos,
282              struct GNUNET_CONTAINER_HeapNode *node)
283 {
284   struct GNUNET_CONTAINER_HeapNode *parent;
285
286   GNUNET_assert (node->parent == NULL);
287   while ( (heap->order == GNUNET_CONTAINER_HEAP_ORDER_MAX) 
288           ? (pos->cost >= node->cost) 
289           : (pos->cost <= node->cost) )
290     {
291       /* node is descendent of pos */
292       pos->tree_size += (1 + node->tree_size);
293       if (pos->left_child == NULL)
294         {
295           pos->left_child = node;
296           node->parent = pos;
297           return;
298         }
299       if (pos->right_child == NULL)
300         {
301           pos->right_child = node;
302           node->parent = pos;
303           return;
304         }
305       /* keep it balanced by descending into smaller subtree */
306       if (pos->left_child->tree_size < pos->right_child->tree_size)
307         pos = pos->left_child;
308       else
309         pos = pos->right_child;
310     }
311   /* make 'node' parent of 'pos' */
312   parent = pos->parent;
313   pos->parent = NULL;
314   node->parent = parent;
315   if (NULL == parent)
316     {
317       heap->root = node;
318     }
319   else
320     {
321       if (parent->left_child == pos)
322         parent->left_child = node;
323       else
324         parent->right_child = node;
325     }
326   /* insert 'pos' below 'node' */
327   insert_node (heap, node, pos);
328   CHECK (pos);
329 }
330
331
332 /**
333  * Inserts a new element into the heap.
334  *
335  * @param heap heap to modify
336  * @param element element to insert
337  * @param cost cost for the element
338  * @return node for the new element
339  */
340 struct GNUNET_CONTAINER_HeapNode *
341 GNUNET_CONTAINER_heap_insert (struct GNUNET_CONTAINER_Heap *heap,
342                               void *element,
343                               GNUNET_CONTAINER_HeapCostType cost)
344 {
345   struct GNUNET_CONTAINER_HeapNode *node;
346
347   node = GNUNET_malloc (sizeof (struct GNUNET_CONTAINER_HeapNode));
348   node->heap = heap;
349   node->element = element;
350   node->cost = cost;
351   heap->size++;
352   if (NULL == heap->root)
353     heap->root = node;
354   else
355     insert_node (heap, heap->root, node);
356   GNUNET_assert (heap->size == heap->root->tree_size + 1);
357   CHECK (heap->root);
358   return node;
359 }
360
361
362 /**
363  * Remove root of the heap.
364  *
365  * @param heap heap to modify
366  * @return element data stored at the root node, NULL if heap is empty
367  */
368 void *
369 GNUNET_CONTAINER_heap_remove_root (struct GNUNET_CONTAINER_Heap *heap)
370 {
371   void *ret;
372   struct GNUNET_CONTAINER_HeapNode *root;
373
374   if (NULL == (root = heap->root))
375     return NULL;
376   heap->size--;
377   ret = root->element;
378   if (root->left_child == NULL)
379     {
380       heap->root = root->right_child;
381       if (root->right_child != NULL)
382         root->right_child->parent = NULL;
383     }
384   else if (root->right_child == NULL)
385     {
386       heap->root = root->left_child;
387       root->left_child->parent = NULL;
388     }
389   else
390     {
391       root->left_child->parent = NULL;
392       root->right_child->parent = NULL;
393       heap->root = root->left_child;
394       insert_node (heap, heap->root, root->right_child);
395     }
396   GNUNET_free (root);
397 #if DEBUG
398   GNUNET_assert (( (heap->size == 0) && 
399                    (heap->root == NULL) ) ||
400                  (heap->size == heap->root->tree_size + 1) );
401   CHECK (heap->root);
402 #endif
403   return ret;
404 }
405
406
407 /**
408  * Remove the given node 'node' from the tree and update
409  * the 'tree_size' fields accordingly.  Preserves the
410  * children of 'node' and does NOT change the overall
411  * 'size' field of the tree.
412  */
413 static void
414 remove_node (struct GNUNET_CONTAINER_HeapNode *node)
415 {
416   struct GNUNET_CONTAINER_HeapNode *ancestor;
417   struct GNUNET_CONTAINER_Heap *heap = node->heap;
418
419   /* update 'size' of the ancestors */
420   ancestor = node;
421   while (NULL != (ancestor = ancestor->parent))    
422     ancestor->tree_size--;
423
424   /* update 'size' of node itself */
425   if (node->left_child != NULL)
426     node->tree_size -= (1 + node->left_child->tree_size);
427   if (node->right_child != NULL)
428     node->tree_size -= (1 + node->right_child->tree_size);
429
430   /* unlink 'node' itself and insert children in its place */
431   if (node->parent == NULL)
432     {
433       if (node->left_child != NULL)
434         {
435           heap->root = node->left_child;
436           node->left_child->parent = NULL;
437           if (node->right_child != NULL)
438             {
439               node->right_child->parent = NULL;
440               insert_node (heap, heap->root, node->right_child);        
441             }
442         }
443       else
444         {
445           heap->root = node->right_child;
446           if (node->right_child != NULL)
447             node->right_child->parent = NULL;
448         }
449     }
450   else
451     {
452       if (node->parent->left_child == node)
453         node->parent->left_child = NULL;
454       else
455         node->parent->right_child = NULL;
456       if (node->left_child != NULL)
457         {
458           node->left_child->parent = NULL;
459           node->parent->tree_size -= (1 + node->left_child->tree_size);
460           insert_node (heap, node->parent, node->left_child);
461         }
462       if (node->right_child != NULL)
463         {
464           node->right_child->parent = NULL;
465           node->parent->tree_size -= (1 + node->right_child->tree_size);
466           insert_node (heap, node->parent, node->right_child);
467         }
468     }
469   node->parent = NULL;
470   node->left_child = NULL;
471   node->right_child = NULL;
472   GNUNET_assert (node->tree_size == 0);
473   CHECK (heap->root);
474 }
475
476
477 /**
478  * Removes a node from the heap.
479  * 
480  * @param node node to remove
481  * @return element data stored at the node
482  */
483 void *
484 GNUNET_CONTAINER_heap_remove_node (struct GNUNET_CONTAINER_HeapNode *node)
485 {
486   void *ret;
487   struct GNUNET_CONTAINER_Heap *heap;
488
489   heap = node->heap; 
490   CHECK (heap->root);
491   if (heap->walk_pos == node)
492     (void) GNUNET_CONTAINER_heap_walk_get_next (heap);
493   remove_node (node);
494   heap->size--;
495   ret = node->element;
496   if (heap->walk_pos == node)
497     heap->walk_pos = NULL;
498   GNUNET_free (node);
499 #if DEBUG
500   CHECK (heap->root);
501   GNUNET_assert (( (heap->size == 0) && 
502                    (heap->root == NULL) ) ||
503                  (heap->size == heap->root->tree_size + 1) );
504 #endif
505   return ret;
506 }
507
508
509 /**
510  * Updates the cost of any node in the tree
511  *
512  * @param heap heap to modify
513  * @param node node for which the cost is to be changed
514  * @param new_cost new cost for the node
515  */
516 void
517 GNUNET_CONTAINER_heap_update_cost (struct GNUNET_CONTAINER_Heap *heap,
518                                    struct GNUNET_CONTAINER_HeapNode *node, 
519                                    GNUNET_CONTAINER_HeapCostType new_cost)
520 {
521 #if DEBUG
522   GNUNET_assert ( ( (heap->size == 0) && 
523                     (heap->root == NULL) ) ||
524                   (heap->size == heap->root->tree_size + 1) );
525   CHECK (heap->root);
526 #endif
527   remove_node (node);
528 #if DEBUG
529   CHECK (heap->root);
530   GNUNET_assert ( ( (heap->size == 1) && 
531                     (heap->root == NULL) ) ||
532                   (heap->size == heap->root->tree_size + 2) );
533 #endif
534   node->cost = new_cost;
535   if (heap->root == NULL)
536     heap->root = node;
537   else
538     insert_node (heap, heap->root, node);
539 #if DEBUG
540   CHECK (heap->root);
541   GNUNET_assert ( ( (heap->size == 0) && 
542                     (heap->root == NULL) ) ||
543                   (heap->size == heap->root->tree_size + 1) );
544 #endif
545 }
546
547
548 /* end of heap.c */