dynarray_emplace_enlarge.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* Increase the size of a dynamic array in preparation of an emplace operation.
  2. Copyright (C) 2017-2021 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. <https://www.gnu.org/licenses/>. */
  15. #include <dynarray.h>
  16. #include <errno.h>
  17. #include <intprops.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. bool
  21. __libc_dynarray_emplace_enlarge (struct dynarray_header *list,
  22. void *scratch, size_t element_size)
  23. {
  24. size_t new_allocated;
  25. if (list->allocated == 0)
  26. {
  27. /* No scratch buffer provided. Choose a reasonable default
  28. size. */
  29. if (element_size < 4)
  30. new_allocated = 16;
  31. else if (element_size < 8)
  32. new_allocated = 8;
  33. else
  34. new_allocated = 4;
  35. }
  36. else
  37. /* Increase the allocated size, using an exponential growth
  38. policy. */
  39. {
  40. new_allocated = list->allocated + list->allocated / 2 + 1;
  41. if (new_allocated <= list->allocated)
  42. {
  43. /* Overflow. */
  44. __set_errno (ENOMEM);
  45. return false;
  46. }
  47. }
  48. size_t new_size;
  49. if (INT_MULTIPLY_WRAPV (new_allocated, element_size, &new_size))
  50. return false;
  51. void *new_array;
  52. if (list->array == scratch)
  53. {
  54. /* The previous array was not heap-allocated. */
  55. new_array = malloc (new_size);
  56. if (new_array != NULL && list->array != NULL)
  57. memcpy (new_array, list->array, list->used * element_size);
  58. }
  59. else
  60. new_array = realloc (list->array, new_size);
  61. if (new_array == NULL)
  62. return false;
  63. list->array = new_array;
  64. list->allocated = new_allocated;
  65. return true;
  66. }
  67. libc_hidden_def (__libc_dynarray_emplace_enlarge)