heap.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #ifndef __sti__heap_h__
  2. #define __sti__heap_h__
  3. // Public Domain.
  4. #include <stdint.h>
  5. typedef int (*comp_fn)(const void* a, const void* b, void* user);
  6. // children at indices 2i + 1 and 2i + 2
  7. // parent at index floor((i − 1) ∕ 2).
  8. typedef struct heap_ {
  9. char* data;
  10. size_t len;
  11. size_t alloc;
  12. comp_fn cmp;
  13. void* user;
  14. } heap_;
  15. // declare a heap of type t
  16. #define HEAP(t) \
  17. union { \
  18. t** type; \
  19. heap_ heap; \
  20. }
  21. // initialize internals and set the cmp function
  22. #define HEAP_init(h, c, u) \
  23. do { \
  24. (h)->heap.cmp = (c); \
  25. (h)->heap.len = 0; \
  26. (h)->heap.alloc = 0; \
  27. (h)->heap.data = 0; \
  28. (h)->heap.user = (u); \
  29. } while(0)
  30. // insert a value into the heap
  31. #define HEAP_insert(h, e) heap_insert_(&(h)->heap, (void*)(e), sizeof(*((h)->type)))
  32. void heap_insert_(heap_* h, char* elem, size_t elem_sz);
  33. // get the value of the most extreme value without removing it
  34. #define HEAP_peek(h, e) heap_peek_(&(h)->heap, (void*)(e), sizeof(*((h)->type)))
  35. int heap_peek_(heap_* h, char* out, size_t elem_sz);
  36. // remove the top, most extreme value from the heap
  37. #define HEAP_pop(h, e) heap_pop_(&(h)->heap, (void*)(e), sizeof(*((h)->type)))
  38. int heap_pop_(heap_* h, char* out, size_t elem_sz);
  39. // pop the top element and insert a new one at the same time
  40. // faster than separate operations.
  41. #define HEAP_insert_pop(h, i, o) heap_insert_pop_(&(h)->heap, (void*)(i), (o), sizeof(*((h)->type)))
  42. void heap_insert_pop_(heap_* h, char* in, char* out, size_t elem_sz);
  43. // free all internal memory. does not free h itself
  44. #define HEAP_free(h) heap_free_(&(h)->heap);
  45. void heap_free_(heap_* h);
  46. #define HEAP_delete(h, e) heap_delete_(&(h)->heap, (void*)(e), sizeof(*((h)->type)))
  47. void heap_delete_(heap_* h, char* elem, size_t elem_sz);
  48. // returns -1 if not found, the item index otherwise
  49. #define HEAP_find(h, e) heap_find_(&(h)->heap, (void*)(e), sizeof(*((h)->type)))
  50. ssize_t heap_find_(heap_* h, char* elem, size_t elem_sz);
  51. /*
  52. int heap_contains_(heap_* h, char* elem, size_t elem_sz);
  53. size_t heap_count_(heap_* h, char* elem, size_t elem_sz);
  54. */
  55. #endif //__sti__heap_h__