libevent, a very good c network library, has recently begun to analyze.

Where to start? I choose to start from the simplest basic things, from simplicity to complexity.

Today, we will generate the minimum heap of libevent, and realize how the author of libevent realizes the minimum heap. The minimum heap is used in libevent's time management to calculate whether to time out.

Minimum heap: a sort of complete binary tree, in which the data value of any non terminal node is not greater than the value of its left and right child nodes.

### 1. Min? Heap? Shift? Up? Adjust up after inserting element

### 2. Min? Heap? Shift? Down? Element adjust down (delete element)

### 3. Code Notes

1 /* 2 * Copyright (c) 2006 Maxim Yegorushkin <maxim.yegorushkin@gmail.com> 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. The name of the author may not be used to endorse or promote products 14 * derived from this software without specific prior written permission. 15 * 16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 */ 27 #ifndef _MIN_HEAP_H_ 28 #define _MIN_HEAP_H_ 29 30 #include "event.h" 31 #include "evutil.h" 32 33 //The minimum heap is a sort of complete binary tree, in which the data value of any non terminal node is not greater than the value of its left and right child nodes. 34 typedef struct min_heap 35 { 36 //Dynamically allocate memory to save points to*event Pointer to 37 struct event** p; 38 //n Is the number of elements,a Number capacity 39 unsigned n, a; 40 } min_heap_t; 41 42 static inline void min_heap_ctor(min_heap_t* s); 43 static inline void min_heap_dtor(min_heap_t* s); 44 static inline void min_heap_elem_init(struct event* e); 45 static inline int min_heap_elem_greater(struct event *a, struct event *b); 46 static inline int min_heap_empty(min_heap_t* s); 47 static inline unsigned min_heap_size(min_heap_t* s); 48 static inline struct event* min_heap_top(min_heap_t* s); 49 static inline int min_heap_reserve(min_heap_t* s, unsigned n); 50 static inline int min_heap_push(min_heap_t* s, struct event* e); 51 static inline struct event* min_heap_pop(min_heap_t* s); 52 static inline int min_heap_erase(min_heap_t* s, struct event* e); 53 static inline void min_heap_shift_up_(min_heap_t* s, unsigned hole_index, struct event* e); 54 static inline void min_heap_shift_down_(min_heap_t* s, unsigned hole_index, struct event* e); 55 56 int min_heap_elem_greater(struct event *a, struct event *b) 57 { 58 return evutil_timercmp(&a->ev_timeout, &b->ev_timeout, >); 59 } 60 61 void min_heap_ctor(min_heap_t* s) { s->p = 0; s->n = 0; s->a = 0; } 62 void min_heap_dtor(min_heap_t* s) { if(s->p) free(s->p); } 63 void min_heap_elem_init(struct event* e) { e->min_heap_idx = -1; } 64 int min_heap_empty(min_heap_t* s) { return 0u == s->n; } 65 unsigned min_heap_size(min_heap_t* s) { return s->n; } 66 struct event* min_heap_top(min_heap_t* s) { return s->n ? *s->p : 0; } 67 68 //Insert element 69 int min_heap_push(min_heap_t* s, struct event* e) 70 { 71 //Check memory 72 if(min_heap_reserve(s, s->n + 1)) 73 return -1; 74 75 //Insert element up adjustment 76 min_heap_shift_up_(s, s->n++, e); 77 return 0; 78 } 79 80 //pop Head element 81 struct event* min_heap_pop(min_heap_t* s) 82 { 83 if(s->n) 84 { 85 //->Priority ratio*high 86 //e Pointer to the head element 87 struct event* e = *s->p; 88 //Element down, 0 U Represents the head node index, s->p[--s->n]: The lowest and rightmost element, used to fill in the empty position after insertion 89 min_heap_shift_down_(s, 0u, s->p[--s->n]); 90 91 //The header element is indexed in the heap as-1，Pile out 92 e->min_heap_idx = -1; 93 return e; 94 } 95 return 0; 96 } 97 98 //Delete in heap equal to e Elements of 99 int min_heap_erase(min_heap_t* s, struct event* e) 100 { 101 if(((unsigned int)-1) != e->min_heap_idx) 102 { 103 struct event *last = s->p[--s->n]; 104 //Parent node index 105 unsigned parent = (e->min_heap_idx - 1) / 2; 106 /* we replace e with the last element in the heap. We might need to 107 shift it upward if it is less than its parent, or downward if it is 108 greater than one or both its children. Since the children are known 109 to be less than the parent, it can't need to shift both up and 110 down. */ 111 //If e Not root element, current e The parent node value of is greater than last，Up adjustment required 112 if (e->min_heap_idx > 0 && min_heap_elem_greater(s->p[parent], last)) 113 min_heap_shift_up_(s, e->min_heap_idx, last); 114 else 115 //If e Is the root element or e Parent node element value of is not greater than last，Element down, e->min_heap_idx Is the head node index, last: Bottom most right element 116 //，Used to fill the empty position after insertion 117 min_heap_shift_down_(s, e->min_heap_idx, last); 118 //take e Element out of pile 119 e->min_heap_idx = -1; 120 return 0; 121 } 122 return -1; 123 } 124 125 //Adjust allocated memory 126 int min_heap_reserve(min_heap_t* s, unsigned n) 127 { 128 //If the capacity of an element is less than the number of elements, the memory needs to be reallocated 129 if(s->a < n) 130 { 131 struct event** p; 132 //a If the default value is 0, it will be 8. If there is a previous value (not the first adjustment), it will be doubled 133 unsigned a = s->a ? s->a * 2 : 8; 134 //If a It's not enough. Let's go straight a Be equal to n，Same number and capacity of elements 135 if(a < n) 136 a = n; 137 //Readjust memory, allocate continuously 138 if(!(p = (struct event**)realloc(s->p, a * sizeof *p))) 139 return -1; 140 //First address 141 s->p = p; 142 //capacity 143 s->a = a; 144 } 145 return 0; 146 } 147 148 //Adjust up after inserting element 149 void min_heap_shift_up_(min_heap_t* s, unsigned hole_index, struct event* e) 150 { 151 //Index of the parent node 152 unsigned parent = (hole_index - 1) / 2; 153 //If hole_index Not equal to 0 and the parent node element is greater than the given element, continue to compare until it reaches hole_index Is the root element, 154 //Or the parent element is greater than e，Find where to insert 155 while(hole_index && min_heap_elem_greater(s->p[parent], e)) 156 { 157 //The element value of the parent node is large. Put the parent node in the current hole_index Location on 158 (s->p[hole_index] = s->p[parent])->min_heap_idx = hole_index; 159 160 //hole_index Index assigned as parent 161 hole_index = parent; 162 163 //Find the current hole_index Parent node index of 164 parent = (hole_index - 1) / 2; 165 } 166 167 //Jump out of the loop and find the location to insert. The index of the location is now hole_index 168 (s->p[hole_index] = e)->min_heap_idx = hole_index; 169 } 170 171 //Element down (delete element) 172 void min_heap_shift_down_(min_heap_t* s, unsigned hole_index, struct event* e) 173 { 174 //Right child index 175 unsigned min_child = 2 * (hole_index + 1); 176 //There is a right child. If there is no right child tree, adjust it directly downward. Because there is a left child tree at most, and the value must be no less than the parent node, you can adjust it directly downward 177 while(min_child <= s->n) 178 { 179 //Select the index of the child with the lowest value of left and right children, and add it according to the priority()Better view 180 min_child -= ((min_child == s->n) || min_heap_elem_greater(s->p[min_child], s->p[min_child - 1])); 181 //If e The element is not greater than the smallest child element, so there is no need to continue, hole_index It's his position 182 if(!(min_heap_elem_greater(e, s->p[min_child]))) 183 break; 184 //Put the little child element in hole_index Position 185 (s->p[hole_index] = s->p[min_child])->min_heap_idx = hole_index; 186 //hole_index Save the current child index 187 hole_index = min_child; 188 //The current small child's position is vacated. Continue the next cycle and compare the left and right children of the current small child 189 min_child = 2 * (hole_index + 1); 190 } 191 //take e Elements in hole_index,Then adjust up. commonly e Element is the lowest right node. Do not exclude the possibility of being more than the current position on the parent node 192 //So it needs to be adjusted up 193 min_heap_shift_up_(s, hole_index, e); 194 } 195 196 #endif /* _MIN_HEAP_H_ */