strbuf.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* ----------------------------------------------------------------------------
  2. libconfig - A library for processing structured configuration files
  3. Copyright (C) 2005-2010 Mark A Lindner
  4. This file is part of libconfig.
  5. This library is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. This library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this library. If not, see <http://www.gnu.org/licenses/>.
  15. ----------------------------------------------------------------------------
  16. */
  17. #include "strbuf.h"
  18. #include <string.h>
  19. #include <stdlib.h>
  20. #define STRING_BLOCK_SIZE 64
  21. /* ------------------------------------------------------------------------- */
  22. char *strbuf_release(strbuf_t *buf)
  23. {
  24. char *r = buf->string;
  25. memset(buf, 0, sizeof(strbuf_t));
  26. return(r);
  27. }
  28. /* ------------------------------------------------------------------------- */
  29. void strbuf_append(strbuf_t *buf, const char *text)
  30. {
  31. static const size_t mask = ~(STRING_BLOCK_SIZE - 1);
  32. size_t len = strlen(text);
  33. size_t newlen = buf->length + len + 1; /* add 1 for NUL */
  34. if(newlen > buf->capacity)
  35. {
  36. buf->capacity = (newlen + (STRING_BLOCK_SIZE - 1)) & mask;
  37. buf->string = (char *)realloc(buf->string, buf->capacity);
  38. }
  39. strcpy(buf->string + buf->length, text);
  40. buf->length += len;
  41. }
  42. /* ------------------------------------------------------------------------- */
  43. /* eof */