cvector · Overview
cvector
NAME
CVECTOR - overview of the cvector dynamic array
LIBRARY
C Collections (libccollections, -lccollections)
SYNOPSIS
#include <ccollections/cvector.h>
DESCRIPTION
A cvec is a resizable array of elements of one type, kept contiguous in memory. Access by index is O(1), appending at the end is amortized O(1), and sorting is O(n log n) and stable, so equal elements keep their relative order. The capacity starts at 4 elements and never goes below 4. A full vector doubles its capacity, and when a removal leaves it less than a quarter full the capacity is halved. cvec_reserve(3) and cvec_append_array(3) grow the capacity to the next power of two at or above the count they need. There are two layers in the API. The type-inferred macros, such as cvec_construct(3), cvec_push(3), cvec_at(3) and cvec_sort(3), keep the element type with the handle in companion variables, which cvec_declare(3), the construct macros and cvec_redeclare(3) declare, and on a hard error such as a failed allocation they stop the program through ccol__fatal_err(). The raw functions, such as cvector_create_full(3), cvector_push_back(3), cvector_pop_back(3) and cvector_reserve(3), take elements by pointer and report a failure in their return value. The element type can be any type: An arithmetic type, a pointer, a struct, a union, a function pointer type such as void (*)(int), or an array type such as char[32].
OWNERSHIP OF ELEMENTS
The vector keeps a copy of each element. For a pointer element it keeps only the value of the pointer; it never follows that address and never frees the object behind it. cvec_destroy(3) and cvec_reset(3) don't free the objects that the elements point to either, so the caller has to free them first.
REFERENCES INTO THE VECTOR
cvec_data_ptr(3), cvec_at_ptr(3) and the address of a cvec_at(3) element all point into the backing store, and any operation that can grow or shrink that store moves it: A push, an append, a reserve, a pop, a reset and the destruction. Get such a pointer again after each of them. You can pass a value read from the vector to cvec_push(3), and a pointer into the vector to cvec_append_array(3); both read their source safely even when they reallocate the store.
THREAD SAFETY
A vector has no internal lock. One vector can be shared between threads, but then the caller must serialize every call that changes it against all other calls on that vector.
SEE ALSO
cvec_construct(3), cvec_redeclare(3), cvec_push(3), cvec_at(3), cvec_sort(3), cvector_create_full(3), cvector_push_back(3), cvector_begin_iter(3), csort_sort(3), cstring(7), citerators(7)