3 /* vs_alloc(), VS_ADDCH()
5 /* auto-resizing string library
9 /* #include "vstring.h"
11 /* struct vstring *vs_alloc(len)
14 /* int VS_ADDCH(vs, wp, ch)
15 /* struct vstring *vs;
19 /* char *vs_strcpy(vp, dst, src)
20 /* struct vstring *vp;
24 /* These functions and macros implement a small library for
25 /* arbitrary-length strings that grow automatically when
26 /* they fill up. The allocation strategy is such that there
27 /* will always be place for the terminating null character.
29 /* vs_alloc() allocates storage for a variable-length string
30 /* of at least "len" bytes.
32 /* VS_ADDCH() adds a character to a variable-length string
33 /* and automagically extends the string if fills up.
34 /* \fIvs\fP is a pointer to a vstring structure; \fIwp\fP
35 /* the current write position in the corresponding character
36 /* array; \fIch\fP the character value to be written.
37 /* Note that VS_ADDCH() is a macro that evaluates some
38 /* arguments more than once.
40 /* vs_strcpy() appends a null-terminated string to a variable-length
41 /* string. \fIsrc\fP provides the data to be copied; \fIvp\fP is the
42 /* target, and \fIdst\fP the current write position within the target.
43 /* The result is null-terminated. The return value is the new write
46 /* VS_ADDCH() returns zero if it was unable to dynamically
49 /* vs_alloc() returns a null pointer in case of problems.
51 /* vs_strcpy() returns a null pointer if the request failed.
53 /* Auto-resizing may change the address of the string data in
54 /* a vstring structure. Beware of dangling pointers.
57 /* Eindhoven University of Technology
58 /* Department of Mathematics and Computer Science
59 /* Den Dolech 2, P.O. Box 513, 5600 MB Eindhoven, The Netherlands
66 static char vstring_sccsid[] = "@(#) vstring.c 1.3 92/01/15 21:53:06";
70 extern char *malloc();
71 extern char *realloc();
73 /* Application-specific stuff */
77 /* vs_alloc - initial string allocation */
79 struct vstring *vs_alloc(len)
82 register struct vstring *vp;
85 || (vp = (struct vstring *) malloc(sizeof(struct vstring))) == 0
86 || (vp->str = malloc(len)) == 0)
88 vp->last = vp->str + len - 1;
92 /* vs_realloc - extend string, update write pointer */
94 char *vs_realloc(vp, cp)
95 register struct vstring *vp;
98 int where = cp - vp->str;
99 int len = vp->last - vp->str + 1;
101 if ((vp->str = realloc(vp->str, len *= 2)) == 0)
103 vp->last = vp->str + len - 1;
104 return (vp->str + where);
107 /* vs_strcpy - copy string */
109 char *vs_strcpy(vp, dst, src)
110 register struct vstring *vp;
115 if (VS_ADDCH(vp, dst, *src) == 0)