40 static inline void min_heap_ctor(
min_heap_t* s);
41 static inline void min_heap_dtor(
min_heap_t* s);
42 static inline void min_heap_elem_init(
struct event* e);
43 static inline int min_heap_elem_greater(
struct event *a,
struct event *b);
44 static inline int min_heap_empty(
min_heap_t* s);
45 static inline unsigned min_heap_size(
min_heap_t* s);
47 static inline int min_heap_reserve(
min_heap_t* s,
unsigned n);
51 static inline void min_heap_shift_up_(
min_heap_t* s,
unsigned hole_index,
struct event* e);
52 static inline void min_heap_shift_down_(
min_heap_t* s,
unsigned hole_index,
struct event* e);
54 int min_heap_elem_greater(
struct event *a,
struct event *b)
56 return evutil_timercmp(&a->ev_timeout, &b->ev_timeout, >);
59 void min_heap_ctor(
min_heap_t* s) { s->p = 0; s->n = 0; s->a = 0; }
60 void min_heap_dtor(
min_heap_t* s) { free(s->p); }
61 void min_heap_elem_init(
struct event* e) { e->min_heap_idx = -1; }
62 int min_heap_empty(
min_heap_t* s) {
return 0u == s->n; }
63 unsigned min_heap_size(
min_heap_t* s) {
return s->n; }
68 if(min_heap_reserve(s, s->n + 1))
70 min_heap_shift_up_(s, s->n++, e);
78 struct event* e = *s->p;
79 min_heap_shift_down_(s, 0u, s->p[--s->n]);
88 if(((
unsigned int)-1) != e->min_heap_idx)
90 struct event *last = s->p[--s->n];
91 unsigned parent = (e->min_heap_idx - 1) / 2;
97 if (e->min_heap_idx > 0 && min_heap_elem_greater(s->p[parent], last))
98 min_heap_shift_up_(s, e->min_heap_idx, last);
100 min_heap_shift_down_(s, e->min_heap_idx, last);
101 e->min_heap_idx = -1;
112 unsigned a = s->a ? s->a * 2 : 8;
115 if(!(p = (
struct event**)realloc(s->p, a *
sizeof *p)))
123 void min_heap_shift_up_(
min_heap_t* s,
unsigned hole_index,
struct event* e)
125 unsigned parent = (hole_index - 1) / 2;
126 while(hole_index && min_heap_elem_greater(s->p[parent], e))
128 (s->p[hole_index] = s->p[parent])->min_heap_idx = hole_index;
130 parent = (hole_index - 1) / 2;
132 (s->p[hole_index] = e)->min_heap_idx = hole_index;
135 void min_heap_shift_down_(
min_heap_t* s,
unsigned hole_index,
struct event* e)
137 unsigned min_child = 2 * (hole_index + 1);
138 while(min_child <= s->n)
140 min_child -= min_child == s->n || min_heap_elem_greater(s->p[min_child], s->p[min_child - 1]);
141 if(!(min_heap_elem_greater(e, s->p[min_child])))
143 (s->p[hole_index] = s->p[min_child])->min_heap_idx = hole_index;
144 hole_index = min_child;
145 min_child = 2 * (hole_index + 1);
147 min_heap_shift_up_(s, hole_index, e);