scratch_buffer_grow_preserve.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* Variable-sized buffer with on-stack default allocation.
  2. Copyright (C) 2015-2023 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. #ifndef _LIBC
  16. # include <libc-config.h>
  17. #endif
  18. #include <scratch_buffer.h>
  19. #include <errno.h>
  20. #include <string.h>
  21. bool
  22. __libc_scratch_buffer_grow_preserve (struct scratch_buffer *buffer)
  23. {
  24. size_t new_length = 2 * buffer->length;
  25. void *new_ptr;
  26. if (buffer->data == buffer->__space.__c)
  27. {
  28. /* Move buffer to the heap. No overflow is possible because
  29. buffer->length describes a small buffer on the stack. */
  30. new_ptr = malloc (new_length);
  31. if (new_ptr == NULL)
  32. return false;
  33. memcpy (new_ptr, buffer->__space.__c, buffer->length);
  34. }
  35. else
  36. {
  37. /* Buffer was already on the heap. Check for overflow. */
  38. if (__glibc_likely (new_length >= buffer->length))
  39. new_ptr = realloc (buffer->data, new_length);
  40. else
  41. {
  42. __set_errno (ENOMEM);
  43. new_ptr = NULL;
  44. }
  45. if (__glibc_unlikely (new_ptr == NULL))
  46. {
  47. /* Deallocate, but buffer must remain valid to free. */
  48. free (buffer->data);
  49. scratch_buffer_init (buffer);
  50. return false;
  51. }
  52. }
  53. /* Install new heap-based buffer. */
  54. buffer->data = new_ptr;
  55. buffer->length = new_length;
  56. return true;
  57. }
  58. libc_hidden_def (__libc_scratch_buffer_grow_preserve)