Data Structures (ds)#
- group ds
Data structures library.
For an overview, see Data Structures.
rcsw/ds/adjmatrix.h#
Adjacency matrix representation of a graph.
Functions
-
static inline size_t adjmatrix_n_vertices(const struct adjmatrix *matrix)#
The number of vertices in the graph.
-
static inline void *adjmatrix_access(const struct adjmatrix *const matrix, size_t u, size_t v)#
Access an element of the adjacency matrix.
- Parameters:
matrix – The matrix handle.
u – Edge source.
v – Edge sink.
- Returns:
The value of the edge between the two vertices (may dereference as 0 if no edge exists—used adjmatrix_edge_query() to be sure).
-
static inline size_t adjmatrix_element_space(size_t n_vertices, bool is_weighted)#
Get the # of bytes needed for an adjacency matrix.
- Parameters:
n_vertices – # vertices in the graph to be represented.
is_weighted – Is the graph weighted or not? Weighted graphs use doubles as the edge weights, and unweighted graphs use ints.
- Returns:
# total bytes required.
-
static inline bool adjmatrix_edge_query(const struct adjmatrix *const matrix, size_t u, size_t v)#
Determine if (u,v) exists.
- Parameters:
matrix – The matrix handle.
u – Vertex #1.
v – Vertex #2.
-
static inline size_t adjmatrix_n_edges(const struct adjmatrix *const matrix)#
Get the # of edges currently defined in the graph.
- Parameters:
matrix – The matrix handle.
- Returns:
The # of edges, or 0 on ERROR.
-
static inline void adjmatrix_print(const struct adjmatrix *const matrix)#
Print an adjacency matrix.
- Parameters:
matrix – The matrix handle.
-
static inline bool adjmatrix_isempty(const struct adjmatrix *matrix)#
Determine if the matrix/graph is empty, defined as having 0 defined edges.
- Parameters:
matrix – The matrix handle.
-
static inline status_t adjmatrix_transpose(struct adjmatrix *const matrix)#
Transpose an adjacency matrix. Use for moving from row -> col major and vice versa.
- Parameters:
matrix – The matrix handle.
- Returns:
-
struct adjmatrix *adjmatrix_init(struct adjmatrix *matrix_in, const struct adjmatrix_config *params)#
Initialize an adjacency matrix.
- Parameters:
matrix_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed; ignored (may be NULL) otherwise. See Memory Model .
params – Initialization parameters.
- Returns:
The initialized adjacency matrix, or NULL if an error occurred.
-
void adjmatrix_destroy(struct adjmatrix *matrix)#
Destroy an adjacency matrix. Any further use of the provided handle is undefined.
- Parameters:
matrix – The matrix handle.
-
status_t adjmatrix_edge_addd(struct adjmatrix *matrix, size_t u, size_t v, const double *w)#
Add a directed edge to the graph.
- Parameters:
matrix – The matrix handle.
u – Source vertex.
v – Sink vertex.
w – Weight of edge. Ignored for unweighted graphs (pass NULL probably).
- Returns:
-
status_t adjmatrix_edge_addu(struct adjmatrix *matrix, size_t u, size_t v)#
Add an undirected edge to the graph.
Adding an edge (u, v) also adds the edge (v, u). Undirected graphs are always unweighted (see adjmatrix), so no weight is taken.
- Parameters:
matrix – The matrix handle.
u – Vertex #1.
v – Vertex #2.
- Returns:
-
struct adjmatrix_config#
- #include <rcsw/ds/adjmatrix.h>
Adjacency matrix initialization parameters.
Public Members
-
dptr_t *elements#
Pointer to application-allocated space for storing the adjmatrix data. Ignored unless RCSW_NOALLOC_DATA is passed.
-
uint32_t flags#
Configuration flags. See adjmatrix::flags for valid flags.
-
size_t n_vertices#
Initial # of vertices for graph, for space allocation.
-
bool is_directed#
Is the graph directed or undirected?
-
bool is_weighted#
Are the graph edges weighted? Must be false if adjmatrix_config::is_directed is false: weighted undirected graphs are not supported (see adjmatrix).
-
dptr_t *elements#
-
struct adjmatrix#
- #include <rcsw/ds/adjmatrix.h>
Implementation of adjacency matrix representation of a “static” graph.
Static in the sense that the # of vertices in the graph cannot be changed after initialization. Graphs can be weighted or unweighted, and directed or undirected, with one exception:
Sentinel values in the matrix used for detecting if an edge exists are NAN for weighted graphs and 0 for unweighted graphs, so don’t use those values for valid edges.
Pros: Removing edges takes O(1). Queries like “is there an edge from vertex u
to vertex v” are efficient and can be done in O(1).
Cons: Consumes O(V^2) space, regardless of # edges (i.e. don’t use this for sparse graphs). Also you cannot use this data structure if the max # of edges in the graph is not known a priori.
Note
Weighted graphs must be directed. adjmatrix_init() rejects
is_weighted && !is_directed(function precondition: NULL underLIBRA_FPC_RETURN), because adjmatrix_edge_addu() takes no weight. To model a weighted undirected graph, make it directed and add each edge in both directions with adjmatrix_edge_addd(), and remove both directions when removing it.Note
Edge weights are always
doubleand unweighted edges areint; the element type is not configurable.Public Members
-
bool is_directed#
Is the graph directed?
-
bool is_weighted#
Is the graph weighted?
-
size_t n_edges#
Number of edges currently in the graph
-
struct matrix matrix#
Underlying matrix implementation handle. Its matrix_config::n_rows is the number of vertices, and its matrix_config::elt_size the size of an edge (
doubleif weighted,intif not).
-
uint32_t flags#
Configuration flags. Valid flags are:
All other flags are ignored.
-
bool is_directed#
rcsw/ds/allocm.h#
Allocation maps for fixed-size blocks in caller-provided memory.
Defines
-
RCSW_ALLOCM_INUSE#
Marks a block as allocated in an allocation map.
Functions
-
static inline size_t allocm_n_entries(size_t n_blocks)#
The # of allocm_entry needed to manage
n_blocksblocks.
-
static inline size_t allocm_map_bytes(size_t n_blocks)#
The # of bytes an allocation map for
n_blocksblocks occupies.Each entry is dptr_t aligned and sized, so storage laid out after the map keeps
RCSW_CONFIG_PTR_ALIGNalignment.
-
static inline bool allocm_inuse(const struct allocm_entry *map, size_t index)#
Whether block
indexis currently allocated.
-
void allocm_init(struct allocm_entry *map, size_t n_blocks)#
Initialize an allocation map, marking all
n_blocksblocks as free.mapmust have room for allocm_map_bytes() bytes.
-
int allocm_alloc(struct allocm_entry *map)#
Allocate a free block.
- Returns:
Index of the allocated block, or -1 if all blocks are in use.
-
void allocm_free(struct allocm_entry *map, size_t index)#
Return a block to the free list.
Freeing a block which is not currently allocated has no effect.
-
struct allocm_entry#
- #include <rcsw/ds/allocm.h>
An entry in an allocation map for fixed-size blocks (datablocks or nodes) in caller-provided memory.
A map managing N blocks is N+1 entries long (see allocm_n_entries()): entry 0 holds the index of the first free block (or -1 if none), and entry i+1 describes block i: the index of the next free block, -1 for the end of the free list, or RCSW_ALLOCM_INUSE. Allocation and deallocation are O(1).
Public Members
-
int32_t value#
-
int32_t value#
rcsw/ds/binheap.h#
Implementation of binary heap using darray.
Functions
-
static inline size_t binheap_lchild(size_t i)#
Index of the left child of element
iin a binheap.Indices are 1-based (slot 0 is scratch space), so the root is 1.
-
static inline bool binheap_isfull(const struct binheap *const heap)#
Determine if the heap is currently full.
- Parameters:
heap – The heap handle.
-
static inline bool binheap_isempty(const struct binheap *const heap)#
Determine if the heap is currently empty.
- Parameters:
heap – The heap handle.
-
static inline size_t binheap_size(const struct binheap *const heap)#
Determine # elements currently in the heap.
- Parameters:
heap – The heap handle.
- Returns:
# elements in heap, or 0 on ERROR.
-
static inline size_t binheap_capacity(struct binheap *heap)#
Get the heap capacity.
- Parameters:
heap – The heap handle.
- Returns:
# possible elements the heap can hold.
-
static inline size_t binheap_element_space(size_t max_elts, size_t elt_size)#
Calculate the # of bytes that the heap will require if RCSW_NOALLOC_DATA is passed to manage a specified # of elements of a specified size.
- Parameters:
max_elts – # of desired elements the heap will hold
elt_size – size of elements in bytes
- Returns:
The total # of bytes the application would need to allocate
-
static inline status_t binheap_clear(struct binheap *heap)#
Empty the heap, but don’t deallocate its data.
- Parameters:
heap – The heap handle.
- Returns:
-
static inline void *binheap_peek(const struct binheap *heap)#
Get an element from the heap without removing it.
- Parameters:
heap – The heap handle.
- Returns:
Reference to top element on heap, or NULL if an error occurred.
-
static inline size_t binheap_height(const struct binheap *heap)#
Get the current height of a binheap.
-
struct binheap *binheap_init(struct binheap *heap_in, const struct binheap_config *config)#
Initialize a heap.
- Parameters:
heap_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed; ignored (may be NULL) otherwise. See Memory Model .
config – Initialization parameters.
- Returns:
The initialized heap, or NULL if an error occurred.
-
void binheap_destroy(struct binheap *heap)#
Destroy a heap. Any further use of the heap handle after calling this function is undefined.
- Parameters:
heap – The heap handle.
-
status_t binheap_insert(struct binheap *heap, const void *e)#
Add element to heap.
- Parameters:
heap – The heap handle.
e – The element to add.
- Returns:
OK, if successful, ERROR otherwise.
-
status_t binheap_make(struct binheap *heap, const void *data, size_t n_elts)#
Convert an unordered array into a heap (presumably after you have copied a bunch of data into the heap array, instead of adding elements one at a time). This is O(n), rather than than the O(nlogn) for adding each element one at a time.
- Parameters:
heap – The heap handle.
data – A sequential array of data to turn into a heap.
n_elts – # of elements in the data array.
- Returns:
-
status_t binheap_extract(struct binheap *heap, void *e)#
Remove top element from heap.
The heap is rebuilt after the element is removed.
- Parameters:
heap – The heap handle.
e – The top element, to be filled.
- Returns:
-
status_t binheap_delete_key(struct binheap *heap, size_t index)#
Delete the key at index i on the heap.
The last element is moved into the hole and sifted to its correct position.
- Parameters:
heap – The heap handle.
index – The index to delete (1-based, 1 <= index <= size).
- Returns:
-
struct binheap_config#
- #include <rcsw/ds/binheap.h>
binheap initialization parameters.
Public Members
-
int (*cmpe)(const void *const e1, const void *const e2)#
For comparing elements. Cannot be NULL.
-
void (*printe)(const void *e)#
For printing an element. Can be NULL. If NULL, you can’t use binheap_print().
-
dptr_t *elements#
Pointer to application-allocated space for storing the binheap data. Ignored unless RCSW_NOALLOC_DATA is passed.
-
size_t elt_size#
Size of elements in bytes.
-
size_t max_elts#
Maximum number of elements allowed.
-
uint32_t flags#
Configuration flags. See binheap::flags for valid flags.
-
size_t init_size#
Initial size of heap.
-
int (*cmpe)(const void *const e1, const void *const e2)#
-
struct binheap#
- #include <rcsw/ds/binheap.h>
Binary heap structure.
A heap in which the smallest/largest element is guaranteed to always be on the top of the heap; other elements can be in any order.
Implemented using a binary tree inside a darray, starting at index 1; index 0 is used for a temp element for swapping elements during sifting.
Public Members
-
uint32_t flags#
Configuration flags. Valid flags are:
All other flags are ignored.
-
uint32_t flags#
rcsw/ds/bstree.h#
Binary search tree, and the base of the red-black, order statistics, and interval trees.
Enums
Functions
-
static inline struct bstree_node *bstree_root(const struct bstree *const tree)#
Get the root node of the tree.
The tree’s bstree::root is a sentinel; the real root is its left child. Returns bstree::nil if the tree is empty, and NULL if
treeis NULL (function precondition).
-
static inline bool bstree_isfull(const struct bstree *const bst)#
Determine if a bstree is currently full.
- Parameters:
bst – The BST handle
-
static inline bool bstree_isempty(const struct bstree *const bst)#
Determine if a bstree is currently empty.
- Parameters:
bst – The BST handle
-
static inline size_t bstree_size(const struct bstree *const bst)#
Determine # elements currently a bstree.
- Parameters:
bst – The BST handle
- Returns:
# elements in bst, or 0 on ERROR
-
static inline size_t bstree_element_space(size_t max_elts, size_t elt_size)#
Calculate the # of bytes that the BST will require if RCSW_NOALLOC_DATA is passed to manage a specified # of elements of a specified size.
The +2 is for the root and nil nodes.
- Parameters:
max_elts – # of desired elements the BST will hold
elt_size – size of elements in bytes
- Returns:
The total # of bytes the application would need to allocate
-
static inline size_t bstree_meta_space(size_t max_elts)#
Calculate the space needed for the nodes in a bstree.
Used in conjunction with RCSW_NOALLOC_META. The +2 is for the root and nil nodes.
- Parameters:
max_elts – Max # of elements the BST will hold.
- Returns:
The # of bytes required.
-
status_t bstree_insert(struct bstree *tree, void *key, void *data)#
Insert an item into a bstree.
Keys are fixed-size: exactly RCSW_BSTREE_NODE_KEYSIZE bytes are copied from
key, and bstree_config::cmpkey compares those copies. Duplicate keys are rejected (ERROR with errno=EEXIST).- Parameters:
tree – The BST handle
key – The key for the data to insert. Must point to RCSW_BSTREE_NODE_KEYSIZE readable bytes.
data – The data to insert
-
struct bstree *bstree_init(struct bstree *tree_in, const struct bstree_config *params)#
Initialize a bstree.
- Parameters:
tree_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed; ignored (may be NULL) otherwise. See Memory Model .
params – Initialization parameters
-
void bstree_destroy(struct bstree *tree)#
Destroy a binary search tree.
Any further use of the tree after calling this function is undefined.
- Parameters:
tree – The BST to destroy
-
status_t bstree_remove(struct bstree *tree, const void *key)#
Remove the node in a BST that contains data that matches the given key.
- Parameters:
tree – The BST handle
key – Key to match in the search for the node to delete
- Returns:
status_t. ERROR with errno=ENOENT if no node has
key.
-
status_t bstree_delete(struct bstree *tree, struct bstree_node *victim, void *elt)#
Delete a node from the tree.
The algorithm from this function is from Introduction_To_Algorithms
- Parameters:
tree – The BST handle
victim – The node to delete
elt – To be filled with the data of the deleted node if non-NULL
- Returns:
-
struct bstree_node *bstree_node_query(const struct bstree *tree, struct bstree_node *search_root, const void *key)#
Query a BST for a specific node, starting the search at the specified search root.
- Parameters:
tree – The BST handle
search_root – The root of the search (not necessarily the root of the tree)
key – The key to match
- Returns:
The node with the matching key, or NULL if not found
-
void *bstree_data_query(const struct bstree *tree, const void *key)#
Get the data associated with a key.
This function returns the data in the first node for which the compare function returned 0 for.
- Parameters:
tree – The BST handle
key – The key to search for
- Returns:
The data associated with the key, or NULL if no match for key was found
-
int bstree_traverse(struct bstree *tree, int (*cb)(const struct bstree *tree, struct bstree_node *node), enum bstree_traversal_type type)#
Traverse a binary search tree and operate on each node’s data.
Can traverse in a pre-order, post-order, or in-order way.
If the callback returns nonzero on a given node, then the traversal is aborted.
- Parameters:
tree – The BST handle
cb – Callback called on each node in the tree, and passed the BST handle. Cannot be used to modify the BST handle, but CAN modify the node.
type – The type of traversal to perform.
- Returns:
Return code of last callback that was non-zero, or 0 if callback succeeded on all nodes
-
status_t bstree_map(struct bstree *tree, void (*f)(void *e), enum bstree_traversal_type type)#
Apply a function to the data of every node in a bstree.
This is the uniform higher-order counterpart to bstree_traverse(). The callback receives only the element data pointer (not the internal node), matching the signature used by darray_map(), llist_map(), etc.
- Parameters:
tree – The BST handle.
f – Callback applied to each element. May modify element data but must not insert or remove nodes.
type – Traversal order: pre-, in-, or post-order.
- Returns:
-
status_t bstree_inject(struct bstree *tree, void (*f)(void *e, void *result), void *result, enum bstree_traversal_type type)#
Compute a cumulative result over all elements in a bstree.
- Parameters:
tree – The BST handle.
f – Callback applied to each element. First argument is the element data; second argument is
result.result – Initial result value, updated in place by
f.type – Traversal order.
- Returns:
-
status_t bstree_insert_internal(struct bstree *tree, void *key, void *data, size_t node_size)#
Insert a new data into a BST.
This should NEVER be called by an application—for internal use only.
- Parameters:
tree – The BST handle
key – The key of the data to insert
data – The data to insert
node_size – The size of the nodes in the tree, in bytes
- Returns:
-
struct bstree *bstree_init_internal(struct bstree *tree_in, const struct bstree_config *params, size_t node_size)#
Initialize a binary search (or related) tree, which may have different node sizes.
This should NEVER be called by an application—for internal use only.
- Parameters:
tree_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed; ignored (may be NULL) otherwise. See Memory Model .
params – Initialization parameters
node_size – The size of the nodes in the tree, in bytes
- Returns:
The initialized tree, or NULL if an error occurred
-
struct bstree_config#
- #include <rcsw/ds/bstree.h>
Parameters for bstree.
Public Members
-
int (*cmpkey)(const void *const e1, const void *const e2)#
For comparing keys associated with elements. Cannot be NULL.
-
void (*printe)(const void *e)#
For printing an element. Can be NULL.
-
dptr_t *meta#
Pointer to application-allocated space for storing the bstree nodes. Ignored unless RCSW_NOALLOC_META is passed.
-
dptr_t *elements#
Pointer to application-allocated space for storing data managed by the bstree. Ignored unless RCSW_NOALLOC_DATA is passed.
-
size_t elt_size#
Size of elements in bytes.
-
int max_elts#
Maximum number of elements allowed. -1 = no upper limit.
-
uint32_t flags#
Configuration flags. Valid flags are:
All other flags are ignored.
-
int (*cmpkey)(const void *const e1, const void *const e2)#
-
struct bstree_node#
- #include <rcsw/ds/bstree.h>
The base node for all binary search trees.
For all nodes from trees derived from bstree, the node MUST:
(1) Have all the fields present below and have them declared in the same order as the “parent” structs.
(2) Have the same size as the “parent” struct entries.
This is so that I can take the derived class struct, cast it to a bstree/bstree_node, and pass it to a function in the bstree class, and have everything work as desired.
Aligned to dptr_t, so that arrays of these in caller-provided memory keep every member naturally aligned. (Not packed: packing would misalign the pointer members.)
Public Members
-
uint8_t key[sizeof(int32_t)]#
-
struct bstree_node *left#
-
struct bstree_node *right#
-
struct bstree_node *parent#
-
bool red#
If the tree is used as a red-black tree, then this field is used to indicate the color of the node. It is undefined for regular BSTs. If red is false then the node is black.
-
int32_t tmp#
-
uint8_t key[sizeof(int32_t)]#
-
struct bstree_space_mgmt#
- #include <rcsw/ds/bstree.h>
Container for all memory (space) used by a bstree.
Public Members
-
dptr_t *datablocks#
Space for the data elements. Used if RCSW_NOALLOC_DATA passed in bstree_config::flags.
-
struct allocm_entry *db_map#
Space for the allocation map for datablocks. Used if RCSW_NOALLOC_DATA passed in bstree_config::flags.
-
struct bstree_node *nodes#
Space for bstree_node objects. Used if RCSW_NOALLOC_META passed in bstree_config::flags.
-
struct allocm_entry *node_map#
Space for the allocation map for bstree_node objects. Used if RCSW_NOALLOC_META passed in bstree_config::flags.
-
dptr_t *datablocks#
-
struct bstree#
- #include <rcsw/ds/bstree.h>
Binary Search Tree using approach from Introduction to Algorithms.
Public Members
-
struct bstree_config cfg#
The configuration the tree was initialized with, with bstree_config::flags, bstree_config::elt_size and bstree_config::cmpkey as the tree uses them (ostree_init() and inttree_init() set some of these themselves). bstree_config::meta and bstree_config::elements are as passed (NULL unless caller-provided memory is used); bstree::space holds the views into them.
-
struct bstree_space_mgmt space#
Management of all node and element space for the tree.
-
size_t current#
Number of nodes/elements currently in the tree.
-
size_t depth#
Current depth as a traversal progresses.
-
struct bstree_node *root#
Root of the tree (sentinel). root->left should always point to the node which is the root of the tree. Use this so that there are fewer special cases/less checking for NULL pointers.
-
struct bstree_node *nil#
Sentinel. Points to a node which should always be black (for red-black trees) but has aribtrary children and parent. Use this so that there are no fewer special cases in the code/less checking for NULL pointers.
-
struct bstree_config cfg#
rcsw/ds/bstree_node.h#
Binary search tree node operations. Only bstree_node_height() is public; the rest is internal to the tree implementations.
Functions
-
size_t bstree_node_height(const struct bstree *tree, const struct bstree_node *node)#
Get the height of a binary search tree anchored at a node.
- Parameters:
tree – The BST handle.
node – The root of the subtree to get the height of.
- Returns:
The height or 0 if the node is NULL
rcsw/ds/darray.h#
Dynamic array.
Functions
-
static inline bool darray_isfull(const struct darray *const arr)#
Determine if the dynamic array is currently full.
- Parameters:
arr – The dynamic array handle
-
static inline bool darray_isempty(const struct darray *const arr)#
Determine if the dynamic arrayis currently empty.
- Parameters:
arr – The dynamic array handle
-
static inline size_t darray_size(const struct darray *const arr)#
Determine # elements currently in the darray.
- Parameters:
arr – The dynamic array handle
- Returns:
# elements in arr, or 0 on ERROR
-
static inline size_t darray_capacity(const struct darray *const arr)#
Determine array capacity.
- Parameters:
arr – The dynamic array handle.
- Returns:
# slots currently allocated, or 0 on ERROR.
-
static inline status_t darray_set_size(struct darray *const arr, size_t n_elts)#
Set # elements currently in the darray.
You can’t use this function to the # elements to greater than the current capacity, even if the max # of elements for the array is greater. Use darray_resize() if you need that.
- Parameters:
arr – The dynamic array handle.
n_elts – The new # of elements in the array.
- Returns:
-
static inline size_t darray_element_space(size_t max_elts, size_t elt_size)#
Calculate the # of bytes that will be required for the specified # of elements and the element size.
- Parameters:
max_elts – # of desired elements the dynamic array will hold.
elt_size – size of elements in bytes.
- Returns:
The total # of bytes the application would need to allocate.
-
struct darray *darray_init(struct darray *arr_in, const struct darray_config *params)#
Initialize an darray.
It is valid to initialize the darray with an initial size of 0.
- Parameters:
arr_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed; ignored (may be NULL) otherwise. See Memory Model .
params – Initialization parameters.
- Returns:
The initialized list, or NULL if an ERROR occurred
-
void darray_destroy(struct darray *arr)#
Delete a darray.
Any use of the darray handle after calling this function is undefined.
- Parameters:
arr – The darray handle
-
status_t darray_clear(struct darray *arr)#
Clear a darray.
Resets the count of # elements in array to 0, and memset()s all elements to 0.
- Parameters:
arr – The darray handle
- Returns:
-
status_t darray_data_clear(struct darray *arr)#
Clear a darray’s data (the element count is not affected)
Memset()s all elements to 0.
- Parameters:
arr – The darray handle
- Returns:
-
status_t darray_insert(struct darray *arr, const void *e, size_t index)#
Insert an item into an darray.
Inserts an item into the given position in the darray. If the array currently full, it will be extended to accomodate the new element, unless doing so would cause the max_elts for the darray to be exceeded. If RCSW_DS_SORTED was passed during initialization, the darray is resorted after insertion.
If the array was initialized with an unlimited maximum # of elements, then the array is extended to twice its current size (for amortized O(1) insertions).
- Parameters:
arr – The darray handle
e – The element to insert
index – The index to insert at. If 0, this function behaves as a prepend function (very inefficient, but allowable). If equal to darray_size(), behaves as append function (efficient—use this).
- Returns:
-
status_t darray_remove(struct darray *arr, void *e, size_t index)#
Remove an item from an darray.
If RCSW_DS_SORTED was passed during initialization, then the remaining elements in the list are shifted to close the empty slot and preserve the sort order (inefficient). If RCSW_DS_SORTED was not passed during initialization, then the last element in the array is simply used to overwrite the element to be removed, which is a much faster operation.
If the darray’s storage is heap-allocated (not RCSW_NOALLOC_DATA), then it is shrunk to 1/2 its current capacity whenever the current deletion brought its utilization down at or below 25% (for amortized O(1) deletions).
- Parameters:
arr – The darray handle
e – To be filled with the removed element if non-NULL
index – The index of the element to remove
- Returns:
-
status_t darray_idx_serve(const struct darray *arr, void *e, size_t index)#
Get an element in a darray (array not modified)
- Parameters:
arr – The darray handle
e – To be filled with the served element
index – Index of element to get
- Returns:
-
int darray_idx_query(const struct darray *arr, const void *e)#
Find the index of an element.
Find an element in the darray which is equal to e: the first one in a linear scan, or any one of several equal elements in a binary search. A recursive implementation of binary search will be used if the darray is sorted, linear scan otherwise. This function can only be called if darray::cmpe was non-NULL during initialization.
- Parameters:
arr – The darray handle
e – The element to search for.
- Returns:
The index, or -1 if not found
-
void *darray_data_get(const struct darray *arr, size_t index)#
Retrieve an item from an darray.
Returns the item at the specified index. There is NO upper bounds checking to make sure that index < darray_size().
- Parameters:
arr – The darray handle.
index – The index to get the data for.
- Returns:
The element, or NULL if an error occurred
-
status_t darray_data_set(struct darray *arr, size_t index, const void *e)#
Set an item in a darray.
Sets the item at the specified index to the passed in value. Because this can break a sorted order, the array is no longer considered sorted afterwards.
- Parameters:
arr – The darray handle
index – The index of the item to set. Must be < darray_size().
e – The new value
- Returns:
-
status_t darray_resize(struct darray *arr, size_t size)#
Resize a darray.
Resizes the darray to the specified size. If size < current capacity of the array, then the array is reduced to its first “size” elements. If size > current capacity, then the array is increased to be able to hold “size” elements.
- Parameters:
arr – The darray handle.
size – The new size.
- Returns:
-
status_t darray_data_copy(struct darray *arr1, const struct darray *arr2)#
Copy the data from one darray to another.
Afterwards the destination holds exactly the source’s elements (its size becomes the source’s size). The element sizes must be the same. The destination is extended if it is too small and can grow (heap storage, and its max_elts allows it); otherwise ERROR with errno=ENOSPC. The two arrays’ storage cannot overlap.
- Parameters:
arr1 – The destination.
arr2 – The source.
- Returns:
-
status_t darray_sort(struct darray *arr, enum exec_type type)#
Sort a darray.
Can only be called if darray::cmpe was non-NULL during initialization.
-
status_t darray_map(struct darray *arr, void (*f)(void *e))#
Apply a function to all elements in the darray.
- Parameters:
arr – The darray handle.
f – The callback for each element (can modify elements).
- Returns:
-
status_t darray_inject(const struct darray *arr, void (*f)(void *e, void *res), void *result)#
Compute a cumulative result (sum, count, …) over all elements in the darray.
- Parameters:
arr – The darray handle
f – The callback for each element (can modify elements). It is passed each element in turn, along with the in-progress result.
result – The initial result.
- Returns:
-
struct darray *darray_filter(struct darray *arr, bool (*pred)(const void *e), uint32_t flags, void *elements)#
Filter out elements into a new darray.
Iterate through the darray and find all the items that satisfy the predicate, and return a new darray containing only the items for which the predicate returned true. Matched elements are transferred from the original array to the new array, and removed from the original array. If no elements are found that fulfill the predicate, an empty darray is returned.
-
struct darray *darray_copy(const struct darray *arr, uint32_t flags, void *elements)#
Create a copy of a darray.
Makes a copy of an darray by initializing a new darray and copying the original darray’s data to it. The original darray is unchanged.
-
struct ds_iterator *darray_iter_init(struct ds_iterator *iter, struct darray *arr, enum ds_iter_type type, bool (*classify)(void *e))#
Initialize an iterator over a darray.
- Parameters:
iter – Caller-allocated iterator storage.
arr – The darray to iterate over.
type – ITER_FORWARD or ITER_BACKWARD.
classify – Optional filter predicate; pass NULL for no filtering.
- Returns:
iteron success, or NULL on error.
-
struct darray_config#
- #include <rcsw/ds/darray.h>
Dynamic array (darray) initialization parameters.
Public Members
-
int (*cmpe)(const void *const e1, const void *const e2)#
For comparing elements. Can be NULL. If NULL, sorting the darray is disabled.
-
void (*printe)(const void *e)#
For printing an element. Can be NULL. If NULL, you can’t use darray_print().
-
dptr_t *elements#
Pointer to application-allocated space for storing data managed by the darray. Ignored unless RCSW_NOALLOC_DATA is passed.
-
size_t elt_size#
Size of elements in bytes.
-
int max_elts#
Maximum number of elements allowed. -1 = no upper limit.
-
uint32_t flags#
Configuration flags. See darray::flags for valid flags.
-
size_t init_size#
Initial size of the array (must be < max_elts). Ignored if RCSW_NOALLOC_DATA is passed.
-
int (*cmpe)(const void *const e1, const void *const e2)#
-
struct darray#
- #include <rcsw/ds/darray.h>
Dynamic array data structure.
It follows the dynamic table resizing algorithm from _Introduction_to_Algorithms, in order to provide O(1) amortized insertions and deletions. You can also resize the darray to whatever size you want at any time.
Public Members
-
uint8_t *elements#
The array that holds the actual data
-
size_t current#
Next item in the darray will be inserted here (also # of elements in darray).
-
size_t capacity#
Current capacity of array in # slots.
-
size_t elt_size#
Size in bytes of an element.
-
bool sorted#
Is the array is currently sorted?
-
int max_elts#
Maximum number of elements allowed in the array (-1 for no limit)
-
uint32_t flags#
Run-time configuration flags.
Valid flags are:
All other flags are ignored.
-
int (*cmpe)(const void *const e1, const void *const e2)#
For comparing elements for <,=,>. Can be NULL. If NULL, certain darray operations aren’t allowed (like sorting).
-
void (*printe)(const void *e)#
For printing an element (can be NULL)
-
uint8_t *elements#
rcsw/ds/ds.h#
Common definitions for all data structures.
Defines
-
RCSW_DS_SORTED#
Keep the data structure sorted after insertions/deletions. Also implies maintaining the relative ordering of elements.
Applies to:
-
RCSW_DS_ORDERED#
Maintain the relative ordering between elements as they are inserted, but not sort the elements.
Applies to:
-
RCSW_DS_HASHMAP_LINPROB#
Indicate that the hashmap should perform linear probing if the bucket that an item hashes into is currently full.
Results in greater hashmap utilization. Lookups (including the duplicate check on every add) search the home bucket and up to hashmap::max_probe buckets after it, which grows as nodes spill out of full buckets.
-
RCSW_DS_RBUFFER_AS_FIFO#
Indicate that a rbuffer should act as a FIFO (i.e., items are never overrwritten/only added to ringbuffer when the ringbuffer is not currently full.
-
RCSW_DS_LLIST_DB_DISOWN#
Indicate that a llist should NOT to allocate/deallocate a datablock for a llist_node when the llist_node is allocated/deallocated. This is useful when you are pointing to valid datablocks that are managed by another data structure. An example use case would be an LRU list pointing to datablocks within a cache.
The list stores the caller’s pointers and never allocates or frees datablocks. Consequently:
Removing elements (llist_remove(), llist_remove_if(), llist_delete(), llist_clear()) releases only the nodes; the data remains owned by whoever owns it.
Lists created from this one (llist_copy(), llist_copy_if(), llist_filter()) copy the data, unless they are themselves created with RCSW_DS_LLIST_DB_DISOWN or RCSW_DS_LLIST_DB_PTR.
llist_filter() into a list with one of these flags is refused unless the source list has one too, and llist_splice() requires both lists to agree on them.
-
RCSW_DS_LLIST_DB_PTR#
Indicate that a llist should NOT use compare function when checking for equality/searching the linked list. Instead, the pointers for llist_node->data are compared. This is useful when you have a pair of linked lists as free/alloc lists which don’t point to actual data, but only carve up a chunk of memory.
This flag implies RCSW_DS_LLIST_DB_DISOWN.
-
RCSW_DS_BSTREE_RB#
Indicate that a bstree should function as a red-black tree and rebalance itself after insertions and deletions.
-
RCSW_DS_BSTREE_INT#
Indicate that a bstree should function as an interval tree.
Set automatically by inttree_init(), which also sets RCSW_DS_BSTREE_RB and the element size; there is no need to pass it.
-
RCSW_DS_BSTREE_OS#
Indicate that a bstree should function as an Order Statistics Tree.
Set automatically by ostree_init(), which also sets RCSW_DS_BSTREE_RB; there is no need to pass it.
-
RCSW_DS_BINHEAP_MIN#
Indicate that a binheap should function as a min heap. If you do not pass this flag, binheap will function as a max heap.
-
RCSW_DS_EXTFLAGS_SHIFT#
Bit position of the first flag bit not used by
ds. Data structures built on top ofdsdefine their flags as(1 << (RCSW_DS_EXTFLAGS_SHIFT + n))to avoid conflicts.
Enums
Functions
-
static inline size_t ds_meta_space(size_t max_elts)#
Calculate how large the chunk of memory for the metadata for a data structure needs to be, given a max # of elements.
Used in conjunction with RCSW_NOALLOC_DATA and/or RCSW_NOALLOC_META for data structures requiring metadata.
You really shouldn’t use this function.
- Parameters:
max_elts – Max # elements the structure will manage.
- Returns:
Total # of bytes required.
-
static inline size_t ds_elt_space_simple(size_t max_elts, size_t elt_size)#
Calculate how large the chunk of memory for some “element” that a data structure will manage needs to be, given a max # of elements and element size. “Element” can refer to the nodes needed by some data structures, or the actual elements the data structure will manage.
For data structures that do NOT require metadata (FIFOs, ringbuffers, etc.).
You really shouldn’t use this function—use the specific calculation functions for each data structure found in their respective header files. Used in conjunction with RCSW_NOALLOC_DATA.
- Parameters:
max_elts – Max # elements the structure will manage
elt_size – Size of each element in bytes
- Returns:
Total # of bytes required
-
static inline size_t ds_elt_space_with_meta(size_t max_elts, size_t elt_size)#
Calculate how large the chunk of memory for the elements that a data structure will manage needs to be, given a max # of elements and element size.
For data structures that DO require metadata (trees, linked lists, etc.).
You really shouldn’t use this function—use the specific calculation functions for each data structure found in their respective header files. Used in conjunction with RCSW_NOALLOC_DATA.
- Parameters:
max_elts – Max # elements the structure will manage
elt_size – Size of each element in bytes
- Returns:
Total # of bytes required
-
status_t ds_elt_clear(void *elt, size_t elt_size)#
Utility function to clear an element.
Zeroes the element’s bytes with memset(), so the element needs no particular alignment.
- Parameters:
elt – Element to clear.
elt_size – Size of element in bytes.
- Returns:
-
status_t ds_elt_copy(void *elt1, const void *elt2, size_t elt_size)#
Utility function to copy elt2 into elt1, overwriting.
Copies the element’s bytes with memcpy(), so the elements need no particular alignment. Does nothing if
elt1andelt2are the same.- Parameters:
elt1 – Destination.
elt2 – Source.
elt_size – Size of elements in bytes.
- Returns:
rcsw/ds/dynmatrix.h#
Dynamically sized matrix.
Functions
-
static inline void *dynmatrix_access(const struct dynmatrix *const matrix, size_t u, size_t v)#
Access an element within a dynamic matrix.
The element must exist within the matrix (i.e. this function does not expand the matrix).
- Parameters:
matrix – The matrix handle.
u – The row within the matrix.
v – The column within the matrix.
- Returns:
Reference to element, or NULL if an error occurred.
-
static inline size_t dynmatrix_space(size_t n_rows, size_t n_cols, size_t elt_size)#
Calculate the # of bytes required for the initial size of the dynamic matrix.
- Parameters:
n_rows – Initial # rows.
n_cols – Initial # columns.
elt_size – Size of the elements in bytes.
- Returns:
The # of bytes required.
-
static inline status_t dynmatrix_clear(struct dynmatrix *const matrix, size_t u, size_t v)#
Clear an element within the dynamic matrix.
- Parameters:
matrix – The matrix handle.
u – Row of element to clear.
v – Column of element to clear.
- Returns:
-
static inline bool dynmatrix_issquare(const struct dynmatrix *const matrix)#
Return if the dynmatrix is square or not.
-
struct dynmatrix *dynmatrix_init(struct dynmatrix *matrix_in, const struct dynmatrix_config *params)#
Initialize a dynamic matrix.
- Parameters:
matrix_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed; ignored (may be NULL) otherwise. See Memory Model .
params – The initialization parameters.
- Returns:
The initialized matrix, or NULL if an error occurred.
-
void dynmatrix_destroy(struct dynmatrix *matrix)#
Destroy a dynamic matrix.
Any further use of the handle is undefined after this function is called.
- Parameters:
matrix – The matrix handle.
-
status_t dynmatrix_transpose(struct dynmatrix *matrix)#
Transpose a dynamic matrix in place.
Note
Square matrices only; a non-square matrix fails the function precondition (ERROR under
LIBRA_FPC_RETURN). For an M x N matrix, dynmatrix_resize() it to K x K with K = max(M,N), transpose, then resize it to N x M.- Parameters:
matrix – The matrix handle.
- Returns:
-
void dynmatrix_print(const struct dynmatrix *matrix)#
Print a dynamic matrix.
Calls the printe() function on each element in the matrix.
- Parameters:
matrix – The matrix handle.
-
status_t dynmatrix_resize(struct dynmatrix *matrix, size_t u, size_t v)#
Resize a dynamic matrix manually.
Existing elements inside the new bounds keep their values; new elements are zero. The resize is all-or-nothing: if it fails (e.g., out of memory), the matrix keeps its old dimensions and contents, though some memory reserved along the way may not be released until a later resize or destroy.
- Parameters:
matrix – The matrix handle.
u – The desired # of rows. Can be <,>,= the current #. If =, no action is performed.
v – The desired # of columns. Can be <,>,= the current #. If =, no action is performed.
- Returns:
-
status_t dynmatrix_set(struct dynmatrix *matrix, size_t u, size_t v, const void *w)#
Set an element in the dynamic matrix to a specific value.
If the row/column is outside the current bounds of the matrix, the matrix will be resized to accommodate.
- Parameters:
matrix – The matrix handle.
u – Element row index.
v – Element column index.
w – New element value.
- Returns:
-
struct dynmatrix_config#
- #include <rcsw/ds/dynmatrix.h>
Dynamic matrix initialization parameters.
Public Members
-
void (*printe)(const void *e)#
For printing an element. Can be NULL.
-
size_t elt_size#
Size of elements in bytes.
-
uint32_t flags#
Configuration flags. See dynmatrix::flags for valid flags; in particular, element storage is always heap-allocated.
-
void (*printe)(const void *e)#
-
struct dynmatrix#
- #include <rcsw/ds/dynmatrix.h>
Representation of a dynamically-sized matrix using a dynamic array row vectors, with each row vector also being a dynamic array.
Dynamic in the sense that the matrix dimensions can be changed after initialization. The matrix can grow to be any size, but an initial size can be specified during initialization, as the resizing operation can be very expensive, depending on the current size of the matrix. Assumes row-major order (this is C after all).
Should only be used for applications where the matrix is dense, or when the dimensions of the matrix are small (if the dimensions are large AND the matrix is sparse, it will definitely be really inefficient, and possibly won’t even fit into memory). In addition, this data structure should really only be used if you can guarantee that resizing the matrix happens infrequently.
Besides dynmatrix_resize(), the matrix grows when dynmatrix_set() is given an out-of-bounds index; no other function resizes it.
Note
Only the handle can be caller-provided (RCSW_NOALLOC_HANDLE). The row vector and every row are always heap-allocated, so RCSW_NOALLOC_DATA and RCSW_NOALLOC_META have no effect and a dynmatrix cannot be used in builds without a heap. Use matrix (fixed dimensions, caller-provided storage allowed) there instead.
Public Members
-
size_t n_rows#
Number of rows in matrix.
-
size_t n_cols#
Number of columns in matrix.
-
size_t elt_size#
Size of matrix elements in bytes.
-
uint32_t flags#
Configuration flags. Valid flags are:
RCSW_ZALLOC (zeroes the handle; elements are always zero-initialized regardless)
All other flags are ignored, including RCSW_NOALLOC_DATA and RCSW_NOALLOC_META.
-
void (*printe)(const void *const e)#
For printing an element. Can be NULL. If NULL, then dynmatrix_print() is disabled.
-
size_t n_rows#
rcsw/ds/fifo.h#
General-purpose FIFO built on a ringbuffer.
Functions
-
static inline bool fifo_isfull(const struct fifo *const fifo)#
Determine if the FIFO is currently full.
- Parameters:
fifo – The FIFO handle
-
static inline bool fifo_isempty(const struct fifo *const fifo)#
Determine if the FIFO is currently empty.
- Parameters:
fifo – The FIFO handle
-
static inline size_t fifo_size(const struct fifo *const fifo)#
Determine # elements currently in the FIFO.
- Parameters:
fifo – The FIFO handle.
- Returns:
# elements in FIFO, or 0 on ERROR.
-
static inline size_t fifo_capacity(const struct fifo *const fifo)#
Get the FIFO capacity.
- Parameters:
fifo – The FIFO handle.
- Returns:
Capacity of the FIFO, or 0 on ERROR.
-
static inline void *fifo_front(const struct fifo *const fifo)#
Get the first FIFO item without removing it.
- Parameters:
fifo – The FIFO handle.
- Returns:
Pointer to the first element, or NULL if no such element or an error occurred.
-
static inline size_t fifo_element_space(size_t max_elts, size_t elt_size)#
Calculate the # of bytes that the FIFO will require if RCSW_NOALLOC_DATA is passed to manage a specified # of elements of a specified size.
- Parameters:
max_elts – # of desired elements the FIFO will hold
elt_size – size of elements in bytes
- Returns:
The total # of bytes the application would need to allocate
-
static inline struct fifo *fifo_init(struct fifo *const fifo_in, const struct fifo_config *const params)#
Initialize a FIFO.
- Parameters:
fifo_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed; ignored (may be NULL) otherwise. See Memory Model .
params – The initialization parameters.
- Returns:
The initialized FIFO, or NULL if an error occurred (errno is set by rbuffer_init()).
-
static inline void fifo_destroy(struct fifo *const fifo)#
Destroy a FIFO.
Any further use of the FIFO after this function is called is undefined.
- Parameters:
fifo – The FIFO to destroy.
-
static inline status_t fifo_add(struct fifo *const fifo, const void *const e)#
Enqueue an element into the FIFO.
- Parameters:
fifo – The FIFO handle.
e – The element to enqueue. Cannot be NULL.
- Returns:
status_t. ERROR with errno=ENOSPC if the FIFO is full.
-
static inline status_t fifo_remove(struct fifo *const fifo, void *const e)#
Dequeue an element from the FIFO.
- Parameters:
fifo – The FIFO handle.
e – The element to dequeue into from the FIFO. Can be NULL.
- Returns:
-
static inline status_t fifo_clear(struct fifo *const fifo)#
Clear a FIFO.
Empty the FIFO, but do not deallocate its memory.
- Returns:
-
static inline status_t fifo_map(struct fifo *const fifo, void (*f)(void *e))#
Apply an operation to all elements of the FIFO.
- Parameters:
fifo – The FIFO handle.
f – A function pointer which will be called for every element in the FIFO. This function CAN modify FIFO elements.
- Returns:
-
static inline status_t fifo_inject(struct fifo *const fifo, void (*f)(void *e, void *res), void *const result)#
Compute a cumulative result (sum, count, …) over all elements of a FIFO.
- Parameters:
fifo – The FIFO handle.
f – A function point which will be called for every element in the FIFO. This function CAN modify FIFO elements.
result – The initial value for the cumulative result to be computed. This will be passed to each invocation of the callback.
- Returns:
-
struct fifo_config#
- #include <rcsw/ds/fifo.h>
Parameters for fifo.
Public Members
-
void (*printe)(const void *e)#
For printing an element. Can be NULL. If NULL, you can’t use fifo_print().
-
dptr_t *elements#
Pointer to application-allocated space for storing data managed by the fifo. Ignored unless RCSW_NOALLOC_DATA is passed.
-
size_t elt_size#
Size of elements in bytes.
-
size_t max_elts#
Maximum number of elements allowed.
-
void (*printe)(const void *e)#
-
struct fifo#
- #include <rcsw/ds/fifo.h>
General purpose FIFO.
A thin, type-safe wrapper around a rbuffer created with RCSW_DS_RBUFFER_AS_FIFO; every fifo_*() function is static inline and forwards to the matching rbuffer_*() function. This implementation is more full-featured than rawfifo, but is not safe to use in ISRs.
Handle storage and the valid flags are as for rbuffer, namely RCSW_ZALLOC, RCSW_NOALLOC_HANDLE and RCSW_NOALLOC_DATA (in fifo_config::flags); all other flags are ignored.
rcsw/ds/hashmap.h#
Hashmap with fixed-size buckets.
Defines
-
RCSW_HASHMAP_KEYSIZE#
Size of the key storage in each hashnode, in bytes.
Keys are stored zero-padded to this size, and two keys are equal if all RCSW_HASHMAP_KEYSIZE bytes are equal. The maximum value of hashmap_config::key_len.
Functions
-
static inline size_t hashmap_element_space(size_t n_buckets, size_t bucket_size, size_t elt_size)#
Calculate the # of bytes that the hashmap will require if RCSW_NOALLOC_DATA is passed to manage a specified # of elements of a specified size.
We compute the # max elements so that you don’t have to worry about the # buckets not being an even multiple of the max # elements, and allocating too little space because of rounding errors.
- Parameters:
n_buckets – The # buckets in the hashmap.
bucket_size – The size of each bucket in the hashmap.
elt_size – Size of elements in bytes.
- Returns:
The total # of bytes the application would need to allocate.
-
static inline size_t hashmap_meta_space(size_t n_buckets)#
Calculate the space needed for the nodes in the hashmap.
Used in conjunction with RCSW_NOALLOC_META.
- Parameters:
n_buckets – # of desired buckets in the hashmap
- Returns:
The # of bytes required
-
struct hashmap *hashmap_init(struct hashmap *map_in, const struct hashmap_config *params)#
Initialize a hashmap.
- Parameters:
map_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed; ignored (may be NULL) otherwise. See Memory Model .
params – Initialization parameters
- Returns:
The initialized hashmap, or NULL if an error occurred
-
void hashmap_destroy(struct hashmap *map)#
destroy a hashmap. Any further use of the hashmap after calling this function is undefined.
-
status_t hashmap_sort(struct hashmap *map)#
Sort a hashmap.
Sorts every bucket, so that lookups in it use binary search. Not needed if RCSW_DS_SORTED was passed during initialization: the buckets are then kept sorted on every insertion.
- Parameters:
map – The hashmap handle.
- Returns:
-
status_t hashmap_clear(struct hashmap *map)#
Clear a hashmap, but don’t deallocate its data.
- Parameters:
map – The hashmap handle.
- Returns:
-
void *hashmap_data_get(struct hashmap *map, const void *key)#
Returns the data from the hashmap corresponding to the given key.
- Parameters:
map – The hashmap handle.
key – Key to match with. Must point to hashmap_config::key_len readable bytes.
- Returns:
The data, or NULL if an error occurred or the data was not found.
-
status_t hashmap_add(struct hashmap *map, const void *key, const void *data)#
Add a node to the hashmap.
This function takes the key and data for the new node, calculates the hash for it, and then adds it to the correct bucket. If the bucket is currently full, it returns failure, unless RCSW_DS_HASHMAP_LINPROB was passed during initialization, in which case the node goes into the next bucket with space. If the key already exists, failure is returned (no duplicates are allowed).
With linear probing, the duplicate check (and every lookup of an absent key) looks at the home bucket plus hashmap::max_probe buckets after it, so it stays as cheap as without probing until nodes start to spill.
- Parameters:
map – The hashmap handle.
key – The key to add. Must point to hashmap_config::key_len readable bytes.
data – The data to add.
- Returns:
-
status_t hashmap_remove(struct hashmap *map, const void *key)#
Remove a node from a hashmap.
This function searches the hashmap for the specified key. If it is found, it is removed from the appropriate bucket. If it is not found, nothing is changed and ERROR is returned with errno=ENOENT.
- Parameters:
map – The hashmap handle.
key – The key for the data to remove. Must point to hashmap_config::key_len readable bytes.
- Returns:
-
status_t hashmap_map(struct hashmap *map, void (*f)(void *e))#
Apply a function to the data of every element in a hashmap.
Iterates all buckets in insertion order and calls
fon each element’s data. The callback signature matches darray_map() and llist_map().- Parameters:
map – The hashmap handle.
f – Callback applied to each element. May modify element data but must not insert or remove keys.
- Returns:
-
status_t hashmap_inject(struct hashmap *map, void (*f)(void *e, void *result), void *result)#
Compute a cumulative result over all elements in a hashmap.
- Parameters:
map – The hashmap handle.
f – Callback applied to each element. First argument is the element data; second argument is
result.result – Initial result value, updated in place by
f.
- Returns:
-
void hashmap_print(const struct hashmap *map)#
Show stats about a hashmap.
This function shows some basic stastics about the hashmap: total # of collisions, utilization, etc.
- Parameters:
map – The hashmap handle.
-
status_t hashmap_gather(const struct hashmap *map, struct hashmap_stats *stats)#
Gather statistics about current state of hashmap.
Takes O(n_nodes) time without RCSW_DS_HASHMAP_LINPROB. With it, the hashmap_stats::hash_quality computation rescans the nodes once for every 256 buckets (no memory is allocated), so this is meant for diagnostics, not for hot paths.
- Parameters:
map – The hashmap handle.
stats – The statistics to be filled.
- Returns:
-
struct hashmap_config#
- #include <rcsw/ds/hashmap.h>
Hashmap initialization parameters.
Public Members
-
dptr_t *meta#
Pointer to application-allocated space for storing the hashmap buckets. Ignored unless RCSW_NOALLOC_META is passed.
-
dptr_t *elements#
Pointer to application-allocated space for storing data managed by the hashmap. Ignored unless RCSW_NOALLOC_DATA is passed.
-
size_t elt_size#
Size of elements in bytes.
-
uint32_t flags#
Run time configuration flags. Valid flags are:
All other flags are ignored.
-
status_t (*hash)(const void *const key, size_t len, uint32_t *out)#
Hashing function to use. Must be non-NULL.
-
size_t key_len#
Length of every key in bytes, at most RCSW_HASHMAP_KEYSIZE. All hashmap functions read exactly this many bytes from the keys passed to them, and only these bytes are hashed; the hashmap zero-pads the stored copy.
0 means RCSW_HASHMAP_KEYSIZE, so that every key must point to that many readable bytes, with any unused bytes zeroed by the caller.
-
size_t bsize#
Initial size of hash buckets; passed to darray_init() as darray_config::init_size; this is also used as darray_config::max_elts ; that is, fixed size hash buckets.
-
size_t n_buckets#
Number of buckets for hashmap.
-
dptr_t *meta#
-
struct hashmap_stats#
- #include <rcsw/ds/hashmap.h>
Hashmap statistics.
Provides detailed info about how well the hashmap is working.
Public Members
-
size_t n_nodes#
Number of hashnodes in hashmap. Updated on add/remove.
-
size_t n_adds#
Number of adds to hashmap since last reset.
-
size_t n_addfails#
Number of failures to add to hashmap since last reset.
-
size_t n_collisions#
Number of collisions when adding since last reset.
-
double collision_ratio#
Colliding adds / total successful adds.
-
bool sorted#
Is the hashmap sorted?
-
double max_util#
Max bucket utilization.
-
double min_util#
Min bucket utilization.
-
double average_util#
Average bucket utilization.
-
double hash_quality#
How evenly the hash function spreads the current keys over the buckets, relative to an ideal random hash: the expected number of key comparisons for a lookup, divided by what a uniformly random hash would give for the same number of keys and buckets.
About 1.0: as good as random (0.95-1.05 is normal sampling noise).
Above 1.0: keys cluster in some buckets; e.g. 2.0 means lookups do twice the work of a random hash. Try another hash function, or a prime number of buckets if the keys share low-order bit patterns.
Below 1.0: better than random (possible for structured keys).
Uses the bucket each key hashes to (its home bucket), so the result is the same with or without RCSW_DS_HASHMAP_LINPROB. 0 if the hashmap is empty. Collect a representative set of keys before reading it.
-
size_t n_nodes#
-
struct hashmap_space_mgmt#
- #include <rcsw/ds/hashmap.h>
Simple convenience struct for the space for hashmap data.
Element space is chunked into 3 parts (in order):
An allocation map of data blocks (see allocm_map_bytes())
Datablock array (max_elts * elt_size, padded to a multiple of sizeof(dptr_t) so the hashnodes after it stay aligned)
Metadata array of hashnode
Meta space from hashmap_config::meta is used for the darray handles (buckets).
Public Members
-
struct allocm_entry *db_map#
-
struct hashmap#
- #include <rcsw/ds/hashmap.h>
The hashmap data structure (an associative array).
The elements in this data structure are hashnode objects, and the nodes are the dynamic arrays (darray) used to implement the buckets.
Public Members
-
struct hashmap_config cfg#
The configuration the hashmap was initialized with. hashmap_config::key_len is the key length in use (RCSW_HASHMAP_KEYSIZE if 0 was passed). hashmap_config::meta and hashmap_config::elements are as passed (NULL unless caller-provided memory is used); hashmap::space holds the views into them.
-
struct hashmap_space_mgmt space#
Management of all node and element space for the hashmap.
-
size_t max_elts#
Max number of of elements allowed in the hashmap: hashmap_config::bsize x hashmap_config::n_buckets.
-
struct hashmap_stats stats#
Current hashmap statistics
-
size_t max_probe#
Only used with RCSW_DS_HASHMAP_LINPROB. The furthest past its home bucket any node has been placed since init or the last hashmap_clear(). Lookups probe only this many buckets after the home bucket. Never decreases on remove, so it is always an upper bound. Always 0 without linear probing.
-
bool sorted#
Is the hashmap currently sorted?
-
struct hashmap_config cfg#
-
struct hashnode#
- #include <rcsw/ds/hashmap.h>
Nodes within the hashmap (each bucket is filled with these).
As you woulde xpect for an associative array element, this is a key-value pair
Aligned to dptr_t, so that arrays of these in caller-provided memory keep every member naturally aligned. (Not packed: packing would misalign the pointer members.)
rcsw/ds/inttree.h#
Interval tree.
Functions
-
void inttree_init_helper(const struct bstree *tree)#
Initialize the interval tree specific bits of a BST.
- Parameters:
tree – The partially constructed interval tree.
-
static inline struct inttree_node *inttree_root(const struct bstree *const tree)#
Get the root node of an interval tree.
As bstree_root(), typed as a
structinttree_node*.
-
static inline bool inttree_isfull(const struct bstree *const tree)#
Determine if an interval tree is full.
- Parameters:
tree – The interval tree handle.
-
static inline bool inttree_isempty(const struct bstree *const tree)#
Determine if an interval tree is empty.
- Parameters:
tree – The interval tree handle.
-
static inline size_t inttree_size(const struct bstree *const tree)#
Get # elements currently in an interval tree.
- Parameters:
tree – The interval tree handle.
- Returns:
The # of elements, or 0 on error.
-
static inline size_t inttree_element_space(size_t max_elts)#
Calculate the # of bytes that the interval tree will require if RCSW_NOALLOC_DATA is passed to manage a specified # of elements of a specified size.
- Parameters:
max_elts – # of desired elements the tree will hold
- Returns:
The total # of bytes the application would need to allocate
-
static inline size_t inttree_meta_space(size_t max_elts)#
Calculate the space needed for the nodes in the interval tree, given a max # of elements.
Used in conjunction with RCSW_NOALLOC_META.
- Parameters:
max_elts – # of desired elements the tree will hold
- Returns:
The # of bytes required
-
static inline status_t inttree_delete(struct bstree *tree, struct inttree_node *victim, void *elt)#
Delete a node from the tree.
The algorithm from this function is from Introduction_To_Algorithms
- Parameters:
tree – The BST handle
victim – The node to delete
elt – To be filled with the data of the deleted node if non-NULL
- Returns:
-
static inline status_t inttree_remove(struct bstree *tree, const void *key)#
Remove the node in a BST that contains data that matches the given key.
- Parameters:
tree – The BST handle
key – Key to match in the search for the node to delete
- Returns:
status_t. ERROR with errno=ENOENT if no node has
key.
-
status_t inttree_insert(struct bstree *tree, struct interval_data *interval)#
Insert an interval into an interval tree.
- Parameters:
tree – The interval tree handle.
interval – The interval to insert.
- Returns:
-
struct bstree *inttree_init(struct bstree *tree_in, const struct bstree_config *params)#
Initialize an interval tree.
RCSW_DS_BSTREE_INT and RCSW_DS_BSTREE_RB are added to
params->flags,params->elt_sizeis set tosizeof(struct interval_data), andparams->cmpkeyis ignored (intervals are keyed on their low end).paramsitself is not modified.- Parameters:
tree_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed; ignored (may be NULL) otherwise. See Memory Model .
params – Initialization parameters.
- Returns:
The initialized tree, or NULL if an error occurred.
-
struct inttree_node *inttree_overlap_search(const struct bstree *tree, struct inttree_node *root, const struct interval_data *interval)#
Determine if the given interval overlaps any in the interval tree.
To search the entire tree, pass
inttree_root(tree)(see inttree_root()) asroot. (tree->rootis a sentinel, not the root node.)- Parameters:
tree – The interval tree handle
root – Root of tree to start searching at
interval – The interval to test for overlaps with.
- Returns:
The first overlapping interval encountered, or NULL if none was found or an error occurred.
-
struct interval_data#
- #include <rcsw/ds/inttree.h>
A simple representation of an interval for use in an interval tree.
Aligned to dptr_t, so that arrays of these in caller-provided memory keep every member naturally aligned. (Not packed: packing would misalign the pointer members.)
-
struct inttree_node#
- #include <rcsw/ds/inttree.h>
A node in an interval tree.
Note that the first fields are identical to the ones in the bstree_node; this is necessary for the casting to “up” the inheritance tree to work.
Aligned to dptr_t, so that arrays of these in caller-provided memory keep every member naturally aligned. (Not packed: packing would misalign the pointer members.)
Public Members
-
uint8_t key[sizeof(int32_t)]#
-
struct inttree_node *left#
-
struct inttree_node *right#
-
struct inttree_node *parent#
-
bool red#
-
int32_t max_high#
This field is the largest HIGH value of the subtree rooted at this node.
-
uint8_t key[sizeof(int32_t)]#
rcsw/ds/iter.h#
Iterators over data structures.
Enums
Functions
-
struct ds_iterator *ds_iter_init(struct ds_iterator *iter, void *ds, enum ds_iter_type type, const struct ds_ops *ops, bool (*classify)(void *e))#
Initialize an iterator.
For implementing a DS’s *_iter_init() function: this does not set the cursor, which the caller must do. Applications should call the DS’s own function (e.g., llist_iter_init()) instead.
The caller is responsible for the storage of
iter(stack or heap). No allocation is performed by this function.- Parameters:
iter – The iterator to initialize. Must be non-NULL.
ds – The data structure to iterate over. Must be non-NULL.
type – Direction of iteration.
ops – Vtable of traversal operations for this data structure type. Must be non-NULL. Each DS exposes its own
ds_opsinstance; see the individual DS headers (e.g. llist_iter_ops, rbuffer_iter_ops). For darrays, use darray_iter_init().classify – Optional filter predicate. Pass NULL for unfiltered iteration.
- Returns:
iteron success, or NULL ifops->previs NULL but ITER_BACKWARD was requested.
-
void *ds_iter_next(struct ds_iterator *iter)#
Return the next element satisfying the iteration conditions.
Calls ds_ops::next or ds_ops::prev depending on the direction stored in
iter. If aclassifypredicate was set, elements that do not pass are skipped and the next qualifying element is returned instead.- Parameters:
iter – The iterator.
- Returns:
Pointer to the element data, or NULL when the sequence is exhausted.
-
struct ds_ops#
- #include <rcsw/ds/iter.h>
Vtable of traversal operations for a data structure.
Each iterable data structure defines a static instance of this struct and points ds_iterator::ops at it during ds_iter_init(). Adding a new iterable data structure requires no changes to iter.c — only a new static ds_ops instance in the new DS’s own source file.
Note
prevmay be NULL for data structures that only support forward iteration (e.g. a singly-linked list or a FIFO).Public Members
-
void *(*next)(struct ds_iterator *iter)#
Advance the iterator forward and return the current element’s data.
- Return:
Pointer to element data, or NULL when the sequence is exhausted.
-
void *(*prev)(struct ds_iterator *iter)#
Advance the iterator backward and return the current element’s data.
May be NULL if the data structure does not support backward iteration. If NULL and ITER_BACKWARD is requested, ds_iter_init() will return NULL.
-
void *(*next)(struct ds_iterator *iter)#
-
struct ds_iterator#
- #include <rcsw/ds/iter.h>
A position-independent iterator over a data structure.
The iterator is a value type: the caller allocates it (on the stack or heap) and initializes it with ds_iter_init(). Multiple independent iterators over the same container can exist simultaneously because no state is stored inside the container itself.
Typical usage:
Initialize it with the data structure’s own function, which sets the cursor (ds_iter_init() alone does not):
struct ds_iterator it; llist_iter_init(&it, my_list, ITER_FORWARD, NULL); // NULL: no filter void* e; while ((e = ds_iter_next(&it)) != NULL) { process(e); }
For a filtered iteration pass a classify callback:
llist_iter_init(&it, my_list, ITER_FORWARD, my_pred);
Public Members
-
const struct ds_ops *ops#
Vtable set by ds_iter_init(); do not modify directly.
-
void *container#
Opaque pointer to the container being iterated.
-
void *node#
-
size_t idx#
-
union ds_iterator cursor#
DS-specific cursor:
idxfor indexed structures (darray, rbuffer),nodefor pointer-chased ones (llist). Set by the DS’s *_iter_init() function and then managed entirely by the ops callbacks.
-
enum ds_iter_type type#
Direction of iteration; read by the ops callbacks.
-
bool (*classify)(void *e)#
Optional filter. If non-NULL, ds_iter_next() only returns elements for which this function returns true. Elements that do not pass are skipped transparently.
-
const struct ds_ops *ops#
rcsw/ds/llist.h#
Doubly linked list.
Defines
-
LLIST_FOREACH(LIST, DIR, VAR)#
Iterate over a llist.
To go forward, pass ‘next’ as the
DIRfield; to iterate through the list backward, pass ‘prev’ in theDIRfield.VARis scoped to the loop, so the macro can be used more than once in the same block. Do not remove or relink the current node inside the loop. You cannot call this macro on a NULL/unitialized list.- Parameters:
LIST – The linked list
DIR – The name of the field used for traversal (next or prev), which sets the direction of traversal.
VAR – The name of the llist_node* local variable to each node will be assigned to when iterating over the list.
-
LLIST_ITER(LIST, START, DIR, VAR)#
Same as LLIST_FOREACH(). but the
STARTparameter allows you to start at an arbitrary location in the list. Pass list->first as theSTARTparameter to make it the same as LLIST_FOREACH().VARis scoped to the loop, so the macro can be used more than once in the same block. Do not remove or relink the current node inside the loop. You cannot call this macro on a NULL/unitialized list.- Parameters:
LIST – The llist.
START – The starting locating with the linked list (must point to a node in the list).
DIR – The name of the field used for traversal (next or prev) which sets the direction of traversal.
VAR – The name of the local variable you want to use when iterating over the list.
Functions
-
static inline bool llist_isfull(const struct llist *const list)#
Determine if the llist is currently full.
- Parameters:
list – The linked list handle.
-
static inline bool llist_isempty(const struct llist *const list)#
Determine if the llist is currently empty.
- Parameters:
list – The linked list handle.
-
static inline size_t llist_size(const struct llist *const list)#
Determine # elements currently in the llist.
- Parameters:
list – The linked list handle.
- Returns:
# elements in linked list, or 0 on ERROR.
-
static inline size_t llist_element_space(size_t max_elts, size_t elt_size)#
Calculate the # of bytes that the llist will require if RCSW_NOALLOC_DATA is passed to manage a specified # of elements of a specified size.
- Parameters:
max_elts – # of desired elements the linked list will hold.
elt_size – size of elements in bytes.
- Returns:
The total # of bytes the application would need to allocate.
-
static inline size_t llist_meta_space(size_t max_elts)#
Calculate the space needed for the nodes in the llist, given a max # of elements.
Used in conjunction with RCSW_NOALLOC_META.
- Parameters:
max_elts – # of desired elements the linked list will hold.
- Returns:
The # of bytes required.
-
struct llist *llist_init(struct llist *list_in, const struct llist_config *params)#
Initialize a llist.
- Parameters:
list_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed; ignored (may be NULL) otherwise. See Memory Model .
params – The initialization parameters.
- Returns:
The initialized list, or NULL if an error occurred.
-
void llist_destroy(struct llist *list)#
Destroy a llist.
The entire list is iterated through once. Any further use of the pointer to this llist is undefined. Do not call it twice on the same list.
- Parameters:
list – The list to destroy.
-
status_t llist_clear(struct llist *list)#
Clear a llist.
This routine clears an llist. Every node with allocated memory for its data field (non-NULL) will have that memory freed if it is in the DS domain, along with the memory for the node.
- Parameters:
list – The linked list handle.
- Returns:
-
status_t llist_remove(struct llist *list, const void *e)#
Remove an item from a llist.
Memory for the node and its data is deallocated.
- Parameters:
list – The linked list handle.
e – The element to remove, matched with the list’s
cmpefunction.
- Returns:
-
status_t llist_delete(struct llist *list, struct llist_node *victim, void *e)#
Delete a node from a llist.
- Parameters:
list – The linked list handle.
victim – the linked list node to delete from the list.
e – To be filled with the data from the victim node if non-NULL.
- Returns:
-
status_t llist_append(struct llist *list, void *data)#
Append an item to a llist.
- Parameters:
list – The linked list handle.
data – The data to insert into the list.
- Returns:
-
status_t llist_prepend(struct llist *list, void *data)#
Prepend an item to the llist.
This routine prepends an item to the start of the llist. Can be used as a “push” function.
- Parameters:
list – The linked list handle.
data – The data to insert into the list.
- Returns:
-
void llist_print(struct llist *list)#
llist_print() - Print the llist
- Parameters:
list – The linked list handle.
-
void *llist_data_query(struct llist *list, const void *e)#
Search a llist for specific data.
This routine searches the linked list for a llist_node whose data matches that of the provided argument according to the list->cmpe function.
- Parameters:
list – The linked list handle.
e – The data to search for.
- Returns:
The matching data, or NULL if an error occurred or no match was found.
-
struct llist_node *llist_node_query(struct llist *list, const void *e)#
Search a llist for specific data.
This routine searches the linked list for a llist_node whose data matches that of the provided argument according to the list->cmpe function.
- Parameters:
list – The linked list handle
e – The data to search for
- Returns:
The node for which the data matched, or NULL if an error occurred or no match was found.
-
status_t llist_sort(struct llist *list, enum exec_type type)#
Sort a llist.
Sorts a linked list with a stable mergesort, O(n log n) time and O(1) extra space. Both exec_type values give the same result: EXEC_REC merges bottom-up over the whole list; EXEC_ITER splits the list in half first and merges the sorted halves. Neither recurses.
-
struct llist *llist_copy(struct llist *list, uint32_t flags, void *elements, void *nodes)#
Create a copy of a llist.
flags,elements, andnodesdetermine how memory is managed for the new list.- Parameters:
list – The linked list handle.
flags – Initialization flags for the new list.
elements – Space for elements in the new list. Must be non-NULL if RCSW_NOALLOC_DATA is passed in
flags; can be NULL otherwise.nodes – Space for nodes in the new list. Must be non-NULL if RCSW_NOALLOC_META is passed in
flags; can be NULL otherwise.
- Returns:
The new list, or NULL if an error occurred..
-
struct llist *llist_copy_if(struct llist *list, bool (*pred)(const void *e), uint32_t flags, void *elements, void *nodes)#
Create a copy of part of a llist (conditional copy).
This routine iterates through the list and finds all the items that satisfy the predicate, and duplicates them, creating a new list contain all the nodes in the orginal list that satisfied the predicate. If no elements are found that fulfill the predicate, an empty list is returned.
- Parameters:
list – The linked list handle.
pred – The predicate for determining element membership in the new list
flags – Initialization flags for the new list.
elements – Space for elements in the new list. Must be non-NULL if RCSW_NOALLOC_DATA is passed in
flags; can be NULL otherwise.nodes – Space for nodes in the new list. Must be non-NULL if RCSW_NOALLOC_META is passed in
flags; can be NULL otherwise.
- Returns:
The new list, or NULL if an error occurred.
-
struct llist *llist_filter(struct llist *list, bool (*pred)(const void *const e), uint32_t flags, void *elements, void *nodes)#
Filter out elements from one llist into another.
This routine iterates through the llist and finds all the items that satisfy the predicate, and moves them into a new list (they are removed from the original list). If no elements are found that fulfill the predicate, an empty list is returned.
If
flagscontains RCSW_DS_LLIST_DB_DISOWN or RCSW_DS_LLIST_DB_PTR,listmust have one of them too: otherwise the new list would point at datablockslistfrees as the elements are removed, so NULL is returned with errno=EINVAL.- Parameters:
list – The linked list handle
flags – Initialization flags for the new list.
elements – Space for elements in the new list. Must be non-NULL if RCSW_NOALLOC_DATA is passed in
flags; can be NULL otherwise.nodes – Space for nodes in the new list. Must be non-NULL if RCSW_NOALLOC_META is passed in
flags; can be NULL otherwise.pred – The predicate for determining element membership in the new list
- Returns:
The new list, or NULL if an error occurred.
-
status_t llist_remove_if(struct llist *list, bool (*pred)(const void *e))#
Remove and deallocate all elements satisfying a predicate.
Iterates the list and removes every element for which
predreturns true. Memory for both the matching llist_node objects and the data they contain are deallocated. If no elements satisfy the predicate, the list is unchanged.Note
If RCSW_DS_LLIST_DB_DISOWN is set, the datablocks will not be freed — see its documentation for the side-effects.
- Parameters:
list – The linked list handle.
pred – Predicate; elements for which this returns true are removed.
- Returns:
-
status_t llist_splice(struct llist *list1, struct llist *list2, struct llist_node *node)#
Splice two llist objects together.
Moves every element of list2 into list1, immediately before
node; pass NULL to append. To prepend, pass list1->first. Either list may be empty. On success list2’s handle is released (unless it was caller-provided), and any further use of list2 is undefined; on failure neither list is changed.Both lists must use heap-allocated nodes and datablocks (neither RCSW_NOALLOC_META nor RCSW_NOALLOC_DATA), have the same element size, and agree on RCSW_DS_LLIST_DB_DISOWN and RCSW_DS_LLIST_DB_PTR (list1 takes over freeing list2’s datablocks, or not freeing them). If list1 has RCSW_DS_SORTED, it is re-sorted afterwards.
- Parameters:
list1 – The linked list handle for the splicer.
list2 – The linked list handle for the splicee.
node – The node in list1 to insert list2 before, or NULL to append.
- Returns:
status_t. ERROR with errno=ENOSPC if list1’s max_elts would be exceeded, ENOENT if
nodeis not in list1, EINVAL if the lists are not compatible.
-
status_t llist_map(struct llist *list, void (*f)(void *e))#
Apply a function to all elements in the llist.
- Parameters:
list – The linked list handle.
f – The function to apply, which CAN modify elements.
- Returns:
-
status_t llist_inject(struct llist *list, void (*f)(void *e, void *res), void *result)#
Compute a cumulative result (sum, count, …) over all elements in the llist.
- Parameters:
list – The linked list handle.
f – The mapping function, which CAN modify elements.
result – The initial result, which is passed to the callback along with each element in the linked list.
- Returns:
-
struct ds_iterator *llist_iter_init(struct ds_iterator *iter, struct llist *list, enum ds_iter_type type, bool (*classify)(void *e))#
Initialize an iterator over a llist.
- Parameters:
iter – Caller-allocated iterator storage.
list – The list to iterate over.
type – ITER_FORWARD or ITER_BACKWARD.
classify – Optional filter predicate; pass NULL for no filtering.
- Returns:
iteron success, or NULL on error.
Variables
-
struct llist_config#
- #include <rcsw/ds/llist.h>
Parameters for llist.
Public Members
-
int (*cmpe)(const void *const e1, const void *const e2)#
For comparing elements. If NULL, then llist querying, sorting, etc. are disabled.
-
void (*printe)(const void *e)#
For printing an element. Can be NULL. If NULL, llist_print() cannot be called.
-
dptr_t *meta#
Pointer to application-allocated space for storing the nodes managed by the llist. Ignored unless RCSW_NOALLOC_META is passed.
-
dptr_t *elements#
Pointer to application-allocated space for storing the datablocks managed by the llist. Ignored unless RCSW_NOALLOC_DATA is passed.
-
size_t elt_size#
Size of elements in bytes.
-
int max_elts#
Maximum Number of elements allowed. -1 = no upper limit.
-
uint32_t flags#
Configuration flags. Valid flags are:
All other flags are ignored.
-
int (*cmpe)(const void *const e1, const void *const e2)#
-
struct llist_node#
- #include <rcsw/ds/llist.h>
Linked list node for llist.
Aligned to dptr_t, so that arrays of these in caller-provided memory keep every member naturally aligned. (Not packed: packing would misalign the pointer members.)
Public Members
-
struct llist_node *next#
Next node in the list.
-
struct llist_node *prev#
Previous node in the list.
-
struct llist_node *next#
-
struct llist_space_mgmt#
- #include <rcsw/ds/llist.h>
Container for all memory (space) used by a llist.
Public Members
-
dptr_t *datablocks#
Space for the data elements. Used if RCSW_NOALLOC_DATA passed in llist_config::flags.
-
struct allocm_entry *db_map#
Space for the allocation map for datablocks. Used if RCSW_NOALLOC_DATA passed in llist_config::flags.
-
struct llist_node *nodes#
Space for llist_node objects. Used if RCSW_NOALLOC_META passed in llist_config::flags.
-
struct allocm_entry *node_map#
Space for the allocation map for llist_node objects. Used if RCSW_NOALLOC_META passed in llist_config::flags.
-
dptr_t *datablocks#
-
struct llist#
- #include <rcsw/ds/llist.h>
Linked list data structure.
Public Members
-
struct llist_config cfg#
The configuration the list was initialized with. llist_config::meta and llist_config::elements are as passed (NULL unless caller-provided memory is used); llist::space holds the views into them.
-
struct llist_space_mgmt space#
Views into caller-provided memory.
-
bool sorted#
If true, list is currently sorted.
-
struct llist_node *first#
First node (for easy prepending).
-
struct llist_node *last#
Last node (for easy appending).
-
struct llist_config cfg#
rcsw/ds/matrix.h#
Fixed-size matrix.
Functions
-
static inline void *matrix_access(const struct matrix *const matrix, size_t u, size_t v)#
Access an element within a static matrix.
- Parameters:
matrix – The matrix handle.
u – The row within the matrix.
v – The column within the matrix.
- Returns:
Reference to element, or NULL if an error occurred.
-
static inline size_t matrix_element_space(size_t n_rows, size_t n_cols, size_t elt_size)#
Calculate the # of bytes required for the static matrix.
- Parameters:
n_rows – Initial # rows.
n_cols – Initial # columns.
elt_size – Size of the elements in bytes.
- Returns:
The # of bytes required.
-
static inline status_t matrix_elt_clear(struct matrix *const matrix, size_t u, size_t v)#
Clear an element within the static matrix.
- Parameters:
matrix – The matrix handle.
u – Row of element to clear.
v – Column of element to clear.
- Returns:
-
static inline status_t matrix_set(struct matrix *const matrix, size_t u, size_t v, const void *const w)#
Set an element in the static matrix to a specific value.
- Parameters:
matrix – The matrix handle.
u – Element row index.
v – Element column index.
w – New element value.
- Returns:
-
static inline bool matrix_issquare(const struct matrix *const matrix)#
Return if the matrix is square or not.
-
struct matrix *matrix_init(struct matrix *matrix_in, const struct matrix_config *params)#
Initialize a static matrix.
- Parameters:
matrix_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed; ignored (may be NULL) otherwise. See Memory Model .
params – The initialization parameters.
- Returns:
The initialized matrix, or NULL if an error occurred.
-
void matrix_destroy(struct matrix *matrix)#
Destroy a static matrix.
Any further use of the handle is undefined after this function is called.
- Parameters:
matrix – The matrix handle.
-
status_t matrix_transpose(struct matrix *matrix)#
Transpose a static matrix in place.
Note
Square matrices only. Transposing a non-square matrix in place would also have to swap matrix_config::n_rows and matrix_config::n_cols and permute the storage by cycles, which is not implemented. A non-square matrix fails the function precondition (ERROR under
LIBRA_FPC_RETURN). To transpose an M x N matrix, copy it element by element into an N x M one.- Parameters:
matrix – The matrix handle.
- Returns:
-
struct matrix_config#
- #include <rcsw/ds/matrix.h>
Static matrix initialization parameters.
Public Members
-
void (*printe)(const void *e)#
For printing an element. Can be NULL. If NULL, matrix_print() is disabled.
-
dptr_t *elements#
Pointer to application-allocated space for storing the data managed by the matrix. Ignored unless RCSW_NOALLOC_DATA is passed.
-
size_t elt_size#
Size of elements in bytes.
-
uint32_t flags#
Run-time configuration flags. Valid flags are:
All other flags ignored.
-
size_t n_rows#
Number of rows in matrix.
-
size_t n_cols#
Number of columns in matrix.
-
void (*printe)(const void *e)#
-
struct matrix#
- #include <rcsw/ds/matrix.h>
Representation of a fixed-size (static) matrix using a single contiguous array and indexing said array in 2 dimensions.
Static in the sense that the matrix dimensions cannot be changed after initialization. Assumes row-major order (this is C after all).
Should only be used for applications where the matrix is dense, or when the dimensions of the matrix are small (if the dimensions are large AND the matrix is sparse, it will definitely be really inefficient, and possibly won’t even fit into memory).
Note
matrix_transpose() supports square matrices only.
Public Members
-
struct matrix_config cfg#
The configuration the matrix was initialized with. matrix_config::elements is as passed (NULL if the library allocated the storage); use matrix::elements for the storage in use.
-
struct matrix_config cfg#
rcsw/ds/multififo.h#
FIFO whose elements are consumed in pieces through child FIFOs.
Functions
-
static inline bool multififo_isfull(const struct multififo *const fifo)#
Determine if the multi-FIFO is currently full.
Note
This works with the root FIFO only—to check if a child shadow FIFO is full, use fifo_isfull() with an appropriate fifo reference.
- Parameters:
fifo – The multi-FIFO handle.
-
static inline bool multififo_isempty(const struct multififo *const fifo)#
Determine if the multi-FIFO is currently empty.
Note
This works with the root FIFO only—to check if a child shadow FIFO is empty, use fifo_isempty() with an appropriate fifo reference.
- Parameters:
fifo – The multi-FIFO handle.
-
static inline size_t multififo_size(const struct multififo *const fifo)#
Determine # elements currently in the multi-FIFO.
Note
This works with the root FIFO only—to get the # elements in a child shadow FIFO, use fifo_size() with an appropriate fifo reference.
- Parameters:
fifo – The multi-FIFO handle.
- Returns:
# elements in the multi-FIFO, or 0 on ERROR.
-
static inline bool multififo_islocked(const struct multififo *const fifo)#
Determine if the multi-FIFO is busy in multififo_add() or multififo_remove(). Child FIFO consumers must not dequeue while it is.
- Parameters:
fifo – The multi-FIFO handle.
-
static inline size_t multififo_capacity(const struct multififo *const fifo)#
Get the multi-FIFO capacity.
Note
This works with the root FIFO only—to get capacity of a child shadow FIFO, use fifo_capacity() with an appropriate fifo reference.
- Parameters:
fifo – The multi-FIFO handle.
- Returns:
Capacity of the multi-FIFO, or 0 on ERROR.
-
static inline size_t multififo_element_space(size_t max_elts, size_t elt_size)#
Calculate the # of bytes that the multi-FIFO will require if RCSW_NOALLOC_DATA is passed to manage a specified # of elements of a specified size.
- Parameters:
max_elts – # of desired elements the multi-FIFO will hold.
elt_size – size of elements in the multi-FIFO in bytes.
- Returns:
The total # of bytes the application would need to allocate
-
static inline size_t multififo_meta_space(size_t elt_size, size_t n_children)#
Calculate the # of bytes needed for all child shadow FIFOs to point into elements in multififo::root.
- Parameters:
elt_size – Size of root FIFO elements in bytes.
n_children – # of shadow child FIFOs.
- Returns:
The total # of bytes the application would need to allocate.
-
struct multififo *multififo_init(struct multififo *fifo_in, const struct multififo_config *params)#
Initialize a multi-FIFO.
- Parameters:
fifo_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed; ignored (may be NULL) otherwise. See Memory Model .
params – The initialization parameters.
- Returns:
The initialized multi-FIFO, or NULL if an error occurred.
-
void multififo_destroy(struct multififo *fifo)#
Destroy a multi-FIFO.
Any further use of the multi-FIFO after this function is called is undefined.
- Parameters:
fifo – The multi-FIFO to destroy.
-
status_t multififo_add(struct multififo *fifo, const void *e)#
Enqueue an element into the multi-FIFO.
Copy the element into an available slot in the root FIFO.
If the root FIFO’s front element has not been fed to the child FIFOs yet (i.e., the root FIFO was empty, so the new element is the front), copy it into each child FIFO, split into child-sized pieces. Otherwise the children are not touched: the next element is fed to them by multififo_remove().
- Parameters:
fifo – The multi-FIFO handle.
e – The element to enqueue. Cannot be NULL.
- Returns:
status_t. ERROR with errno=EAGAIN if the multi-FIFO is busy (see multififo_islocked()).
-
static inline void *multififo_front(const struct multififo *const fifo)#
Get the first multi-FIFO item without removing it.
- Parameters:
fifo – The multi-FIFO handle.
- Returns:
Pointer to the first element, or NULL if no such element or an error occurred.
-
status_t multififo_remove(struct multififo *fifo, void *e)#
Dequeue an element from the multi-FIFO.
If every child FIFO has been drained of the root FIFO’s front element, the element is dequeued into
e(if non-NULL). Otherwise, no effect. If a remove is performed and the root FIFO is not empty afterwards, the new front element is copied into the child FIFOs.- Parameters:
fifo – The multi-FIFO handle.
e – The element to dequeue into from the multi-FIFO. Can be NULL.
- Returns:
status_t. Note that it is an ERROR to try to remove an element from the root FIFO before all children have finished processing it. ERROR with errno=EAGAIN if the multi-FIFO is busy (see multififo_islocked()).
-
struct multififo_config#
- #include <rcsw/ds/multififo.h>
Parameters for multififo.
Public Members
-
dptr_t *elements#
Pointer to application-allocated space for storing data managed by the multififo. Ignored unless RCSW_NOALLOC_DATA is passed.
-
dptr_t *meta#
Pointer to application-allocated space for storing child shadow FIFOs. Ignored unless RCSW_NOALLOC_META is passed.
-
size_t elt_size#
Size of the “base” elements (i.e., the elements in the main FIFO) in bytes.
-
size_t max_elts#
Maximum number of elements allowed.
-
size_t n_children#
The # of child shadow FIFOs: 1 to 8, since multififo::front_refmask has one bit per child.
-
size_t *children#
Configuration for child shadow FIFOs. Currently only the element size is needed; if this changes, either fifo_config or another parameter struct will be used instead.
-
uint32_t flags#
Configuration flags. See multififo::flags for valid flags.
-
dptr_t *elements#
-
struct multififo_children_mgmt#
- #include <rcsw/ds/multififo.h>
The child FIFOs of a multififo and their storage.
Public Members
-
struct fifo *fifos#
Child shadow FIFOs, each holding a copy of the root FIFO’s front element split into child-sized pieces. Implicitly uses RCSW_NOALLOC_DATA, RCSW_NOALLOC_HANDLE.
-
struct fifo *fifos#
-
struct multififo#
- #include <rcsw/ds/multififo.h>
A FIFO which itself contains multiple child shadow FIFOs.
Useful when you want to put large packets of data into a FIFO, but have consumers pull them out in much smaller chunks, such as when you have a process which produces large packets of data which you want to send over UART without disrupting/preempting the main process. This can be easily done with this data structure and a say 1ms “tick” ISR which pulls data out of a child FIFO as it becomes available.
Elements are stored in the “root” FIFO. When an element becomes the front of the root FIFO, it is copied into the child FIFOs, split into pieces of each child’s element size. It stays at the front until every child has been drained and multififo_remove() is called.
NOT thread safe in general. multififo_add() and multififo_remove() hold an internal busy flag (taken with an atomic exchange) for their duration, so that an asynchronous consumer (e.g., an ISR draining a child FIFO) can check multififo_islocked() and back off while the children are being updated. If either function finds the flag already held, it fails with
EAGAINwithout touching the multi-FIFO. All other functions must be called synchronously.Public Members
-
uint8_t front_refmask#
Bitmask indicating which child FIFOs have finished processing the current front element in multififo::root, and which haven’t. Child FIFO
isets bit1 << i, so there can be at most 8 children.
-
bool front_fed#
Whether the current front element of multififo::root has been copied into the child FIFOs. Each front element is fed to the children exactly once; multififo::front_refmask alone can’t tell “not fed yet” from “fed and fully consumed”.
-
bool locked#
Atomic busy flag held by multififo_add() and multififo_remove(); read it with multififo_islocked(). Consumers of child FIFOs must not dequeue while it is set.
-
struct multififo_children_mgmt children#
Management of all root and child datablocks and metadata for the multi-FIFO.
-
uint32_t flags#
Run-time configuration flags. Valid flags are:
All other flags are ignored.
-
uint8_t front_refmask#
rcsw/ds/ostree.h#
Order statistics tree.
Functions
-
static inline struct ostree_node *ostree_root(const struct bstree *const tree)#
Get the root node of an order-statistic tree.
As bstree_root(), typed as a
structostree_node*.
-
void ostree_init_helper(struct bstree *tree)#
Initialize the order-statistic tree specific bits of a BST.
- Parameters:
tree – The ostree handle.
-
static inline size_t ostree_element_space(size_t max_elts, size_t elt_size)#
Calculate the # of bytes that the BST will require if RCSW_NOALLOC_DATA is passed to manage a specified # of elements of a specified size.
The +2 is for the root and nil nodes.
- Parameters:
max_elts – # of desired elements the BST will hold
elt_size – size of elements in bytes
- Returns:
The total # of bytes the application would need to allocate
-
static inline size_t ostree_meta_space(size_t max_elts)#
Calculate the space needed for the nodes in an order-statistic tree.
Used in conjunction with RCSW_NOALLOC_META. The +2 is for the root and nil nodes.
- Parameters:
max_elts – Max # of elements the tree will hold.
- Returns:
The # of bytes required.
-
static inline status_t ostree_delete(struct bstree *tree, struct ostree_node *victim, void *elt)#
Delete a node from the tree.
The algorithm from this function is from Introduction_To_Algorithms
- Parameters:
tree – The BST handle
victim – The node to delete
elt – To be filled with the data of the deleted node if non-NULL
- Returns:
-
static inline status_t ostree_remove(struct bstree *tree, const void *key)#
Remove the node in a BST that contains data that matches the given key.
- Parameters:
tree – The BST handle
key – Key to match in the search for the node to delete
- Returns:
status_t. ERROR with errno=ENOENT if no node has
key.
-
static inline void ostree_destroy(struct bstree *tree)#
Destroy a binary search tree.
Any further use of the tree after calling this function is undefined.
- Parameters:
tree – The BST to destroy
-
static inline struct ostree_node *ostree_node_query(const struct bstree *const tree, struct ostree_node *search_root, const void *const key)#
Query a BST for a specific node, starting the search at the specified search root.
- Parameters:
tree – The BST handle
search_root – The root of the search (not necessarily the root of the tree)
key – The key to match
- Returns:
The node with the matching key, or NULL if not found
-
struct ostree_node *ostree_select(const struct bstree *tree, struct ostree_node *node_in, int i)#
Select the ith smallest element in the order-statistic tree.
- Parameters:
tree – The ostree handle.
node_in – The node to start searching at (usually
ostree_root(tree)).i – The element rank to select.
- Returns:
The ith smallest element, or NULL if no such element or an error occurred.
-
int ostree_rank(const struct bstree *tree, const struct ostree_node *node)#
Get the rank of an element within an order-statistic tree.
- Parameters:
tree – The OStree handle.
node – The node to get the rank of.
- Returns:
The rank, or -1 on ERROR.
-
struct bstree *ostree_init(struct bstree *tree_in, const struct bstree_config *params)#
Initialize an order statistics tree.
RCSW_DS_BSTREE_OS and RCSW_DS_BSTREE_RB are added to
params->flags;paramsitself is not modified.- Parameters:
tree_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed; ignored (may be NULL) otherwise. See Memory Model .
params – Initialization parameters.
- Returns:
The initialized tree, or NULL if an error occurred.
-
struct ostree_node#
- #include <rcsw/ds/ostree.h>
A node in an order-statistic tree, derived from a bstree_node (share common fields).
Aligned to dptr_t, so that arrays of these in caller-provided memory keep every member naturally aligned. (Not packed: packing would misalign the pointer members.)
Note
With later GCC versions, if you don’t have the casting right for functions which are shared between bstree and ostree, things won’t work because of differing alignments/packing under optimizations.
Public Members
-
uint8_t key[sizeof(int32_t)]#
-
struct ostree_node *left#
-
struct ostree_node *right#
-
struct ostree_node *parent#
-
bool red#
-
int32_t count#
Size of subtree anchored at node (including node)
-
uint8_t key[sizeof(int32_t)]#
rcsw/ds/rawfifo.h#
Lock-free single-producer, single-consumer FIFO for 1, 2, or 4-byte elements.
Functions
-
static inline status_t rawfifo_clear(struct rawfifo *const fifo)#
Empty the FIFO by discarding all elements currently in it (doesn’t deallocate anything).
This is a consumer-side operation.
- Parameters:
fifo – The FIFO handle.
- Returns:
-
static inline size_t rawfifo_size(const struct rawfifo *const fifo)#
Get # elements currently in FIFO.
- Parameters:
fifo – The FIFO handle.
- Returns:
# elements in the FIFO; 0 on ERROR.
-
static inline size_t rawfifo_n_free(const struct rawfifo *const fifo)#
Get # of free slots remaining in FIFO.
- Parameters:
fifo – The FIFO handle.
- Returns:
# free elements; 0 on ERROR.
-
status_t rawfifo_init(struct rawfifo *fifo, void *buf, size_t max_elts, size_t elt_size)#
Initialize a raw FIFO.
Note
The FIFO holds one less than
max_eltselements.- Parameters:
fifo – The FIFO handle, to be filled.
buf – Space for the elements:
max_elts*elt_sizebytes, aligned toelt_size. Always caller-provided.max_elts – # of slots in
buf.elt_size – Size of elements in bytes: 1, 2, or 4.
- Returns:
-
size_t rawfifo_deq(struct rawfifo *fifo, void *e, size_t n_elts)#
Remove up to
n_eltselements from the front of the FIFO.Consumer side.
- Parameters:
fifo – The FIFO handle.
e – The array to dequeue elements into.
n_elts – # elements to remove.
- Returns:
# of elements removed, which is less than
n_eltsif the FIFO held fewer.
-
struct rawfifo#
- #include <rcsw/ds/rawfifo.h>
A raw FIFO that is fast, and has a limited API.
Elements must be 1, 2 or 4 bytes. The FIFO is lock-free and safe for exactly one producer and one consumer running concurrently (e.g., an ISR and the main loop, or two threads):
The producer calls rawfifo_enq().
The consumer calls rawfifo_deq() and rawfifo_clear().
Either side may call rawfifo_size() and rawfifo_n_free(); the result is a snapshot which is conservative for the caller (the producer never sees fewer free slots than really exist, the consumer never sees more elements than really exist).
Multiple producers or multiple consumers require external locking. For general (read: non-ISR) FIFO things, fifo should be used instead.
rcsw/ds/rbtree.h#
Red-black rebalancing for bstree.
Functions
-
void rbtree_delete_fixup(struct bstree *tree, struct bstree_node *node)#
Peform rotations and change colors to restore red-black properties after a node is deleted.
The algorithm is from Introduction_To_Algorithms
- Parameters:
tree – The rbtree handle.
node – The parent (or successor) of the node that was deleted.
-
void rbtree_insert_fixup(struct bstree *tree, struct bstree_node *node)#
Fix up tree structure after an insertion.
- Parameters:
tree – The rbtree handle.
node – The parent the node that was inserted.
-
int rbtree_node_black_height(const struct bstree_node *node)#
Get the black height of a node in an RB Tree.
- Parameters:
node – The root of the tree to get the height of.
- Returns:
The height or 0 if the node is NULL.
rcsw/ds/rbuffer.h#
Ringbuffer.
Functions
-
static inline bool rbuffer_isfull(const struct rbuffer *const rb)#
Determine if the ringbuffer is currently full.
Note
If RCSW_DS_RBUFFER_AS_FIFO is not passed (i.e., regular ringbuffers), the concept of “full” doesn’t really make sense.
- Parameters:
rb – The ringbuffer handle.
-
static inline bool rbuffer_isempty(const struct rbuffer *const rb)#
Determine if the ringbuffer is currently empty.
- Parameters:
rb – The ringbuffer handle.
-
static inline size_t rbuffer_size(const struct rbuffer *const rb)#
Determine # elements currently in the ringbuffer.
- Parameters:
rb – The ringbuffer handle.
- Returns:
# elements in ringbuffer, or 0 on ERROR.
-
static inline size_t rbuffer_capacity(const struct rbuffer *const rb)#
Get the capacity of the ringbuffer.
- Parameters:
rb – The ringbuffer handle.
- Returns:
The capacity of the ringbuffer, or 0 on ERROR.
-
static inline size_t rbuffer_element_space(size_t max_elts, size_t elt_size)#
Calculate the # of bytes that the ringbuffer will require if RCSW_NOALLOC_DATA is passed to manage a specified # of elements of a specified size.
- Parameters:
max_elts – # of desired elements the ringbuffer will hold.
elt_size – size of elements in bytes.
- Returns:
The total # of bytes the application would need to allocate.
-
struct rbuffer *rbuffer_init(struct rbuffer *rb_in, const struct rbuffer_config *params)#
Initialize a ringbuffer.
- Parameters:
rb_in – Caller storage for the handle, used only if RCSW_NOALLOC_HANDLE is passed in rbuffer_config::flags. It must then be at least
sizeof(struct rbuffer)bytes; with RCSW_ZALLOC that many bytes are zeroed. Ignored (may be NULL) otherwise. See Memory Model .params – The initialization parameters.
- Returns:
The initialized ringbuffer, or NULL if an error occurred.
-
void rbuffer_destroy(struct rbuffer *rb)#
Destroy a ringbuffer.
Any further reference to the ringbuffer after calling this function is undefined.
- Parameters:
rb – The ringbuffer handle.
-
status_t rbuffer_add(struct rbuffer *rb, const void *e)#
Add an item into the ringbuffer.
If the ringbuffer is full, the oldest element is overwritten, unless it was created with RCSW_DS_RBUFFER_AS_FIFO; then the add fails with
errnoset toENOSPC.- Parameters:
rb – The ringbuffer handle.
e – The element to add.
- Returns:
-
status_t rbuffer_remove(struct rbuffer *rb, void *e)#
Remove the next item from the ringbuffer.
The head/tail indexes are modified when the element is removed.
- Parameters:
rb – The ringbuffer handle.
e – To be filled with the removed element, if non-NULL.
- Returns:
-
void *rbuffer_data_get(const struct rbuffer *rb, size_t idx)#
Get the element in the ringbuffer at the specified index.
The ringbuffer is not modified.
- Parameters:
rb – The ringbuffer handle.
idx – Logical index: 0 is the front (oldest) element. Must be less than rbuffer_size().
- Returns:
The element, or NULL if
idxis out of range or another error occurred.
-
int rbuffer_index_query(struct rbuffer *rb, const void *e)#
Get the index of an element in the ringbuffer.
If no element compare callback was passed during initialization, then calling this function is undefined.
- Parameters:
rb – The ringbuffer handle.
e – The element to attempt to get the index of.
- Returns:
The logical index (as accepted by rbuffer_data_get()) of the first element, from the front, that matches according to the compare function; -1 if none matches or on error.
-
status_t rbuffer_serve_front(const struct rbuffer *rb, void *e)#
Retrieve the first entry from the ringbuffer.
The ringbuffer is not modified.
- Parameters:
rb – The ringbuffer handle.
e – To be filled with the first element.
- Returns:
-
void *rbuffer_front(const struct rbuffer *rb)#
Get a reference to the first entry in the ringbuffer.
The ringbuffer is not modified.
- Parameters:
rb – The ringbuffer handle.
- Returns:
A reference to the first element, or NULL if no such element or an error occurred.
-
status_t rbuffer_clear(struct rbuffer *rb)#
Clear a rbuffer, but do not deallocate its memory.
This resets the head/tail pointers, and zeros the managed memory.
- Parameters:
rb – The ringbuffer handle.
- Returns:
-
status_t rbuffer_map(struct rbuffer *rb, void (*f)(void *e))#
Apply a function to all elements in the ringbuffer.
- Parameters:
rb – The ringbuffer handle.
f – The mapping function, which CAN modify elements.
- Returns:
-
status_t rbuffer_inject(struct rbuffer *rb, void (*f)(void *elt, void *res), void *result)#
Compute a cumulative result (sum, count, …) over all elements in the ringbuffer.
- Parameters:
rb – The ringbuffer handle.
f – The mapping function, which CAN modify elements. First argument will point to each element in the ringbuffer in sequence. Second argument is
result.result – The initial result, which is passed to the callback along with each element in the ringbuffer.
- Returns:
-
void rbuffer_print(struct rbuffer *rb)#
Print each element of the ringbuffer with its
printecallback.If no element print callback was passed during initialization, then calling this function is undefined.
- Parameters:
rb – The ringbuffer handle.
-
struct ds_iterator *rbuffer_iter_init(struct ds_iterator *iter, struct rbuffer *rb, bool (*classify)(void *e))#
Initialize an iterator over a rbuffer.
Iteration is always forward (ITER_FORWARD).
- Parameters:
iter – Caller-allocated iterator storage.
rb – The ringbuffer to iterate over.
classify – Optional filter predicate; pass NULL for no filtering.
- Returns:
iteron success, or NULL on error.
Variables
-
const struct ds_ops rbuffer_iter_ops#
Vtable of traversal operations for rbuffer.
Supports forward iteration only (ringbuffer index arithmetic is asymmetric; backward iteration is left to the caller via index math). ds_ops::prev is NULL.
-
struct rbuffer_config#
- #include <rcsw/ds/rbuffer.h>
Parameters for rbuffer.
Public Members
-
int (*cmpe)(const void *const e1, const void *const e2)#
For comparing elements. Can be NULL. If NULL, rbuffer_index_query() must not be called.
-
void (*printe)(const void *e)#
For printing an element. Can be NULL. If NULL, rbuffer_print() must not be called.
-
dptr_t *elements#
Pointer to application-allocated space for storing the elements managed by the rbuffer. Ignored unless RCSW_NOALLOC_DATA is passed.
-
size_t elt_size#
Size of elements in bytes.
-
size_t max_elts#
Maximum number of elements allowed.
-
uint32_t flags#
Run-time configuration flags.
Valid flags are:
All other flags are ignored.
-
int (*cmpe)(const void *const e1, const void *const e2)#
-
struct rbuffer#
- #include <rcsw/ds/rbuffer.h>
Ringbuffer data structure. Implemented using a fixed-size array.
Public Members
-
struct rbuffer_config cfg#
The configuration the buffer was initialized with. rbuffer_config::elements is as passed (NULL if the library allocated the storage); use rbuffer::elements for the storage in use.
-
size_t current#
Current # of elements in buffer.
-
size_t start#
Physical index of the oldest element (the front). The next insert goes at
(start + current) % cfg.max_elts.
-
struct rbuffer_config cfg#