X-Git-Url: http://git.liburcu.org/?a=blobdiff_plain;f=lib%2Fprio_heap%2Fprio_heap.c;h=0c9bb607510829a0ee62bd3a919d41e4b4b7440e;hb=c9891db2b888da5f93387125dde69174e9f0e916;hp=e660b0cdc9125ccbc9e99bf83267a9e3540b37b1;hpb=162769efd7bca728713c4bf8e609fc408d58f512;p=lttng-modules.git diff --git a/lib/prio_heap/prio_heap.c b/lib/prio_heap/prio_heap.c index e660b0cd..0c9bb607 100644 --- a/lib/prio_heap/prio_heap.c +++ b/lib/prio_heap/prio_heap.c @@ -20,9 +20,23 @@ #include #include -/* - * TODO implement heap_init, heap_free, heap_insert. - */ +int heap_init(struct ptr_heap *heap, size_t size, + gfp_t gfpmask, int gt(void *a, void *b)) +{ + WARN_ON_ONCE(size == 0); + heap->ptrs = kmalloc(size * sizeof(void *), gfpmask); + if (!heap->ptrs) + return -ENOMEM; + heap->size = 0; + heap->max = size; + heap->gt = gt; + return 0; +} + +void heap_free(struct ptr_heap *heap) +{ + kfree(heap->ptrs); +} static void heapify(struct ptr_heap *heap, int pos) { @@ -64,6 +78,34 @@ void *heap_replace_max(struct ptr_heap *heap, void *p) return res; } +void *heap_insert(struct ptr_heap *heap, void *p) +{ + void **ptrs = heap->ptrs; + void *tmp = NULL; + + if (heap->size < heap->max) { + /* Add the element to the end */ + heap->ptrs[heap->size++] = p; + /* rebalance */ + heapify(heap, 0); + return NULL; + } + + /* + * Full. We need to replace the largest (if we are + * smaller or equal to this element). + */ + if (heap->gt(ptrs[0], p)) { + tmp = ptrs[0]; + ptrs[0] = p; + /* rebalance */ + heapify(heap, 0); + } else { + tmp = p; + } + return tmp; +} + void *heap_remove(struct ptr_heap *heap) { void **ptrs = heap->ptrs;