70 lines
2.3 KiB
ReStructuredText
70 lines
2.3 KiB
ReStructuredText
Intrusive, single file, C89+ imperative AA tree that works on freestanding
|
|
systems.
|
|
|
|
The implementation is about 300 lines.
|
|
|
|
BSD 2-Clause license.
|
|
|
|
------------------
|
|
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);
|
|
}
|
|
|
|
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).
|
|
|
|
-----------------
|
|
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. This library uses assert() from the
|
|
standard library. */
|
|
|
|
/* 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
|
|
tests.
|