prio_heap.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Simple insertion-only static-sized priority heap containing
  3. * pointers, based on CLR, chapter 7
  4. */
  5. #include <linux/slab.h>
  6. #include <linux/prio_heap.h>
  7. int heap_init(struct ptr_heap *heap, size_t size, gfp_t gfp_mask,
  8. int (*gt)(void *, void *))
  9. {
  10. heap->ptrs = kmalloc(size, gfp_mask);
  11. if (!heap->ptrs)
  12. return -ENOMEM;
  13. heap->size = 0;
  14. heap->max = size / sizeof(void *);
  15. heap->gt = gt;
  16. return 0;
  17. }
  18. void heap_free(struct ptr_heap *heap)
  19. {
  20. kfree(heap->ptrs);
  21. }
  22. void *heap_insert(struct ptr_heap *heap, void *p)
  23. {
  24. void *res;
  25. void **ptrs = heap->ptrs;
  26. int pos;
  27. if (heap->size < heap->max) {
  28. /* Heap insertion */
  29. pos = heap->size++;
  30. while (pos > 0 && heap->gt(p, ptrs[(pos-1)/2])) {
  31. ptrs[pos] = ptrs[(pos-1)/2];
  32. pos = (pos-1)/2;
  33. }
  34. ptrs[pos] = p;
  35. return NULL;
  36. }
  37. /* The heap is full, so something will have to be dropped */
  38. /* If the new pointer is greater than the current max, drop it */
  39. if (heap->gt(p, ptrs[0]))
  40. return p;
  41. /* Replace the current max and heapify */
  42. res = ptrs[0];
  43. ptrs[0] = p;
  44. pos = 0;
  45. while (1) {
  46. int left = 2 * pos + 1;
  47. int right = 2 * pos + 2;
  48. int largest = pos;
  49. if (left < heap->size && heap->gt(ptrs[left], p))
  50. largest = left;
  51. if (right < heap->size && heap->gt(ptrs[right], ptrs[largest]))
  52. largest = right;
  53. if (largest == pos)
  54. break;
  55. /* Push p down the heap one level and bump one up */
  56. ptrs[pos] = ptrs[largest];
  57. ptrs[largest] = p;
  58. pos = largest;
  59. }
  60. return res;
  61. }