C Collections

cvector · Section 3

cvec_append_array

cvec_append_array - append a C array to a vector (type-inferred, fatal on failure)

C Collections (libccollections, -lccollections)

#include <ccollections/cvector.h>
 
cvec_append_array(v, arr_ptr, elem_count);

A wrapper for cvector_append_array() that calls ccol__fatal_err() when the
append fails, so a caller that has no useful way to recover from an
allocation failure doesn't need to test a return value.
 
It copies elem_count elements from arr_ptr onto the end of v in one bulk
copy and grows the capacity at most once, not once per element. The append
is all or nothing: Either every element lands in the vector or the vector
stays exactly as it was.
 
The elements are copied byte for byte from arr_ptr, so arr_ptr must point
at elements of the vector's declared element type. Unlike cvec_push(3),
this macro converts no element.

v           Vector to append to
arr_ptr     Pointer to the first element of the array to copy from. It
            can point at a const array.
elem_count  Number of elements to copy

The macro stops the program with ccol__fatal_err() when the append fails.
That happens when the allocation fails, when the new element count would
be more than ccol_max_elem_count, when elem_count is large enough to
overflow that count, when arr_ptr is NULL and elem_count is not zero, and
when arr_ptr aliases the backing buffer of v and elem_count reads past the
end of that buffer's reservation.
 
An elem_count of zero succeeds and leaves both the vector and arr_ptr
unchanged, so a NULL arr_ptr is refused only when there is something to
copy.
 
elem_count is evaluated exactly once on every path, the failure path
included, so an expression with a side effect is safe to pass.
 
arr_ptr may point into the backing store of v, for example a pointer from
cvec_data_ptr(3) or cvec_at_ptr(3), and a capacity growth started by this
call doesn't invalidate it. The source and destination ranges may also
overlap, as long as the source range stays inside that buffer's
reservation.
 
Each call grows the capacity at most once, to the next power of two at or
above the new element count, with a floor of 4.
 
The macro asserts when v is NULL.
 
To handle a failed append yourself, call cvector_append_array(3) directly;
that function doesn't stop the program.

int src[] = {1, 2, 3, 4, 5};
cvec_construct(vec, int);
cvec_append_array(vec, src, 5);
// cvec_size(vec) == 5
cvec_destroy(vec);

cvector_append_array(3), cvec_append_cvec(3), cvec_reserve(3), cvec_push(3)