3 #include <gclib/gcstring.h>
4 #include <gclib/types.h>
6 #include <gclib/strfuncs.h>
9 * Strings which manage their own memory
12 String *string_new(const char *init)
14 String *string=mem_new(String,1);
17 string->len=strlen(init);
18 string->alloc=string->len+1;
19 string->str=str_dup(init);
24 * Free a string and either return the contents (if free_segment is FALSE)
25 * or free the contents as well and return NULL (if free_segment is TRUE).
27 char *string_free(String *string,boolean free_segment)
32 mem_free(string->str);
42 * Append a byte to string.
44 void string_append_c(String *string,char c)
46 if (string->len+1==string->alloc)
49 string->str=mem_renew(char,string->str,string->alloc);
51 string->str[string->len++]=c;
52 string->str[string->len]='\0';
56 * Append len bytes from s to string. len may be passed as <0 if s is
57 * a nul-terminated string of unknown length.
59 void string_append_len(String *string,const char *s,ssize_t len)
63 if (string->len+len>=string->alloc)
65 while (string->len+len>=string->alloc)
67 string->str=mem_renew(char,string->str,string->alloc);
69 memcpy(string->str+string->len,s,len);
71 string->str[string->len]='\0';
75 * Sets the length of a String. If the length is less than the current length,
76 * the string will be truncated. If the length is greater than the current
77 * length, the contents of the newly added area are undefined. (However, as
78 * always, string->str[string->len] will be a nul byte.)
80 void string_set_size(String *string,size_t len)
82 if (len>=string->alloc)
84 while (len>=string->alloc)
86 string->str=mem_renew(char,string->str,string->alloc);
89 string->str[string->len]='\0';