Data Structures#
A general, yet highly performant data structures library. It is highly
run-time configurable: the memory used by the data structure handle, the
elements the data structure will manage, and structure metadata can each be
independently provided by the calling application or malloc()ed by the
library. (The one exception is dynmatrix, whose rows are always
heap-allocated; only its handle can be caller-provided.)
Warning
Data structures in this module are not thread-safe. No internal
synchronization is performed. Callers are responsible for all external
locking. See Multithread for suitable primitives
(e.g., mutex, rdwrlock).
Available Structures#
Module |
Notes |
Link |
Time Complexity (typical ops) |
|---|---|---|---|
Ringbuffer |
Fixed-capacity circular buffer. Overwrite mode (oldest element
evicted) or FIFO mode (add fails when full) selectable at init via
|
Add/remove: O(1) |
|
Linked list |
Doubly linked. Supports optional sorted-insertion mode
( |
Append/prepend: O(1); query: O(n); sort: O(n log n) |
|
FIFO |
A header-only wrapper around an |
Push/pop: O(1) |
|
Multi-FIFO |
A FIFO of large elements, each consumed in smaller pieces through up to 8 child FIFOs that point into it. Data is never copied to the children. |
Push/pop: see API reference |
|
Raw FIFO |
Only handles {1, 2, 4}-byte elements. Lock-free for exactly one producer and one consumer, so it can pass data between an ISR and the main loop. |
Push/pop: O(1) |
|
Dynamic array |
Analogous to |
Append: amortized O(1); index: O(1); search: O(n) |
|
Binary Search Tree |
Uses approach in Introduction To Algorithms. |
Insert/remove/query: O(h), worst case O(n) on unbalanced tree |
|
Red-Black Tree |
Self-balancing BST: a |
Insert/remove/query: O(log n) guaranteed |
|
Order Statistics Tree |
Built on Red-Black Tree. Supports order-statistic queries (rank, select). Uses approach in Introduction To Algorithms. |
All BST ops + rank/select: O(log n) |
|
Interval Tree |
Built on Red-Black Tree. Finds a stored interval that overlaps a given one. Uses approach in Introduction To Algorithms. |
Insert/query: O(log n) |
|
Hashmap |
Fixed-size buckets, each a dynamic array. Keys are
|
Insert/query: O(bucket size), times |
|
Binary heap |
Built using dynamic array. A max heap, or a min heap with
|
Insert: O(log n); peek-min/max: O(1); extract-min/max: O(log n) |
|
Matrix |
Static matrix; dimensions cannot change after initialization.
|
Element access: O(1) |
|
Dynamic Matrix |
Dimensions can change after initialization. Can be used to represent dynamic graphs. Works best on densely connected graphs. |
Element access: O(1); resize: O(m*n) |
|
Adjacency Matrix |
Dimensions (# vertices) cannot change after initialization. Efficient graph representation; works best on densely connected graphs. Weighted graphs must be directed; model a weighted undirected graph by adding each edge in both directions. |
Edge query: O(1) |
Common API#
Conventions shared by every structure (configuration, callbacks, element ownership, iterators, flags) are described in Data Structures.
All data structures (loosely) conform to the following API. Not all
structures implement every function — e.g., llist does not
implement llist_data_get() because linked lists do not have an index
concept.
Function |
Purpose |
|---|---|
|
Initialize the data structure. Usage of the handle prior to calling
this function is undefined behavior. Returns |
|
Given the max number of elements and the element size, returns the
number of bytes the caller must reserve if it wants to supply
element storage and pass |
|
Given the max number of elements, returns the number of bytes the
caller must reserve if it wants to supply metadata storage and pass
|
|
Destroy the data structure and release any internally allocated
memory. Usage of the handle after calling this function is
undefined until |
|
Add a new element. Returns |
|
Remove an element: by value ( |
|
Remove all elements without destroying the structure. The handle
remains valid and |
|
Print all elements using the |
|
Returns |
|
Returns |
|
Returns the current number of elements. |
|
Returns the maximum number of elements the structure can currently
hold. Only defined for structures with a fixed capacity at any
point in time (e.g., |
|
Sort the structure in place using the comparator provided at init. |
|
Remove the elements matching a caller-supplied predicate.
|
|
Copy the structure; |
|
Iterate over all elements, computing a cumulative result via a caller-supplied accumulator function (analogous to a fold/reduce). |
|
Apply a caller-supplied function to every element in place. |
|
Find an element. Depending on the structure this returns the element
( |
|
Return a pointer to an element by index (by key for
|
Memory#
Each structure can take its handle, element storage and metadata from the caller instead of the heap. See Memory Model for the flags, sizing rules, zeroing and alignment, and Quickstart Example for an example.
Error Codes#
On failure, functions return NULL (pointer-returning) or ERROR
(status_t-returning) and, on most paths, set errno:
|
Meaning |
|---|---|
|
Invalid argument. Set by every function’s precondition checks (see
Function preconditions) and by a few explicit checks in
|
|
An allocation failed ( |
|
The structure is full ( |
|
|
|
The element, key or edge isn’t present ( |
|
|
Note
Not every error path in every module sets errno. If precise error
discrimination is needed, rely on the ERROR return value for
control flow and treat errno as advisory. This inconsistency is a
known limitation and is tracked for improvement.
Quickstart Example#
The following creates a llist that uses no heap: the handle,
element storage and node storage all come from the caller. The sizing
functions are not constant expressions, so the static buffers are sized
generously and checked before use.
#include "rcsw/ds/llist.h"
#define N_ELTS 16
static dptr_t elements[512 / sizeof(dptr_t)];
static dptr_t nodes[1024 / sizeof(dptr_t)];
static struct llist list;
status_t list_setup(void) {
if (sizeof(elements) < llist_element_space(N_ELTS, sizeof(int)) ||
sizeof(nodes) < llist_meta_space(N_ELTS)) {
return ERROR;
}
struct llist_config config = {
.cmpe = NULL,
.printe = NULL,
.elements = elements,
.meta = nodes,
.elt_size = sizeof(int),
.max_elts = N_ELTS,
.flags = RCSW_NOALLOC_ALL,
};
if (NULL == llist_init(&list, &config)) {
return ERROR; /* errno says why */
}
int val = 42;
llist_append(&list, &val); /* copies val into the list */
/* ... use the list ... */
llist_destroy(&list); /* frees nothing: all memory is the caller's */
return OK;
}
See the test suite for extensive usage examples covering all data structures.