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