dynarray_resize.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* Increase the size of a dynamic array.
  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. #include <dynarray.h>
  16. #include <errno.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. bool
  20. __libc_dynarray_resize (struct dynarray_header *list, size_t size,
  21. void *scratch, size_t element_size)
  22. {
  23. /* The existing allocation provides sufficient room. */
  24. if (size <= list->allocated)
  25. {
  26. list->used = size;
  27. return true;
  28. }
  29. /* Otherwise, use size as the new allocation size. The caller is
  30. expected to provide the final size of the array, so there is no
  31. over-allocation here. */
  32. size_t new_size_bytes;
  33. if (__builtin_mul_overflow (size, element_size, &new_size_bytes))
  34. {
  35. /* Overflow. */
  36. __set_errno (ENOMEM);
  37. return false;
  38. }
  39. void *new_array;
  40. if (list->array == scratch)
  41. {
  42. /* The previous array was not heap-allocated. */
  43. new_array = malloc (new_size_bytes);
  44. if (new_array != NULL && list->array != NULL)
  45. memcpy (new_array, list->array, list->used * element_size);
  46. }
  47. else
  48. new_array = realloc (list->array, new_size_bytes);
  49. if (new_array == NULL)
  50. return false;
  51. list->array = new_array;
  52. list->allocated = size;
  53. list->used = size;
  54. return true;
  55. }
  56. libc_hidden_def (__libc_dynarray_resize)