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 RCSW_DS_RBUFFER_AS_FIFO.

rbuffer

Add/remove: O(1)

Linked list

Doubly linked. Supports optional sorted-insertion mode (RCSW_DS_SORTED). Uncapped length supported unless RCSW_NOALLOC_META or RCSW_NOALLOC_DATA is set, in which case max_elts must be finite.

llist

Append/prepend: O(1); query: O(n); sort: O(n log n)

FIFO

A header-only wrapper around an rbuffer in FIFO mode: strict FIFO semantics, and an add fails with ENOSPC when full.

fifo

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.

multififo

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.

rawfifo

Push/pop: O(1)

Dynamic array

Analogous to std::vector; grows/shrinks as needed using the approach from Introduction To Algorithms.

darray

Append: amortized O(1); index: O(1); search: O(n)

Binary Search Tree

Uses approach in Introduction To Algorithms.

bstree

Insert/remove/query: O(h), worst case O(n) on unbalanced tree

Red-Black Tree

Self-balancing BST: a bstree created with RCSW_DS_BSTREE_RB. Uses approach in Introduction To Algorithms.

bstree

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.

ostree_init()

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.

inttree_init()

Insert/query: O(log n)

Hashmap

Fixed-size buckets, each a dynamic array. Keys are hashmap_config.key_len bytes (0 means RCSW_HASHMAP_KEYSIZE). When a bucket is full, an add fails unless RCSW_DS_HASHMAP_LINPROB is set, which puts the node in the next bucket with space; lookups then also search up to hashmap.max_probe buckets past the home bucket. The hash function is supplied in hashmap_config.hash; rcsw/utils/hash.h provides several.

hashmap

Insert/query: O(bucket size), times max_probe + 1 with linear probing; hashmap_gather() reports how far from random the hash function is.

Binary heap

Built using dynamic array. A max heap, or a min heap with RCSW_DS_BINHEAP_MIN.

binheap

Insert: O(log n); peek-min/max: O(1); extract-min/max: O(log n)

Matrix

Static matrix; dimensions cannot change after initialization. matrix_transpose() handles square matrices only.

matrix

Element access: O(1)

Dynamic Matrix

Dimensions can change after initialization. Can be used to represent dynamic graphs. Works best on densely connected graphs.

dynmatrix

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.

adjmatrix

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

XX_init()

Initialize the data structure. Usage of the handle prior to calling this function is undefined behavior. Returns NULL on failure; errno is set (see Error Codes).

XX_element_space()

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 RCSW_NOALLOC_DATA.

XX_meta_space()

Given the max number of elements, returns the number of bytes the caller must reserve if it wants to supply metadata storage and pass RCSW_NOALLOC_META. Only applicable to structures with per-element metadata (e.g., llist), not contiguous-array structures (e.g., darray).

XX_destroy()

Destroy the data structure and release any internally allocated memory. Usage of the handle after calling this function is undefined until XX_init() is called again.

XX_add() / XX_insert()

Add a new element. Returns ERROR with errno = ENOSPC if the structure is full. See Error Codes.

XX_remove()

Remove an element: by value (llist, hashmap, bstree), by index (darray) or from the front (fifo, rbuffer). Removing a value or key that isn’t present returns ERROR with errno = ENOENT; an out-of-range index fails the precondition check (EINVAL).

XX_clear()

Remove all elements without destroying the structure. The handle remains valid and XX_init() does not need to be called again.

XX_print()

Print all elements using the printe callback provided during initialization. Requires that callback.

XX_isfull()

Returns true if no further elements can be added without first removing one.

XX_isempty()

Returns true if the structure contains no elements.

XX_size()

Returns the current number of elements.

XX_capacity()

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., rbuffer). Distinct from the maximum possible capacity set during initialization.

XX_sort()

Sort the structure in place using the comparator provided at init.

XX_filter() / XX_remove_if()

Remove the elements matching a caller-supplied predicate. XX_filter() moves them into a new instance; XX_remove_if() deletes them in place.

XX_copy() / XX_copy_if()

Copy the structure; XX_copy_if() copies only the elements matching a caller-supplied predicate.

XX_inject()

Iterate over all elements, computing a cumulative result via a caller-supplied accumulator function (analogous to a fold/reduce).

XX_map()

Apply a caller-supplied function to every element in place.

XX_*_query()

Find an element. Depending on the structure this returns the element (llist_data_query()), its node (llist_node_query()) or its index (darray_idx_query()). See per-structure documentation.

XX_data_get()

Return a pointer to an element by index (by key for hashmap_data_get()). Out-of-range indices are the caller’s error, and the response varies: rbuffer_data_get() returns NULL, while darray_data_get() reports a FATAL event and fails an assert().

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:

errno

Meaning

EINVAL

Invalid argument. Set by every function’s precondition checks (see Function preconditions) and by a few explicit checks in darray, llist and multififo.

ENOMEM

An allocation failed (darray, llist, hashmap, binheap, multififo).

ENOSPC

The structure is full (darray, llist, hashmap, binheap, bstree, and rbuffer in FIFO mode).

EEXIST

The key is already present (hashmap, bstree).

ENOENT

The element, key or edge isn’t present (llist_remove(), llist_splice(), hashmap_remove(), bstree_remove(), adjmatrix_edge_remove()).

EAGAIN

bstree_init() failed partway through, or multififo is busy (see multififo_islocked()).

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.