// timeout_heap.h #ifndef TIMEOUT_HEAP_H #define TIMEOUT_HEAP_H #include // For uint64_t #include // For size_t typedef uint64_t TimeoutTime; // e.g., milliseconds since epoch or from now typedef struct { TimeoutTime expiration; // Sort key (smaller = earlier) void *data; // User data (e.g., callback or ID) } TimeoutEntry; // Removed deleted flag typedef struct TimeoutHeap TimeoutHeap; struct TimeoutHeap { TimeoutEntry *heap; // Dynamic array size_t size; // Current number of elements size_t capacity; // Allocated size // Removed freed_count and free_callback }; /** * Create a new timeout heap with initial capacity. * @param initial_capacity Starting capacity (will grow as needed). * @return Pointer to the heap, or NULL on failure. */ TimeoutHeap *timeout_heap_create(size_t initial_capacity); /** * Destroy the timeout heap and free resources (but not the data pointers). * @param h The heap to destroy. */ void timeout_heap_destroy(TimeoutHeap *h); /** * Insert a new timeout into the heap. * @param h The heap. * @param expiration The expiration time. * @param data User data associated with the timeout. * @return 0 on success, -1 on allocation failure. */ int timeout_heap_push(TimeoutHeap *h, TimeoutTime expiration, void *data); /** * Peek at the earliest timeout without removing it. * @param h The heap. * @param out Where to store the entry. * @return 0 on success, -1 if empty. */ int timeout_heap_peek(TimeoutHeap *h, TimeoutEntry *out); /** * Pop the earliest timeout from the heap. * @param h The heap. * @param out Where to store the entry. * @return 0 on success, -1 if empty. */ int timeout_heap_pop(TimeoutHeap *h, TimeoutEntry *out); /** * Remove a timeout by matching expiration and data (immediate removal). * Scans the heap linearly, O(n) time. * Assumes combinations are unique; removes the first match. * Does not free the data — caller should do it if success. * @param h The heap. * @param expiration The expiration time to match. * @param data The data to match. * @return 0 if found and removed, -1 if not found. */ int timeout_heap_cancel(TimeoutHeap *h, TimeoutTime expiration, void *data); #endif // TIMEOUT_HEAP_H