strbuf.c 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /* strbuf - String buffer routines
  2. *
  3. * Copyright (c) 2010-2012 Mark Pulford <mark@kyne.com.au>
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining
  6. * a copy of this software and associated documentation files (the
  7. * "Software"), to deal in the Software without restriction, including
  8. * without limitation the rights to use, copy, modify, merge, publish,
  9. * distribute, sublicense, and/or sell copies of the Software, and to
  10. * permit persons to whom the Software is furnished to do so, subject to
  11. * the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be
  14. * included in all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  19. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  20. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  21. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  22. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include <stdarg.h>
  27. #include <string.h>
  28. #include "strbuf.h"
  29. static void die(const char *fmt, ...)
  30. {
  31. va_list arg;
  32. va_start(arg, fmt);
  33. vfprintf(stderr, fmt, arg);
  34. va_end(arg);
  35. fprintf(stderr, "\n");
  36. exit(-1);
  37. }
  38. void strbuf_init(strbuf_t *s, int len)
  39. {
  40. int size;
  41. if (len <= 0)
  42. size = STRBUF_DEFAULT_SIZE;
  43. else
  44. size = len + 1; /* \0 terminator */
  45. s->buf = NULL;
  46. s->size = size;
  47. s->length = 0;
  48. s->increment = STRBUF_DEFAULT_INCREMENT;
  49. s->dynamic = 0;
  50. s->reallocs = 0;
  51. s->debug = 0;
  52. s->buf = malloc(size);
  53. if (!s->buf)
  54. die("Out of memory");
  55. strbuf_ensure_null(s);
  56. }
  57. strbuf_t *strbuf_new(int len)
  58. {
  59. strbuf_t *s;
  60. s = malloc(sizeof(strbuf_t));
  61. if (!s)
  62. die("Out of memory");
  63. strbuf_init(s, len);
  64. /* Dynamic strbuf allocation / deallocation */
  65. s->dynamic = 1;
  66. return s;
  67. }
  68. void strbuf_set_increment(strbuf_t *s, int increment)
  69. {
  70. /* Increment > 0: Linear buffer growth rate
  71. * Increment < -1: Exponential buffer growth rate */
  72. if (increment == 0 || increment == -1)
  73. die("BUG: Invalid string increment");
  74. s->increment = increment;
  75. }
  76. static inline void debug_stats(strbuf_t *s)
  77. {
  78. if (s->debug) {
  79. fprintf(stderr, "strbuf(%lx) reallocs: %d, length: %d, size: %d\n",
  80. (long)s, s->reallocs, s->length, s->size);
  81. }
  82. }
  83. /* If strbuf_t has not been dynamically allocated, strbuf_free() can
  84. * be called any number of times strbuf_init() */
  85. void strbuf_free(strbuf_t *s)
  86. {
  87. debug_stats(s);
  88. if (s->buf) {
  89. free(s->buf);
  90. s->buf = NULL;
  91. }
  92. if (s->dynamic)
  93. free(s);
  94. }
  95. char *strbuf_free_to_string(strbuf_t *s, int *len)
  96. {
  97. char *buf;
  98. debug_stats(s);
  99. strbuf_ensure_null(s);
  100. buf = s->buf;
  101. if (len)
  102. *len = s->length;
  103. if (s->dynamic)
  104. free(s);
  105. return buf;
  106. }
  107. static int calculate_new_size(strbuf_t *s, int len)
  108. {
  109. int reqsize, newsize;
  110. if (len <= 0)
  111. die("BUG: Invalid strbuf length requested");
  112. /* Ensure there is room for optional NULL termination */
  113. reqsize = len + 1;
  114. /* If the user has requested to shrink the buffer, do it exactly */
  115. if (s->size > reqsize)
  116. return reqsize;
  117. newsize = s->size;
  118. if (s->increment < 0) {
  119. /* Exponential sizing */
  120. while (newsize < reqsize)
  121. newsize *= -s->increment;
  122. } else {
  123. /* Linear sizing */
  124. newsize = ((newsize + s->increment - 1) / s->increment) * s->increment;
  125. }
  126. return newsize;
  127. }
  128. /* Ensure strbuf can handle a string length bytes long (ignoring NULL
  129. * optional termination). */
  130. void strbuf_resize(strbuf_t *s, int len)
  131. {
  132. int newsize;
  133. newsize = calculate_new_size(s, len);
  134. if (s->debug > 1) {
  135. fprintf(stderr, "strbuf(%lx) resize: %d => %d\n",
  136. (long)s, s->size, newsize);
  137. }
  138. s->size = newsize;
  139. s->buf = realloc(s->buf, s->size);
  140. if (!s->buf)
  141. die("Out of memory");
  142. s->reallocs++;
  143. }
  144. void strbuf_append_string(strbuf_t *s, const char *str)
  145. {
  146. int space, i;
  147. space = strbuf_empty_length(s);
  148. for (i = 0; str[i]; i++) {
  149. if (space < 1) {
  150. strbuf_resize(s, s->length + 1);
  151. space = strbuf_empty_length(s);
  152. }
  153. s->buf[s->length] = str[i];
  154. s->length++;
  155. space--;
  156. }
  157. }
  158. /* strbuf_append_fmt() should only be used when an upper bound
  159. * is known for the output string. */
  160. void strbuf_append_fmt(strbuf_t *s, int len, const char *fmt, ...)
  161. {
  162. va_list arg;
  163. int fmt_len;
  164. strbuf_ensure_empty_length(s, len);
  165. va_start(arg, fmt);
  166. fmt_len = vsnprintf(s->buf + s->length, len, fmt, arg);
  167. va_end(arg);
  168. if (fmt_len < 0)
  169. die("BUG: Unable to convert number"); /* This should never happen.. */
  170. s->length += fmt_len;
  171. }
  172. /* strbuf_append_fmt_retry() can be used when the there is no known
  173. * upper bound for the output string. */
  174. void strbuf_append_fmt_retry(strbuf_t *s, const char *fmt, ...)
  175. {
  176. va_list arg;
  177. int fmt_len, try;
  178. int empty_len;
  179. /* If the first attempt to append fails, resize the buffer appropriately
  180. * and try again */
  181. for (try = 0; ; try++) {
  182. va_start(arg, fmt);
  183. /* Append the new formatted string */
  184. /* fmt_len is the length of the string required, excluding the
  185. * trailing NULL */
  186. empty_len = strbuf_empty_length(s);
  187. /* Add 1 since there is also space to store the terminating NULL. */
  188. fmt_len = vsnprintf(s->buf + s->length, empty_len + 1, fmt, arg);
  189. va_end(arg);
  190. if (fmt_len <= empty_len)
  191. break; /* SUCCESS */
  192. if (try > 0)
  193. die("BUG: length of formatted string changed");
  194. strbuf_resize(s, s->length + fmt_len);
  195. }
  196. s->length += fmt_len;
  197. }
  198. /* vi:ai et sw=4 ts=4:
  199. */