aboutsummaryrefslogtreecommitdiff
path: root/src/libString/s_grow.c
blob: 5cf2a1414ceb01f50e3e2e2990ce7df75d15bc26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <u.h>
#include <libc.h>
#include "libString.h"

/* grow a String's allocation by at least `incr' bytes */
extern String*
s_grow(String *s, int incr)	
{
	char *cp;
	int size;

	if(s->fixed)
		sysfatal("s_grow of constant string");
	s = s_unique(s);

	/*
	 *  take a larger increment to avoid mallocing too often
	 */
	size = s->end-s->base;
	if(size/2 < incr)
		size += incr;
	else
		size += size/2;

	cp = realloc(s->base, size);
	if (cp == 0)
		sysfatal("s_grow: %r");
	s->ptr = (s->ptr - s->base) + cp;
	s->end = cp + size;
	s->base = cp;

	return s;
}