s_grow.c 562 B

12345678910111213141516171819202122232425262728293031323334
  1. #include <u.h>
  2. #include <libc.h>
  3. #include "String.h"
  4. /* grow a String's allocation by at least `incr' bytes */
  5. extern String*
  6. s_grow(String *s, int incr)
  7. {
  8. char *cp;
  9. int size;
  10. if(s->fixed)
  11. sysfatal("s_grow of constant string");
  12. s = s_unique(s);
  13. /*
  14. * take a larger increment to avoid mallocing too often
  15. */
  16. size = s->end-s->base;
  17. if(size/2 < incr)
  18. size += incr;
  19. else
  20. size += size/2;
  21. cp = realloc(s->base, size);
  22. if (cp == 0)
  23. sysfatal("s_grow: %r");
  24. s->ptr = (s->ptr - s->base) + cp;
  25. s->end = cp + size;
  26. s->base = cp;
  27. return s;
  28. }