scratch_buffer_grow.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. bool
  21. __libc_scratch_buffer_grow (struct scratch_buffer *buffer)
  22. {
  23. void *new_ptr;
  24. size_t new_length = buffer->length * 2;
  25. /* Discard old buffer. */
  26. scratch_buffer_free (buffer);
  27. /* Check for overflow. */
  28. if (__glibc_likely (new_length >= buffer->length))
  29. new_ptr = malloc (new_length);
  30. else
  31. {
  32. __set_errno (ENOMEM);
  33. new_ptr = NULL;
  34. }
  35. if (__glibc_unlikely (new_ptr == NULL))
  36. {
  37. /* Buffer must remain valid to free. */
  38. scratch_buffer_init (buffer);
  39. return false;
  40. }
  41. /* Install new heap-based buffer. */
  42. buffer->data = new_ptr;
  43. buffer->length = new_length;
  44. return true;
  45. }
  46. libc_hidden_def (__libc_scratch_buffer_grow)