Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : #pragma once
26 :
27 : #include "citerators.h"
28 : #include "common.h"
29 : #include "csort.h"
30 :
31 : // Everything from here to the matching pop is the public ABI and the shared
32 : // library exports it. The library builds with -fvisibility=hidden, so anything
33 : // outside these blocks stays internal.
34 : #pragma GCC visibility push(default)
35 :
36 : // A generic dynamic array of fixed-size elements. It starts with room for 4
37 : // elements, doubles when it's full and halves when less than 1/4 is in use,
38 : // never going below 4. The struct is opaque and cvec is the handle.
39 : typedef struct cvector cvector;
40 :
41 : // The handle of a vector of fixed-size elements, a pointer to an opaque
42 : // cvector. Make one with cvec_construct() or cvector_create() and free it with
43 : // cvec_destroy() or cvector_destroy().
44 : typedef cvector *cvec;
45 :
46 : // Creates an empty vector of elem_size-byte elements with room for 4, using
47 : // your own allocator. elem_size must be more than 0 and at most SIZE_MAX / 4.
48 : // mmgmt_procs is the allocator table, or NULL for malloc and free; all four of
49 : // its functions must be set, and the vector keeps its own copy of the table.
50 : // On failure it gives NULL and, when err isn't NULL, a library-owned error
51 : // string in *err. Destroy the vector with cvector_destroy().
52 : cvec cvector_create_full(size_t elem_size, ccol_memmgmt_procs *mmgmt_procs,
53 : char **err);
54 :
55 : // Creates an empty vector of elem_size-byte elements with room for 4, using
56 : // malloc and free. elem_size must be more than 0 and at most SIZE_MAX / 4. On
57 : // failure it gives NULL and, when err isn't NULL, a library-owned error string
58 : // in *err. Destroy the vector with cvector_destroy().
59 : static inline __attribute__((always_inline)) cvec
60 1086 : cvector_create(size_t elem_size, char **err) {
61 1079 : return cvector_create_full(elem_size, NULL, err);
62 : }
63 :
64 : // Gives the allocator of the vector, or NULL when it uses the default one, so
65 : // you can allocate related memory the same way. Asserts on a NULL v.
66 : ccol_memmgmt_procs *cvector_get_mprocs(cvec v);
67 :
68 : // Internal: Frees the vector; it's the body of cvector_destroy(), which also
69 : // clears your pointer. Use the macro instead.
70 : void cvector__destroy(cvec v);
71 :
72 : // Frees the vector and its buffer and sets v to NULL, so no stale pointer to
73 : // the freed vector stays behind. v must be a modifiable lvalue and is evaluated
74 : // once; a NULL v does nothing. Memory that the elements point to isn't freed
75 : // for you. It's a statement and gives no value.
76 : #define cvector_destroy(v) \
77 : ccol__cvector_destroy_impl( \
78 : v, ccol__uniq(ccol__cvector_destroy_slot, __COUNTER__))
79 :
80 : // Internal: The body of cvector_destroy(). It takes the address of v once into
81 : // slot, which comes from ccol__uniq() so destroy macros can nest without
82 : // -Wshadow warnings.
83 : #define ccol__cvector_destroy_impl(v, slot) \
84 : do { \
85 : __typeof__(v) *slot = &(v); \
86 : if (*slot) { \
87 : cvector__destroy(*slot); \
88 : *slot = NULL; \
89 : } \
90 : } while (0)
91 :
92 : // Copies *new_elem to the end of the vector, doubling the capacity when it's
93 : // full; it's the raw append for code that must not abort. It gives
94 : // ccol_success, ccol_invalid_args for a NULL new_elem, ccol_container_full at
95 : // ccol_max_elem_count, or ccol_not_enough_memory when the growth fails.
96 : // new_elem may point into v's own buffer (from cvector_at() or
97 : // cvector_data_ptr()); a growth doesn't break that. Asserts on a NULL v.
98 : ccol_retval cvector_push_back(cvec v, const void *new_elem);
99 :
100 : // Removes the last element and copies it to *target_elem; it's the raw pop for
101 : // code that must not abort, and the only pop for an array element type. It
102 : // gives ccol_success, ccol_invalid_args for a NULL target_elem, or
103 : // ccol_container_empty. The capacity halves when less than 1/4 of it is in
104 : // use. Asserts on a NULL v.
105 : ccol_retval cvector_pop_back(cvec v, void *target_elem);
106 :
107 : // Gives a pointer to the element at index, or NULL when index is out of
108 : // range, so you can read or change an element in place without aborting on a
109 : // bad index. The pointer is valid until the size of the vector changes.
110 : // Asserts on a NULL v.
111 : void *cvector_at(cvec v, size_t index);
112 :
113 : // Gives the number of elements; the struct is opaque, so this is how you read
114 : // it. Asserts on a NULL v.
115 : size_t cvector_size(cvec v);
116 :
117 : // Removes every element and tries to shrink the capacity back to 4, so you can
118 : // reuse a vector without creating a new one. When that realloc fails the
119 : // capacity stays, but the count is 0 anyway. Elements aren't freed one by
120 : // one. Asserts on a NULL v.
121 : void cvector_reset(cvec v);
122 :
123 : // Makes room for at least new_capacity_count elements, rounded up to a power
124 : // of two (4 at least), so when you know the final size the pushes up to it
125 : // don't reallocate. It never shrinks, and gives false when the request is
126 : // above ccol_max_elem_count or the realloc fails. Asserts on a NULL v.
127 : bool cvector_reserve(cvec v, size_t new_capacity_count);
128 :
129 : // Appends elem_count elements from arr_ptr with at most one reallocation,
130 : // which is cheaper than a push per element. An elem_count of 0 gives true and
131 : // does nothing. It gives false, with v unchanged, for a NULL arr_ptr, on an
132 : // overflow, above ccol_max_elem_count, or when memory runs out. arr_ptr may
133 : // point into v's own buffer, and the source and destination may overlap; such
134 : // an aliasing range must stay inside v's reserved capacity or the call gives
135 : // false and leaves v unchanged. Asserts on a NULL v.
136 : bool cvector_append_array(cvec v, const void *arr_ptr, size_t elem_count);
137 :
138 : // Appends every element of v_from to v_to (v_from can be v_to), so joining two
139 : // vectors needs no loop. It gives false when memory runs out or the result is
140 : // above ccol_max_elem_count. Asserts when either vector is NULL or their
141 : // element sizes differ.
142 : bool cvector_append_cvector(cvec v_to, cvec v_from);
143 :
144 : // Gives the internal buffer, for code that expects a plain C array. Don't free
145 : // it, and don't keep it across a call that can change the size of the vector.
146 : // Asserts on a NULL v.
147 : void *cvector_data_ptr(cvec v);
148 :
149 : // Internal: Destroys *cv and sets it to NULL. The _scoped macros attach it
150 : // with ccol__destructor, so the vector goes away at the end of its scope.
151 4 : static inline void cvector__destroy_cleanup(cvec *cv) {
152 4 : if (cv && *cv) {
153 1 : cvector__destroy(*cv);
154 4 : *cv = NULL;
155 : }
156 : }
157 :
158 : // cvector_begin_iter(), the iterator of a vector, is declared in citerators.h.
159 :
160 : // Gives the index of the first element equal to *elem, or ccol_invalid_size
161 : // when nothing matches or elem is NULL. cmp decides equality (it gives 0 for
162 : // equal elements); with a NULL cmp the comparison is memcmp over the element
163 : // size, so padding bytes of a struct count. Asserts on a NULL v.
164 : size_t cvector_find(cvec v, const void *elem, ccol_comparison_proc cmp);
165 :
166 : // Declares a vector handle v whose elements have the given type, without
167 : // creating the vector. The typed cvec_ macros learn the element type from this
168 : // declaration, so declare v with it before you use them. v is uninitialized;
169 : // create the vector with cvec_init() or cvec_init_mp() and free it with
170 : // cvec_destroy(). It's a declaration.
171 : #define cvec_declare(v, type) \
172 : size_t *v##__ccol_key_type_var __attribute__((unused)); \
173 : __typeof__(type) *v##__ccol_val_type_var __attribute__((unused)); \
174 : cvec v
175 :
176 : // Declares a vector handle v whose elements have the given type, set to NULL,
177 : // for the typed cvec_ macros. Create the vector with cvec_init() or
178 : // cvec_init_mp(). Whatever vector v holds is destroyed when v goes out of
179 : // scope, on every way out, so don't destroy it yourself and don't return it.
180 : // It's a declaration.
181 : #define cvec_declare_scoped(v, type) \
182 : size_t *v##__ccol_key_type_var __attribute__((unused)) = NULL; \
183 : __typeof__(type) *v##__ccol_val_type_var __attribute__((unused)) = NULL; \
184 : cvec v ccol__destructor(cvector__destroy_cleanup) = NULL
185 :
186 : // Makes the typed cvec_ macros work on a vector v that was declared in another
187 : // scope, such as a function parameter of type cvec. type must be the element
188 : // type the vector was created with. It changes nothing about v itself. It's a
189 : // declaration.
190 : #define cvec_redeclare(v, type) \
191 : size_t *v##__ccol_key_type_var __attribute__((unused)) = NULL; \
192 : __typeof__(type) *v##__ccol_val_type_var __attribute__((unused)) = NULL
193 :
194 : // Creates an empty vector for a v declared with cvec_declare() or
195 : // cvec_declare_scoped(), using malloc and free, and assigns it to v. The
196 : // element size comes from the declared type, so you never pass sizeof. A
197 : // failed creation prints the reason and ends the program. It's a statement.
198 : #define cvec_init(v) \
199 : do { \
200 : char *ccol__cvec_err = NULL; \
201 : v = cvector_create(sizeof(*v##__ccol_val_type_var), &ccol__cvec_err); \
202 : if (!(v)) { \
203 : ccol__fatal_err("cvec_init('%s'): %s", #v, \
204 : ccol__cvec_err ? ccol__cvec_err : "unknown error"); \
205 : } \
206 : } while (0)
207 :
208 : // Creates an empty vector for a v declared with cvec_declare() or
209 : // cvec_declare_scoped() and assigns it to v. mprocs is the allocator table, or
210 : // NULL for malloc and free; the vector keeps its own copy. The element size
211 : // comes from the declared type. A failed creation (an allocator with a NULL
212 : // function included) prints the reason and ends the program. It's a statement.
213 : #define cvec_init_mp(v, mprocs) \
214 : do { \
215 : char *ccol__cvec_err = NULL; \
216 : v = cvector_create_full(sizeof(*v##__ccol_val_type_var), (mprocs), \
217 : &ccol__cvec_err); \
218 : if (!(v)) { \
219 : ccol__fatal_err("cvec_init_mp('%s'): %s", #v, \
220 : ccol__cvec_err ? ccol__cvec_err : "unknown error"); \
221 : } \
222 : } while (0)
223 :
224 : // Declares v and creates an empty vector of the given element type in it,
225 : // using malloc and free; it's the usual way to start a vector for the typed
226 : // cvec_ macros. A failed creation prints the reason and ends the program. Free
227 : // the vector with cvec_destroy(). It's a declaration followed by a statement.
228 : #define cvec_construct(v, type) \
229 : cvec_declare(v, type); \
230 : cvec_init(v)
231 :
232 : // Declares v and creates an empty vector of the given element type in it,
233 : // using malloc and free, for the typed cvec_ macros. The vector is destroyed
234 : // when v goes out of scope, on every way out, so don't destroy it yourself and
235 : // don't return it. A failed creation prints the reason and ends the program.
236 : #define cvec_construct_scoped(v, type) \
237 : cvec_declare_scoped(v, type); \
238 : cvec_init(v)
239 :
240 : // Declares v and creates an empty vector of the given element type in it, for
241 : // the typed cvec_ macros. mprocs is the allocator table, or NULL for malloc and
242 : // free; the vector keeps its own copy. A failed creation prints the reason and
243 : // ends the program. Free the vector with cvec_destroy().
244 : #define cvec_construct_mp(v, type, mprocs) \
245 : cvec_declare(v, type); \
246 : cvec_init_mp(v, mprocs)
247 :
248 : // Declares v and creates an empty vector of the given element type in it, for
249 : // the typed cvec_ macros. mprocs is the allocator table, or NULL for malloc and
250 : // free; the vector keeps its own copy. The vector is destroyed when v goes out
251 : // of scope, on every way out, so don't destroy it yourself and don't return
252 : // it. A failed creation prints the reason and ends the program.
253 : #define cvec_construct_mp_scoped(v, type, mprocs) \
254 : cvec_declare_scoped(v, type); \
255 : cvec_init_mp(v, mprocs)
256 :
257 : // Frees the vector and its buffer and sets v to NULL. v must be a modifiable
258 : // lvalue and is evaluated once; a NULL v does nothing. Memory that the
259 : // elements point to isn't freed for you. It's a statement.
260 : #define cvec_destroy(v) cvector_destroy(v)
261 :
262 : // Internal: Names v's element type without top-level qualifiers, so the macros
263 : // can write to a temporary of it even for a const element type. An array type
264 : // stays as it is. It's a type, and it doesn't evaluate v.
265 : #define cvec__unqual_elem_type(v) ccol__unqual_type(*v##__ccol_val_type_var)
266 :
267 : // Internal: A constant expression that is true when v's element type is an
268 : // array, which the macros must handle apart because C can't assign an array.
269 : // The comma operator decays an array to a pointer and leaves every other type
270 : // as it is. It doesn't evaluate v.
271 : #define cvec__elem_is_array(v) \
272 : (!__builtin_types_compatible_p( \
273 : __typeof__(*v##__ccol_val_type_var), \
274 : __typeof__((void)0, *v##__ccol_val_type_var)))
275 :
276 : // Internal: Gives elem for __typeof__ and sizeof on the array path of
277 : // cvec__elem_load, and 0 for any other element type. It's needed because elem
278 : // may be a bit-field there, which neither operator accepts; the value is never
279 : // used.
280 : #define cvec__elem_operand(v, elem) \
281 : __builtin_choose_expr(cvec__elem_is_array(v), (elem), 0)
282 :
283 : // Internal: Declares tmp of v's element type and stores elem into it, with elem
284 : // evaluated once; cvec_push and cvec_find need a typed copy so the value is
285 : // converted and never reinterpreted. A plain element is assigned, as in
286 : // `T tmp = elem;`. For an array element type elem must be an array or a string
287 : // literal: tmp is zeroed and gets elem's bytes up to the smaller size. Both
288 : // arms of each __builtin_choose_expr must compile for every element type,
289 : // which is why arg is a const void * on the non-array path.
290 : #define cvec__elem_load(v, elem, tmp, arg) \
291 : _Static_assert( \
292 : !cvec__elem_is_array(v) || \
293 : !__builtin_types_compatible_p( \
294 : __typeof__(cvec__elem_operand(v, elem)), \
295 : __typeof__((void)0, cvec__elem_operand(v, elem))), \
296 : "a vector whose element type is an array takes an array or a string " \
297 : "literal as the element value"); \
298 : cvec__unqual_elem_type(v) tmp; \
299 : __typeof__(__builtin_choose_expr(cvec__elem_is_array(v), \
300 : ((void)0, cvec__elem_operand(v, elem)), \
301 : (const void *)0)) arg; \
302 : *__builtin_choose_expr(cvec__elem_is_array(v), &arg, &tmp) = (elem); \
303 : __builtin_choose_expr( \
304 : cvec__elem_is_array(v), \
305 : (void)(memset(&tmp, 0, sizeof(tmp)), \
306 : memcpy(&tmp, (const void *)arg, \
307 : sizeof(cvec__elem_operand(v, elem)) < sizeof(tmp) \
308 : ? sizeof(cvec__elem_operand(v, elem)) \
309 : : sizeof(tmp))), \
310 : (void)0)
311 :
312 : // Appends new_elem to the end of v, doubling the capacity when it's full.
313 : // new_elem is a value, not a pointer: Any expression (a literal, a computed
314 : // value, a struct that a function returns), evaluated once and converted to
315 : // v's element type by assignment, so a float pushed into an int vector
316 : // truncates as in `int x = f;` and a type with no implicit conversion doesn't
317 : // compile. For an array element type new_elem is an array or a string literal.
318 : // new_elem may read from v's own buffer. With GCC 11 or later the stored copy
319 : // of a struct has zero padding bytes, which cvec_find relies on. A failure
320 : // (ccol_max_elem_count reached, or no memory) prints the reason and ends the
321 : // program. It's a statement.
322 : #define cvec_push(v, new_elem) \
323 : ccol__cvec_push_impl(v, (new_elem), \
324 : ccol__uniq(ccol__cvec_push_val, __COUNTER__), \
325 : ccol__uniq(ccol__cvec_push_arg, __COUNTER__), \
326 : ccol__uniq(ccol__cvec_push_r, __COUNTER__))
327 :
328 : // Internal: The body of cvec_push. Its temporaries get unique names from the
329 : // public macro so the public macros can nest.
330 : #define ccol__cvec_push_impl(v, new_elem, cvec__push_val, cvec__push_arg, \
331 : cvec__push_r) \
332 : do { \
333 : cvec__elem_load(v, new_elem, cvec__push_val, cvec__push_arg); \
334 : ccol__clear_padding(&cvec__push_val); \
335 : ccol_retval cvec__push_r = \
336 : cvector_push_back((v), (const void *)&cvec__push_val); \
337 : if (cvec__push_r != ccol_success) { \
338 : ccol__fatal_err("cvec_push('%s'): r: %d (%s)", #v, cvec__push_r, \
339 : ccol_retval_to_str(cvec__push_r)); \
340 : } \
341 : } while (0)
342 :
343 : // Removes the last element of v and evaluates to it as a value of the element
344 : // type. The capacity halves when less than 1/4 of it is in use. Popping from
345 : // an empty vector prints an error and ends the program, so check cvec_size()
346 : // first when the vector can be empty. An array element type is refused at
347 : // compile time, since C can't give an array as a value; pop such an element
348 : // into a buffer with cvector_pop_back().
349 : #define cvec_pop(v) \
350 : ccol__cvec_pop_impl(v, ccol__uniq(ccol__cvec_pop_tmp, __COUNTER__), \
351 : ccol__uniq(ccol__cvec_pop_r, __COUNTER__))
352 :
353 : // Internal: The body of cvec_pop, a statement expression whose value is the
354 : // popped element.
355 : #define ccol__cvec_pop_impl(v, cvec__pop_tmp, cvec__pop_r) \
356 : ({ \
357 : _Static_assert(!cvec__elem_is_array(v), \
358 : "cvec_pop cannot give an array element as a value; " \
359 : "pop it into a buffer with cvector_pop_back()"); \
360 : cvec__unqual_elem_type(v) cvec__pop_tmp; \
361 : ccol_retval cvec__pop_r = cvector_pop_back((v), &cvec__pop_tmp); \
362 : if (cvec__pop_r != ccol_success) { \
363 : ccol__fatal_err( \
364 : "cvec_pop('%s'): r: %d (%s)%s", #v, cvec__pop_r, \
365 : ccol_retval_to_str(cvec__pop_r), \
366 : cvec__pop_r == ccol_container_empty ? "; vector is empty" : ""); \
367 : } \
368 : cvec__pop_tmp; \
369 : })
370 :
371 : // Internal: Gives ptr, or stops the program with an out-of-bounds message when
372 : // it's NULL. It keeps cvec_at's diagnostic in one place, and reads the element
373 : // count only on that failure path, so a good lookup costs just the cvector_at()
374 : // call.
375 80714 : static inline __attribute__((always_inline)) void *cvec__at_checked(
376 : void *ptr, cvec v, const char *vec_name, size_t index) {
377 80714 : if (__builtin_expect(!ptr, 0)) {
378 2 : ccol__fatal_err("cvec_at('%s'): index %lu out of bounds (size: %lu)",
379 : vec_name, (unsigned long)index,
380 : (unsigned long)cvector_size(v));
381 : }
382 80712 : return ptr;
383 : }
384 :
385 : // Evaluates to the element at index as an lvalue of the element type, so you
386 : // can read it or assign to it with no cast: cvec_at(v, 0) = 5. index is
387 : // evaluated once, so cvec_at(v, i++) is safe. An out-of-range index prints the
388 : // index and the size and ends the program; use cvec_at_ptr() to get NULL
389 : // instead. The address of the element is valid until the size of v changes.
390 : #define cvec_at(v, index) \
391 : ccol__cvec_at_impl(v, (index), ccol__uniq(ccol__cvec_at_index, __COUNTER__))
392 :
393 : // Internal: The body of cvec_at. index goes into a local first, otherwise a
394 : // side effect in it would happen twice.
395 : #define ccol__cvec_at_impl(v, index, cvec__at_index) \
396 : (*(__typeof__(*v##__ccol_val_type_var) *)({ \
397 : size_t cvec__at_index = (index); \
398 : cvec__at_checked(cvector_at((v), cvec__at_index), (v), #v, \
399 : cvec__at_index); \
400 : }))
401 :
402 : // Evaluates to a pointer of the element type to the element at index, or NULL
403 : // when index is out of range, for code that checks the index instead of
404 : // ending the program. The pointer is valid until the size of v changes.
405 : #define cvec_at_ptr(v, index) \
406 : ((__typeof__(*v##__ccol_val_type_var) *)(cvector_at((v), (index))))
407 :
408 : // Evaluates to the number of elements in v, as a size_t. Asserts on a NULL v.
409 : #define cvec_size(v) cvector_size((v))
410 :
411 : // Removes every element of v and tries to shrink the capacity back to 4, so you
412 : // can reuse the vector; when that shrink fails the capacity stays, but the
413 : // count is 0 anyway. Memory that the elements point to isn't freed for you.
414 : // Asserts on a NULL v.
415 : #define cvec_reset(v) cvector_reset((v))
416 :
417 : // Makes room in v for at least new_capacity_count elements, rounded up to a
418 : // power of two, so the pushes up to that size don't reallocate. It never
419 : // shrinks. new_capacity_count is evaluated once. A request above
420 : // ccol_max_elem_count or a failed allocation prints an error and ends the
421 : // program. It's a statement.
422 : #define cvec_reserve(v, new_capacity_count) \
423 : ccol__cvec_reserve_impl(v, (new_capacity_count), \
424 : ccol__uniq(ccol__cvec_reserve_count, __COUNTER__))
425 :
426 : // Internal: The body of cvec_reserve, which keeps the count in a local.
427 : #define ccol__cvec_reserve_impl(v, new_capacity_count, cvec__reserve_count) \
428 : do { \
429 : size_t cvec__reserve_count = (new_capacity_count); \
430 : if (!cvector_reserve((v), cvec__reserve_count)) { \
431 : ccol__fatal_err( \
432 : "cvec_reserve('%s'): failed to reserve %lu elements; out of " \
433 : "memory?", \
434 : #v, (unsigned long)cvec__reserve_count); \
435 : } \
436 : } while (0)
437 :
438 : // Appends elem_count elements from the array arr_ptr to v with at most one
439 : // reallocation. elem_count is evaluated once, and 0 does nothing. arr_ptr may
440 : // point into v's own buffer as long as the range stays inside v's capacity. A
441 : // NULL arr_ptr, an overflow, a result above ccol_max_elem_count or a failed
442 : // allocation prints an error and ends the program. It's a statement.
443 : #define cvec_append_array(v, arr_ptr, elem_count) \
444 : ccol__cvec_append_array_impl( \
445 : v, (arr_ptr), (elem_count), \
446 : ccol__uniq(ccol__cvec_append_array_count, __COUNTER__))
447 :
448 : // Internal: The body of cvec_append_array, which keeps the count in a local.
449 : #define ccol__cvec_append_array_impl(v, arr_ptr, elem_count, \
450 : cvec__append_array_count) \
451 : do { \
452 : size_t cvec__append_array_count = (elem_count); \
453 : if (!cvector_append_array((v), (arr_ptr), cvec__append_array_count)) { \
454 : ccol__fatal_err( \
455 : "cvec_append_array('%s'): failed to append %lu elements; out of " \
456 : "memory?", \
457 : #v, (unsigned long)cvec__append_array_count); \
458 : } \
459 : } while (0)
460 :
461 : // Appends every element of v_from to v_to; v_from may be v_to itself. A failed
462 : // allocation or a result above ccol_max_elem_count prints an error and ends
463 : // the program, and a NULL vector or different element sizes assert. It's a
464 : // statement.
465 : #define cvec_append_cvec(v_to, v_from) \
466 : do { \
467 : if (!cvector_append_cvector((v_to), (v_from))) { \
468 : ccol__fatal_err("cvec_append_cvec('%s' <- '%s'): out of memory?", #v_to, \
469 : #v_from); \
470 : } \
471 : } while (0)
472 :
473 : // Evaluates to the internal buffer of v as a void *, for code that expects a
474 : // plain C array. Don't free it, and don't keep it across a call that can
475 : // change the size of v. Asserts on a NULL v.
476 : #define cvec_data_ptr(v) cvector_data_ptr((v))
477 :
478 : // Internal: Sorts v in place with a stable mergesort over the buffer; the sort
479 : // macros call it because they can't see inside the opaque struct. The
480 : // temporary buffer comes from v's allocator. It gives false, with v unchanged,
481 : // when that allocation fails.
482 : bool cvector__sort(cvec v, ccol_comparison_proc comparison_proc);
483 :
484 : // Sorts v in place with a stable mergesort and your comparator (O(n log n)
485 : // time, O(n) space), for element types with no default order or when you want
486 : // a different one. Each argument is evaluated once. A NULL v, a NULL
487 : // comparator or a failed allocation stops the program; on failure v is left
488 : // unsorted and unchanged. It's a statement.
489 : #define cvec_sort_with(v, comparison_proc) \
490 : do { \
491 : __typeof__(v) cvec__sort_v = (v); \
492 : if (!cvec__sort_v) { \
493 : ccol__fatal_err("cvec_sort_with('%s'): vector is NULL", #v); \
494 : } \
495 : ccol_comparison_proc cvec__sort_cmp = (comparison_proc); \
496 : if (!cvec__sort_cmp) { \
497 : ccol__fatal_err( \
498 : "cvec_sort_with('%s'): comparison_proc is " \
499 : "NULL; pass a real comparison procedure", \
500 : #v); \
501 : } \
502 : if (!cvector__sort(cvec__sort_v, cvec__sort_cmp)) { \
503 : ccol__fatal_err( \
504 : "cvec_sort_with('%s'): out of memory; vector " \
505 : "left unsorted", \
506 : #v); \
507 : } \
508 : } while (0)
509 :
510 : // Sorts v in place with a stable mergesort and the default order of its
511 : // element type, so the common types need no comparator: Integers, floats (NaN
512 : // last), enums, bool (false first) and char pointers (strcmp order, NULL
513 : // first). A type with no default order (a struct, a union, another pointer, a
514 : // char array) is a compile error that points you to
515 : // cvec_sort_with(). A failed allocation of the temporary
516 : // buffer prints an error and ends the program, with v unchanged.
517 : #define cvec_sort(v) \
518 : do { \
519 : _Static_assert( \
520 : csort__has_default_comparison_proc(*(v##__ccol_val_type_var)), \
521 : "cvec_sort(" #v \
522 : "): this vector's element type has no default comparison procedure " \
523 : "(a struct, a union, a pointer to anything other than char and a " \
524 : "fixed-size char array all have none). Sort this vector with " \
525 : "cvec_sort_with(" #v \
526 : ", your_comparison_proc) and an explicit comparison procedure " \
527 : "instead."); \
528 : ccol_comparison_proc ccol__cvec_sort_cmp = \
529 : csort_get_default_comparison_proc(*(v##__ccol_val_type_var)); \
530 : cvec_sort_with(v, ccol__cvec_sort_cmp); \
531 : } while (0)
532 :
533 : // Evaluates to the index of the first element of v equal to elem, or
534 : // ccol_invalid_size when none matches. elem is a value, not a pointer: Any
535 : // expression, evaluated once and converted to the element type. The comparison
536 : // is the default order of the element type, so -0.0 equals 0.0 and a char * is
537 : // compared as a string (don't use it on pointers to binary buffers). A type
538 : // with no default order falls back to byte-wise equality, which works for
539 : // padded structs only when both copies have zero padding (GCC 11 and later
540 : // clears it here and in cvec_push). Asserts on a NULL v.
541 : #define cvec_find(v, elem) \
542 : ccol__cvec_find_impl(v, (elem), \
543 : ccol__uniq(ccol__cvec_find_needle, __COUNTER__), \
544 : ccol__uniq(ccol__cvec_find_arg, __COUNTER__))
545 :
546 : // Internal: The body of cvec_find, a statement expression whose value is the
547 : // index.
548 : #define ccol__cvec_find_impl(v, elem, cvec__find_needle, cvec__find_arg) \
549 : ({ \
550 : cvec__elem_load(v, elem, cvec__find_needle, cvec__find_arg); \
551 : ccol__clear_padding(&cvec__find_needle); \
552 : cvector_find( \
553 : (v), (const void *)&cvec__find_needle, \
554 : csort_get_default_comparison_proc(*(v##__ccol_val_type_var))); \
555 : })
556 :
557 : #pragma GCC visibility pop
|