C Collections

cvector · Section 3

cvec_reserve

cvec_reserve - reserve capacity for future elements (type-inferred, fatal on failure)

C Collections (libccollections, -lccollections)

#include <ccollections/cvector.h>
 
cvec_reserve(v, new_capacity_count);

A wrapper for cvector_reserve() that calls ccol__fatal_err() when the
reservation fails, so a caller that has no useful way to recover from an
allocation failure doesn't need to test a return value. A reservation too
large to represent also counts as a failure; NOTES gives the two limits
that it is tested against.
 
The capacity grows to the next power of two at or above
new_capacity_count, with a floor of 4 elements, so you usually get more
than you asked for. A request at or below the current capacity does
nothing, and this call never shrinks the capacity. The element count
doesn't change: The new space is capacity, not elements, and you reach it
only by pushing into it.

v                   Vector to reserve capacity for
new_capacity_count  Minimum number of elements to reserve

The macro stops the program through ccol__fatal_err() when the
reservation fails: When the allocation fails, when the capacity is more
than ccol_max_elem_count, or when the capacity times the element size
overflows a size_t.
 
Both limits are tested against the rounded-up capacity, not against
new_capacity_count itself, so a request within a limit can still fail once
it is rounded up to the next power of two. A vector of wide elements hits
the size_t overflow limit first. That limit caps the capacity at SIZE_MAX
divided by the element size, which for any element wider than one byte
is the lower of the two.
 
new_capacity_count is evaluated exactly once on every path, the failure
path included, so an expression with a side effect is safe to pass.
 
The real capacity is rounded up to a power of two, with a minimum of 4.
The element count stays the same; cvec_size(3) reads it.
 
A reservation invalidates every pointer obtained earlier from
cvec_data_ptr(3) or cvec_at_ptr(3). The macro asserts when v is NULL.
 
To handle a failed reservation yourself, call cvector_reserve(3)
directly; that function doesn't stop the program.

cvec_construct(vec, int);
cvec_reserve(vec, 100);   // capacity becomes 128, size stays 0
for (int i = 0; i < 100; i++) {
    cvec_push(vec, i);   // no reallocation in the loop
}
cvec_destroy(vec);

cvector_reserve(3), cvec_append_array(3), cvec_push(3)