s_grow.c 974 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include "String.h"
  12. /* grow a String's allocation by at least `incr' bytes */
  13. extern String*
  14. s_grow(String *s, int incr)
  15. {
  16. char *cp;
  17. int size;
  18. if(s->fixed)
  19. sysfatal("s_grow of constant string");
  20. s = s_unique(s);
  21. /*
  22. * take a larger increment to avoid mallocing too often
  23. */
  24. size = s->end-s->base;
  25. if(size/2 < incr)
  26. size += incr;
  27. else
  28. size += size/2;
  29. cp = realloc(s->base, size);
  30. if (cp == 0)
  31. sysfatal("s_grow: %r");
  32. s->ptr = (s->ptr - s->base) + cp;
  33. s->end = cp + size;
  34. s->base = cp;
  35. return s;
  36. }