dynarray-skeleton.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /* Type-safe arrays which grow dynamically.
  2. Copyright (C) 2017-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. /* Pre-processor macros which act as parameters:
  16. DYNARRAY_STRUCT
  17. The struct tag of dynamic array to be defined.
  18. DYNARRAY_ELEMENT
  19. The type name of the element type. Elements are copied
  20. as if by memcpy, and can change address as the dynamic
  21. array grows.
  22. DYNARRAY_PREFIX
  23. The prefix of the functions which are defined.
  24. The following parameters are optional:
  25. DYNARRAY_ELEMENT_FREE
  26. DYNARRAY_ELEMENT_FREE (E) is evaluated to deallocate the
  27. contents of elements. E is of type DYNARRAY_ELEMENT *.
  28. DYNARRAY_ELEMENT_INIT
  29. DYNARRAY_ELEMENT_INIT (E) is evaluated to initialize a new
  30. element. E is of type DYNARRAY_ELEMENT *.
  31. If DYNARRAY_ELEMENT_FREE but not DYNARRAY_ELEMENT_INIT is
  32. defined, new elements are automatically zero-initialized.
  33. Otherwise, new elements have undefined contents.
  34. DYNARRAY_INITIAL_SIZE
  35. The size of the statically allocated array (default:
  36. at least 2, more elements if they fit into 128 bytes).
  37. Must be a preprocessor constant. If DYNARRAY_INITIAL_SIZE is 0,
  38. there is no statically allocated array at, and all non-empty
  39. arrays are heap-allocated.
  40. DYNARRAY_FINAL_TYPE
  41. The name of the type which holds the final array. If not
  42. defined, is PREFIX##finalize not provided. DYNARRAY_FINAL_TYPE
  43. must be a struct type, with members of type DYNARRAY_ELEMENT and
  44. size_t at the start (in this order).
  45. These macros are undefined after this header file has been
  46. included.
  47. The following types are provided (their members are private to the
  48. dynarray implementation):
  49. struct DYNARRAY_STRUCT
  50. The following functions are provided:
  51. void DYNARRAY_PREFIX##init (struct DYNARRAY_STRUCT *);
  52. void DYNARRAY_PREFIX##free (struct DYNARRAY_STRUCT *);
  53. bool DYNARRAY_PREFIX##has_failed (const struct DYNARRAY_STRUCT *);
  54. void DYNARRAY_PREFIX##mark_failed (struct DYNARRAY_STRUCT *);
  55. size_t DYNARRAY_PREFIX##size (const struct DYNARRAY_STRUCT *);
  56. DYNARRAY_ELEMENT *DYNARRAY_PREFIX##begin (const struct DYNARRAY_STRUCT *);
  57. DYNARRAY_ELEMENT *DYNARRAY_PREFIX##end (const struct DYNARRAY_STRUCT *);
  58. DYNARRAY_ELEMENT *DYNARRAY_PREFIX##at (struct DYNARRAY_STRUCT *, size_t);
  59. void DYNARRAY_PREFIX##add (struct DYNARRAY_STRUCT *, DYNARRAY_ELEMENT);
  60. DYNARRAY_ELEMENT *DYNARRAY_PREFIX##emplace (struct DYNARRAY_STRUCT *);
  61. bool DYNARRAY_PREFIX##resize (struct DYNARRAY_STRUCT *, size_t);
  62. void DYNARRAY_PREFIX##remove_last (struct DYNARRAY_STRUCT *);
  63. void DYNARRAY_PREFIX##clear (struct DYNARRAY_STRUCT *);
  64. The following functions are provided are provided if the
  65. prerequisites are met:
  66. bool DYNARRAY_PREFIX##finalize (struct DYNARRAY_STRUCT *,
  67. DYNARRAY_FINAL_TYPE *);
  68. (if DYNARRAY_FINAL_TYPE is defined)
  69. DYNARRAY_ELEMENT *DYNARRAY_PREFIX##finalize (struct DYNARRAY_STRUCT *,
  70. size_t *);
  71. (if DYNARRAY_FINAL_TYPE is not defined)
  72. */
  73. #include <malloc/dynarray.h>
  74. #include <errno.h>
  75. #include <stdlib.h>
  76. #include <string.h>
  77. #ifndef DYNARRAY_STRUCT
  78. # error "DYNARRAY_STRUCT must be defined"
  79. #endif
  80. #ifndef DYNARRAY_ELEMENT
  81. # error "DYNARRAY_ELEMENT must be defined"
  82. #endif
  83. #ifndef DYNARRAY_PREFIX
  84. # error "DYNARRAY_PREFIX must be defined"
  85. #endif
  86. #ifdef DYNARRAY_INITIAL_SIZE
  87. # if DYNARRAY_INITIAL_SIZE < 0
  88. # error "DYNARRAY_INITIAL_SIZE must be non-negative"
  89. # endif
  90. # if DYNARRAY_INITIAL_SIZE > 0
  91. # define DYNARRAY_HAVE_SCRATCH 1
  92. # else
  93. # define DYNARRAY_HAVE_SCRATCH 0
  94. # endif
  95. #else
  96. /* Provide a reasonable default which limits the size of
  97. DYNARRAY_STRUCT. */
  98. # define DYNARRAY_INITIAL_SIZE \
  99. (sizeof (DYNARRAY_ELEMENT) > 64 ? 2 : 128 / sizeof (DYNARRAY_ELEMENT))
  100. # define DYNARRAY_HAVE_SCRATCH 1
  101. #endif
  102. /* Public type definitions. */
  103. /* All fields of this struct are private to the implementation. */
  104. struct DYNARRAY_STRUCT
  105. {
  106. union
  107. {
  108. struct dynarray_header dynarray_abstract;
  109. struct
  110. {
  111. /* These fields must match struct dynarray_header. */
  112. size_t used;
  113. size_t allocated;
  114. DYNARRAY_ELEMENT *array;
  115. } dynarray_header;
  116. };
  117. #if DYNARRAY_HAVE_SCRATCH
  118. /* Initial inline allocation. */
  119. DYNARRAY_ELEMENT scratch[DYNARRAY_INITIAL_SIZE];
  120. #endif
  121. };
  122. /* Internal use only: Helper macros. */
  123. /* Ensure macro-expansion of DYNARRAY_PREFIX. */
  124. #define DYNARRAY_CONCAT0(prefix, name) prefix##name
  125. #define DYNARRAY_CONCAT1(prefix, name) DYNARRAY_CONCAT0(prefix, name)
  126. #define DYNARRAY_NAME(name) DYNARRAY_CONCAT1(DYNARRAY_PREFIX, name)
  127. /* Address of the scratch buffer if any. */
  128. #if DYNARRAY_HAVE_SCRATCH
  129. # define DYNARRAY_SCRATCH(list) (list)->scratch
  130. #else
  131. # define DYNARRAY_SCRATCH(list) NULL
  132. #endif
  133. /* Internal use only: Helper functions. */
  134. /* Internal function. Call DYNARRAY_ELEMENT_FREE with the array
  135. elements. Name mangling needed due to the DYNARRAY_ELEMENT_FREE
  136. macro expansion. */
  137. static inline void
  138. DYNARRAY_NAME (free__elements__) (DYNARRAY_ELEMENT *__dynarray_array,
  139. size_t __dynarray_used)
  140. {
  141. #ifdef DYNARRAY_ELEMENT_FREE
  142. for (size_t __dynarray_i = 0; __dynarray_i < __dynarray_used; ++__dynarray_i)
  143. DYNARRAY_ELEMENT_FREE (&__dynarray_array[__dynarray_i]);
  144. #endif /* DYNARRAY_ELEMENT_FREE */
  145. }
  146. /* Internal function. Free the non-scratch array allocation. */
  147. static inline void
  148. DYNARRAY_NAME (free__array__) (struct DYNARRAY_STRUCT *list)
  149. {
  150. #if DYNARRAY_HAVE_SCRATCH
  151. if (list->dynarray_header.array != list->scratch)
  152. free (list->dynarray_header.array);
  153. #else
  154. free (list->dynarray_header.array);
  155. #endif
  156. }
  157. /* Public functions. */
  158. /* Initialize a dynamic array object. This must be called before any
  159. use of the object. */
  160. __attribute__ ((nonnull (1)))
  161. static void
  162. DYNARRAY_NAME (init) (struct DYNARRAY_STRUCT *list)
  163. {
  164. list->dynarray_header.used = 0;
  165. list->dynarray_header.allocated = DYNARRAY_INITIAL_SIZE;
  166. list->dynarray_header.array = DYNARRAY_SCRATCH (list);
  167. }
  168. /* Deallocate the dynamic array and its elements. */
  169. __attribute__ ((unused, nonnull (1)))
  170. static void
  171. DYNARRAY_NAME (free) (struct DYNARRAY_STRUCT *list)
  172. {
  173. DYNARRAY_NAME (free__elements__)
  174. (list->dynarray_header.array, list->dynarray_header.used);
  175. DYNARRAY_NAME (free__array__) (list);
  176. DYNARRAY_NAME (init) (list);
  177. }
  178. /* Return true if the dynamic array is in an error state. */
  179. __attribute__ ((nonnull (1)))
  180. static inline bool
  181. DYNARRAY_NAME (has_failed) (const struct DYNARRAY_STRUCT *list)
  182. {
  183. return list->dynarray_header.allocated == __dynarray_error_marker ();
  184. }
  185. /* Mark the dynamic array as failed. All elements are deallocated as
  186. a side effect. */
  187. __attribute__ ((nonnull (1)))
  188. static void
  189. DYNARRAY_NAME (mark_failed) (struct DYNARRAY_STRUCT *list)
  190. {
  191. DYNARRAY_NAME (free__elements__)
  192. (list->dynarray_header.array, list->dynarray_header.used);
  193. DYNARRAY_NAME (free__array__) (list);
  194. list->dynarray_header.array = DYNARRAY_SCRATCH (list);
  195. list->dynarray_header.used = 0;
  196. list->dynarray_header.allocated = __dynarray_error_marker ();
  197. }
  198. /* Return the number of elements which have been added to the dynamic
  199. array. */
  200. __attribute__ ((nonnull (1)))
  201. static inline size_t
  202. DYNARRAY_NAME (size) (const struct DYNARRAY_STRUCT *list)
  203. {
  204. return list->dynarray_header.used;
  205. }
  206. /* Return a pointer to the array element at INDEX. Terminate the
  207. process if INDEX is out of bounds. */
  208. __attribute__ ((nonnull (1)))
  209. static inline DYNARRAY_ELEMENT *
  210. DYNARRAY_NAME (at) (struct DYNARRAY_STRUCT *list, size_t index)
  211. {
  212. if (__glibc_unlikely (index >= DYNARRAY_NAME (size) (list)))
  213. __libc_dynarray_at_failure (DYNARRAY_NAME (size) (list), index);
  214. return list->dynarray_header.array + index;
  215. }
  216. /* Return a pointer to the first array element, if any. For a
  217. zero-length array, the pointer can be NULL even though the dynamic
  218. array has not entered the failure state. */
  219. __attribute__ ((nonnull (1)))
  220. static inline DYNARRAY_ELEMENT *
  221. DYNARRAY_NAME (begin) (struct DYNARRAY_STRUCT *list)
  222. {
  223. return list->dynarray_header.array;
  224. }
  225. /* Return a pointer one element past the last array element. For a
  226. zero-length array, the pointer can be NULL even though the dynamic
  227. array has not entered the failure state. */
  228. __attribute__ ((nonnull (1)))
  229. static inline DYNARRAY_ELEMENT *
  230. DYNARRAY_NAME (end) (struct DYNARRAY_STRUCT *list)
  231. {
  232. return list->dynarray_header.array + list->dynarray_header.used;
  233. }
  234. /* Internal function. Slow path for the add function below. */
  235. static void
  236. DYNARRAY_NAME (add__) (struct DYNARRAY_STRUCT *list, DYNARRAY_ELEMENT item)
  237. {
  238. if (__glibc_unlikely
  239. (!__libc_dynarray_emplace_enlarge (&list->dynarray_abstract,
  240. DYNARRAY_SCRATCH (list),
  241. sizeof (DYNARRAY_ELEMENT))))
  242. {
  243. DYNARRAY_NAME (mark_failed) (list);
  244. return;
  245. }
  246. /* Copy the new element and increase the array length. */
  247. list->dynarray_header.array[list->dynarray_header.used++] = item;
  248. }
  249. /* Add ITEM at the end of the array, enlarging it by one element.
  250. Mark *LIST as failed if the dynamic array allocation size cannot be
  251. increased. */
  252. __attribute__ ((unused, nonnull (1)))
  253. static inline void
  254. DYNARRAY_NAME (add) (struct DYNARRAY_STRUCT *list, DYNARRAY_ELEMENT item)
  255. {
  256. /* Do nothing in case of previous error. */
  257. if (DYNARRAY_NAME (has_failed) (list))
  258. return;
  259. /* Enlarge the array if necessary. */
  260. if (__glibc_unlikely (list->dynarray_header.used
  261. == list->dynarray_header.allocated))
  262. {
  263. DYNARRAY_NAME (add__) (list, item);
  264. return;
  265. }
  266. /* Copy the new element and increase the array length. */
  267. list->dynarray_header.array[list->dynarray_header.used++] = item;
  268. }
  269. /* Internal function. Building block for the emplace functions below.
  270. Assumes space for one more element in *LIST. */
  271. static inline DYNARRAY_ELEMENT *
  272. DYNARRAY_NAME (emplace__tail__) (struct DYNARRAY_STRUCT *list)
  273. {
  274. DYNARRAY_ELEMENT *result
  275. = &list->dynarray_header.array[list->dynarray_header.used];
  276. ++list->dynarray_header.used;
  277. #if defined (DYNARRAY_ELEMENT_INIT)
  278. DYNARRAY_ELEMENT_INIT (result);
  279. #elif defined (DYNARRAY_ELEMENT_FREE)
  280. memset (result, 0, sizeof (*result));
  281. #endif
  282. return result;
  283. }
  284. /* Internal function. Slow path for the emplace function below. */
  285. static DYNARRAY_ELEMENT *
  286. DYNARRAY_NAME (emplace__) (struct DYNARRAY_STRUCT *list)
  287. {
  288. if (__glibc_unlikely
  289. (!__libc_dynarray_emplace_enlarge (&list->dynarray_abstract,
  290. DYNARRAY_SCRATCH (list),
  291. sizeof (DYNARRAY_ELEMENT))))
  292. {
  293. DYNARRAY_NAME (mark_failed) (list);
  294. return NULL;
  295. }
  296. return DYNARRAY_NAME (emplace__tail__) (list);
  297. }
  298. /* Allocate a place for a new element in *LIST and return a pointer to
  299. it. The pointer can be NULL if the dynamic array cannot be
  300. enlarged due to a memory allocation failure. */
  301. __attribute__ ((unused, warn_unused_result, nonnull (1)))
  302. static
  303. /* Avoid inlining with the larger initialization code. */
  304. #if !(defined (DYNARRAY_ELEMENT_INIT) || defined (DYNARRAY_ELEMENT_FREE))
  305. inline
  306. #endif
  307. DYNARRAY_ELEMENT *
  308. DYNARRAY_NAME (emplace) (struct DYNARRAY_STRUCT *list)
  309. {
  310. /* Do nothing in case of previous error. */
  311. if (DYNARRAY_NAME (has_failed) (list))
  312. return NULL;
  313. /* Enlarge the array if necessary. */
  314. if (__glibc_unlikely (list->dynarray_header.used
  315. == list->dynarray_header.allocated))
  316. return (DYNARRAY_NAME (emplace__) (list));
  317. return DYNARRAY_NAME (emplace__tail__) (list);
  318. }
  319. /* Change the size of *LIST to SIZE. If SIZE is larger than the
  320. existing size, new elements are added (which can be initialized).
  321. Otherwise, the list is truncated, and elements are freed. Return
  322. false on memory allocation failure (and mark *LIST as failed). */
  323. __attribute__ ((unused, nonnull (1)))
  324. static bool
  325. DYNARRAY_NAME (resize) (struct DYNARRAY_STRUCT *list, size_t size)
  326. {
  327. if (size > list->dynarray_header.used)
  328. {
  329. bool ok;
  330. #if defined (DYNARRAY_ELEMENT_INIT)
  331. /* The new elements have to be initialized. */
  332. size_t old_size = list->dynarray_header.used;
  333. ok = __libc_dynarray_resize (&list->dynarray_abstract,
  334. size, DYNARRAY_SCRATCH (list),
  335. sizeof (DYNARRAY_ELEMENT));
  336. if (ok)
  337. for (size_t i = old_size; i < size; ++i)
  338. {
  339. DYNARRAY_ELEMENT_INIT (&list->dynarray_header.array[i]);
  340. }
  341. #elif defined (DYNARRAY_ELEMENT_FREE)
  342. /* Zero initialization is needed so that the elements can be
  343. safely freed. */
  344. ok = __libc_dynarray_resize_clear
  345. (&list->dynarray_abstract, size,
  346. DYNARRAY_SCRATCH (list), sizeof (DYNARRAY_ELEMENT));
  347. #else
  348. ok = __libc_dynarray_resize (&list->dynarray_abstract,
  349. size, DYNARRAY_SCRATCH (list),
  350. sizeof (DYNARRAY_ELEMENT));
  351. #endif
  352. if (__glibc_unlikely (!ok))
  353. DYNARRAY_NAME (mark_failed) (list);
  354. return ok;
  355. }
  356. else
  357. {
  358. /* The list has shrunk in size. Free the removed elements. */
  359. DYNARRAY_NAME (free__elements__)
  360. (list->dynarray_header.array + size,
  361. list->dynarray_header.used - size);
  362. list->dynarray_header.used = size;
  363. return true;
  364. }
  365. }
  366. /* Remove the last element of LIST if it is present. */
  367. __attribute__ ((unused, nonnull (1)))
  368. static void
  369. DYNARRAY_NAME (remove_last) (struct DYNARRAY_STRUCT *list)
  370. {
  371. /* used > 0 implies that the array is the non-failed state. */
  372. if (list->dynarray_header.used > 0)
  373. {
  374. size_t new_length = list->dynarray_header.used - 1;
  375. #ifdef DYNARRAY_ELEMENT_FREE
  376. DYNARRAY_ELEMENT_FREE (&list->dynarray_header.array[new_length]);
  377. #endif
  378. list->dynarray_header.used = new_length;
  379. }
  380. }
  381. /* Remove all elements from the list. The elements are freed, but the
  382. list itself is not. */
  383. __attribute__ ((unused, nonnull (1)))
  384. static void
  385. DYNARRAY_NAME (clear) (struct DYNARRAY_STRUCT *list)
  386. {
  387. /* free__elements__ does nothing if the list is in the failed
  388. state. */
  389. DYNARRAY_NAME (free__elements__)
  390. (list->dynarray_header.array, list->dynarray_header.used);
  391. list->dynarray_header.used = 0;
  392. }
  393. #ifdef DYNARRAY_FINAL_TYPE
  394. /* Transfer the dynamic array to a permanent location at *RESULT.
  395. Returns true on success on false on allocation failure. In either
  396. case, *LIST is re-initialized and can be reused. A NULL pointer is
  397. stored in *RESULT if LIST refers to an empty list. On success, the
  398. pointer in *RESULT is heap-allocated and must be deallocated using
  399. free. */
  400. __attribute__ ((unused, warn_unused_result, nonnull (1, 2)))
  401. static bool
  402. DYNARRAY_NAME (finalize) (struct DYNARRAY_STRUCT *list,
  403. DYNARRAY_FINAL_TYPE *result)
  404. {
  405. struct dynarray_finalize_result res;
  406. if (__libc_dynarray_finalize (&list->dynarray_abstract,
  407. DYNARRAY_SCRATCH (list),
  408. sizeof (DYNARRAY_ELEMENT), &res))
  409. {
  410. /* On success, the result owns all the data. */
  411. DYNARRAY_NAME (init) (list);
  412. *result = (DYNARRAY_FINAL_TYPE) { res.array, res.length };
  413. return true;
  414. }
  415. else
  416. {
  417. /* On error, we need to free all data. */
  418. DYNARRAY_NAME (free) (list);
  419. errno = ENOMEM;
  420. return false;
  421. }
  422. }
  423. #else /* !DYNARRAY_FINAL_TYPE */
  424. /* Transfer the dynamic array to a heap-allocated array and return a
  425. pointer to it. The pointer is NULL if memory allocation fails, or
  426. if the array is empty, so this function should be used only for
  427. arrays which are known not be empty (usually because they always
  428. have a sentinel at the end). If LENGTHP is not NULL, the array
  429. length is written to *LENGTHP. *LIST is re-initialized and can be
  430. reused. */
  431. __attribute__ ((unused, warn_unused_result, nonnull (1)))
  432. static DYNARRAY_ELEMENT *
  433. DYNARRAY_NAME (finalize) (struct DYNARRAY_STRUCT *list, size_t *lengthp)
  434. {
  435. struct dynarray_finalize_result res;
  436. if (__libc_dynarray_finalize (&list->dynarray_abstract,
  437. DYNARRAY_SCRATCH (list),
  438. sizeof (DYNARRAY_ELEMENT), &res))
  439. {
  440. /* On success, the result owns all the data. */
  441. DYNARRAY_NAME (init) (list);
  442. if (lengthp != NULL)
  443. *lengthp = res.length;
  444. return res.array;
  445. }
  446. else
  447. {
  448. /* On error, we need to free all data. */
  449. DYNARRAY_NAME (free) (list);
  450. errno = ENOMEM;
  451. return NULL;
  452. }
  453. }
  454. #endif /* !DYNARRAY_FINAL_TYPE */
  455. /* Undo macro definitions. */
  456. #undef DYNARRAY_CONCAT0
  457. #undef DYNARRAY_CONCAT1
  458. #undef DYNARRAY_NAME
  459. #undef DYNARRAY_SCRATCH
  460. #undef DYNARRAY_HAVE_SCRATCH
  461. #undef DYNARRAY_STRUCT
  462. #undef DYNARRAY_ELEMENT
  463. #undef DYNARRAY_PREFIX
  464. #undef DYNARRAY_ELEMENT_FREE
  465. #undef DYNARRAY_ELEMENT_INIT
  466. #undef DYNARRAY_INITIAL_SIZE
  467. #undef DYNARRAY_FINAL_TYPE