2024-04-27 21:51:18 -04:00
|
|
|
Intrusive, single file, C89+ imperative AA tree that works on freestanding
|
2024-04-26 07:54:38 -04:00
|
|
|
systems.
|
2024-04-25 18:51:30 -04:00
|
|
|
|
|
|
|
The implementation is about 300 lines.
|
|
|
|
|
|
|
|
BSD 2-Clause license.
|
2024-04-26 07:54:38 -04:00
|
|
|
|
|
|
|
------------------
|
|
|
|
What are AA Trees?
|
|
|
|
------------------
|
|
|
|
|
|
|
|
`AA Trees <https://user.it.uu.se/~arneande/ps/simp.pdf>`_ are a type of
|
|
|
|
self-balancing binary tree. Unlike AVL trees or red-black trees, which
|
|
|
|
store a constant amount of information per node, AA trees store the
|
|
|
|
"level" of a node (which is approximately the height of the node from
|
|
|
|
the bottom of the tree). This makes rebalancing operations much simpler:
|
|
|
|
most of the code in this library is for handling standard binary tree
|
|
|
|
operations.
|
|
|
|
|
|
|
|
Theoretically, this limits the size of the binary tree to
|
|
|
|
``2**(2**16-1)`` nodes, which is no problem in practice.
|
|
|
|
|
|
|
|
This implementation is "intrusive", meaning that the node data structure
|
|
|
|
does not contain the key or value stored in it. You need to define your
|
|
|
|
own structure and search function like ::
|
|
|
|
|
|
|
|
struct node {
|
|
|
|
char *key;
|
|
|
|
void *val;
|
|
|
|
struct aatree node;
|
|
|
|
};
|
|
|
|
|
|
|
|
int node_cmp(struct aatree *a1, struct aatree *a2)
|
|
|
|
{
|
|
|
|
struct node *n1 = (void *)((char *)a1 - offsetof(struct node, node));
|
|
|
|
struct node *n2 = (void *)((char *)a2 - offsetof(struct node, node));
|
|
|
|
|
|
|
|
return strcmp(n1->key, n2->key);
|
|
|
|
}
|
|
|
|
|
2024-04-27 21:51:18 -04:00
|
|
|
This is standard, portable C89. Intrusive code has the advantage of
|
|
|
|
requiring only one allocation instead of two, allowing for easier
|
|
|
|
memory management (i.e. arena memory allocation).
|
2024-04-26 07:54:38 -04:00
|
|
|
|
|
|
|
-----------------
|
|
|
|
Using the Library
|
|
|
|
-----------------
|
|
|
|
|
|
|
|
In *one* C file, do the following ::
|
|
|
|
|
|
|
|
/* Optional declarations: */
|
|
|
|
#define AATREE_PREFIX /* prefix of each function: put "declspec" or
|
|
|
|
"static" here */
|
|
|
|
#define AATREE_ASSERT /* Define this if you want the code to have
|
|
|
|
asserts. Do not define if you do not want
|
|
|
|
standard library asserts. */
|
|
|
|
|
|
|
|
/* Mandatory declarations */
|
|
|
|
#define AATREE_IMPL
|
|
|
|
#include "aatree.h"
|
|
|
|
|
|
|
|
This will include the implementation of the functions into the C file.
|
|
|
|
If your project consists of more than one C file, then all you need to
|
|
|
|
do is ``#include aatree.h``. The linker will take care of everything else.
|
|
|
|
|
|
|
|
The library also includes it own test code for convienence. Define
|
|
|
|
``AATREE_TEST`` to turn the header into a self-contained C file with a
|
|
|
|
``main()`` function. See ``Makefile`` for an example of compiling the
|
|
|
|
test.
|