{"id":20728018,"url":"https://github.com/jserv/rbtree","last_synced_at":"2025-09-27T15:30:54.570Z","repository":{"id":262094744,"uuid":"886203858","full_name":"jserv/rbtree","owner":"jserv","description":"A red-black tree implementation","archived":false,"fork":false,"pushed_at":"2024-11-11T01:36:15.000Z","size":107,"stargazers_count":28,"open_issues_count":3,"forks_count":3,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-16T10:42:42.469Z","etag":null,"topics":["binary-search-tree","data-structures","red-black-tree"],"latest_commit_sha":null,"homepage":"","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jserv.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-11-10T13:29:20.000Z","updated_at":"2025-01-07T14:33:07.000Z","dependencies_parsed_at":"2024-11-10T14:38:37.821Z","dependency_job_id":null,"html_url":"https://github.com/jserv/rbtree","commit_stats":null,"previous_names":["jserv/rbtree"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jserv%2Frbtree","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jserv%2Frbtree/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jserv%2Frbtree/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jserv%2Frbtree/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jserv","download_url":"https://codeload.github.com/jserv/rbtree/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234444593,"owners_count":18833657,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["binary-search-tree","data-structures","red-black-tree"],"created_at":"2024-11-17T04:35:20.818Z","updated_at":"2025-09-27T15:30:54.558Z","avatar_url":"https://github.com/jserv.png","language":"C","funding_links":[],"categories":[],"sub_categories":[],"readme":"# rbtree\n\nThis package provides a memory-optimized red-black tree implementation with\nsearch and deletion operations guaranteed to run in $O(\\log_2(N))$ time for\na tree containing $N$ elements. Features include intrusive node design,\npointer alignment optimization, optional caching for O(1) min/max access,\nefficient batch operations for bulk insertions, and configurable build-time\noptions for performance tuning.\n\n## Build-time Configuration\n\nThe implementation supports several build-time options:\n- `_RB_ENABLE_LEFTMOST_CACHE` (default: 1): Enable O(1) minimum node access\n- `_RB_ENABLE_RIGHTMOST_CACHE` (default: 0): Enable O(1) maximum node access\n- `_RB_ENABLE_SAFETY_CHECKS` (default: 1): Enable bounds checking (\u003c5% overhead)\n- `_RB_ENABLE_BATCH_OPS` (default: 1): Enable batch operations for efficient bulk insertions\n\n## Data Structure\n\nThe `rb_t` tracking structure can be initialized anywhere in user-accessible\nmemory. It should contain only zero bits before first use, and no specific\ninitialization API is needed.\n\nUnlike a linked list, where the position of elements is explicit, the ordering\nof nodes in an `rb_t` must be defined by a user-provided predicate function.\nA function of type `rb_cmp_t` should be assigned to the `cmp_func` field of the\n`rb_t` structure before any tree operations are performed. This function must\nreturn `true` if the first node argument is \"less than\" the second, according to\nthe desired ordering. Note that \"equal\" values are not allowed; nodes within the\ntree must have a unique and fixed order for the algorithm to function correctly.\n\nNodes within an `rb_t` are represented as an `rb_node_t` structure, which\nresides  in user-managed memory, typically embedded within the data structure\ntracked by the tree. However, unlike linked list structures, the data within an\n`rb_node_t` is entirely opaque, and users cannot manually traverse the tree's\nbinary topology as they can with lists.\n\nNodes can be inserted into the tree with `rb_insert` and removed with\n`rb_remove`. The \"first\" and \"last\" nodes in the tree, as determined by the\ncomparison function, can be accessed using `rb_get_min` and `rb_get_max`,\nrespectively. Additionally, the `rb_contains` function checks if a specific\nnode pointer exists within the tree. All of these operations have a maximum time\ncomplexity of $O(\\log(N))$ based on the size of the tree.\n\n### Operations\n\nTree iteration is provided through the `RB_FOREACH` iterator, which allows\nnatural iteration with nested code blocks instead of callbacks. The iterator\nis non-recursive and uses optimized memory allocation - either dynamic stack\nallocation or a fixed buffer to avoid runtime overhead. Recent improvements\ninclude reduced memory usage and enhanced bounds checking. An\n`RB_FOREACH_CONTAINER` variant iterates using container pointers rather than\nraw node pointers.\n\n### Batch Operations\n\nWhen `_RB_ENABLE_BATCH_OPS` is enabled, the implementation provides batch\noperations for efficient bulk insertions. This feature offers significant\nperformance improvements (up to 8x speedup) when loading large datasets into\nempty trees. The batch API includes:\n\n- `rb_batch_init`: Initialize a batch context with optional initial capacity\n- `rb_batch_add`: Add nodes to the batch buffer\n- `rb_batch_commit`: Sort and insert all batched nodes efficiently\n- `rb_batch_destroy`: Clean up batch resources\n\nFor empty trees, batch operations construct a perfectly balanced tree in O(n)\ntime after O(n log n) sorting. For non-empty trees, the implementation\ngracefully falls back to regular insertions to maintain correctness.\n\n### Implementation Details\n\nThis package uses a conventional red-black tree algorithm. Low-level algorithmic\ndetails are omitted here since they follow established conventions. Instead,\nthis document focuses on aspects specific to this package's implementation.\n\nThe core invariant of the red-black tree ensures that the path from the root to\nany leaf is no more than twice as long as the path to any other leaf. This\nbalance is maintained by associating a \"color\" bit with each node, either red or\nblack, and enforcing a rule that no red node can have a red child (i.e., the\nnumber of black nodes along any path from the root must be equal, and the number\nof red nodes must not exceed this count). This property is maintained using\na series of tree rotations to restore balance after modifications.\n\nThese rotations are conceptually based on a primitive operation that \"swaps\" the\npositions of two nodes in the tree. In many implementations, this is done by\nsimply exchanging the internal data pointers of the nodes. However, this package\nuses an intrusive `rb_node_t` structure, where the node metadata is embedded\ndirectly within the user-defined data structure. This design improves cache\nlocality and eliminates additional memory allocations, but it also requires more\ncomplex logic to handle edge cases, such as when one of the nodes is the root or\nwhen the nodes have a parent-child relationship.\n\nThe `rb_node_t` structure contains only two pointers for left and right\nchildren. Node colors are stored in the least significant bit of the left\npointer, leveraging pointer alignment guarantees. Unlike implementations with\nparent pointers, this package uses a traversal stack for upward navigation\nduring rebalancing. Recent optimizations include magic number extraction,\nimproved bounds checking, and pointer alignment verification to ensure the\ncolor bit storage remains valid. Memory usage has been further reduced through\niterator buffer optimization.\n\n```\n+-------------+     node 2 (black, color in left ptr LSB)\n| rb_t        |    +------------------+\n| * root ----------|    rb_node_t     |\n| * cmp_func  |    | * left¹| * right |  ¹ LSB stores color bit\n+-------------+    +----/---------\\---+\n                       /           \\\n       node 1 (black) /             \\ node 4 (red)\n      +------------------+       +------------------+\n      |    rb_node_t     |       |    rb_node_t     |\n      | * left¹| * right |       | * left¹| * right |\n      +----/---------\\---+       +----/---------\\---+\n          /           \\              /           \\\n       NULL           NULL          /             \\\n                        node 3 (black)        node 5 (black)\n                       +------------------+  +------------------+\n                       |    rb_node_t     |  |    rb_node_t     |\n                       | * left¹| * right |  | * left¹| * right |\n                       +----/---------\\---+  +----/---------\\---+\n                           /           \\         /           \\\n                        NULL           NULL    NULL           \\\n                                                     node 6 (red)\n                                                   +------------------+\n                                                   |    rb_node_t     |\n                                                   | * left¹| * right |\n                                                   +----/---------\\---+\n                                                       /           \\\n                                                    NULL           NULL\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjserv%2Frbtree","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjserv%2Frbtree","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjserv%2Frbtree/lists"}