heap.h 2.1 KB

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