diff -r 000000000000 -r 707d51fedbe0 gclib/gcstring.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/gclib/gcstring.c Tue Jan 24 23:57:11 2012 +0000 @@ -0,0 +1,90 @@ +#include +#include +#include +#include +#include +#include + +/* + * Strings which manage their own memory + */ + +String *string_new(const char *init) +{ + String *string=mem_new(String,1); + if (!init) + init=""; + string->len=strlen(init); + string->alloc=string->len+1; + string->str=str_dup(init); + return string; +} + +/* + * Free a string and either return the contents (if free_segment is FALSE) + * or free the contents as well and return NULL (if free_segment is TRUE). + */ +char *string_free(String *string,boolean free_segment) +{ + char *retval; + if (free_segment) + { + mem_free(string->str); + retval=NULL; + } + else + retval=string->str; + mem_free(string); + return retval; +} + +/* + * Append a byte to string. + */ +void string_append_c(String *string,char c) +{ + if (string->len+1==string->alloc) + { + string->alloc*=2; + string->str=mem_renew(char,string->str,string->alloc); + } + string->str[string->len++]=c; + string->str[string->len]='\0'; +} + +/* + * Append len bytes from s to string. len may be passed as <0 if s is + * a nul-terminated string of unknown length. + */ +void string_append_len(String *string,const char *s,ssize_t len) +{ + if (len<0) + len=strlen(s); + if (string->len+len>=string->alloc) + { + while (string->len+len>=string->alloc) + string->alloc*=2; + string->str=mem_renew(char,string->str,string->alloc); + } + memcpy(string->str+string->len,s,len); + string->len+=len; + string->str[string->len]='\0'; +} + +/* + * Sets the length of a String. If the length is less than the current length, + * the string will be truncated. If the length is greater than the current + * length, the contents of the newly added area are undefined. (However, as + * always, string->str[string->len] will be a nul byte.) + */ +void string_set_size(String *string,size_t len) +{ + if (len>=string->alloc) + { + while (len>=string->alloc) + string->alloc*=2; + string->str=mem_renew(char,string->str,string->alloc); + } + string->len=len; + string->str[string->len]='\0'; +}