1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/gclib/gcstring.c Tue Jan 24 23:54:05 2012 +0000
1.3 @@ -0,0 +1,90 @@
1.4 +#include <stdlib.h>
1.5 +#include <string.h>
1.6 +#include <gclib/gcstring.h>
1.7 +#include <gclib/types.h>
1.8 +#include <gclib/mem.h>
1.9 +#include <gclib/strfuncs.h>
1.10 +
1.11 +/*
1.12 + * Strings which manage their own memory
1.13 + */
1.14 +
1.15 +String *string_new(const char *init)
1.16 +{
1.17 + String *string=mem_new(String,1);
1.18 + if (!init)
1.19 + init="";
1.20 + string->len=strlen(init);
1.21 + string->alloc=string->len+1;
1.22 + string->str=str_dup(init);
1.23 + return string;
1.24 +}
1.25 +
1.26 +/*
1.27 + * Free a string and either return the contents (if free_segment is FALSE)
1.28 + * or free the contents as well and return NULL (if free_segment is TRUE).
1.29 + */
1.30 +char *string_free(String *string,boolean free_segment)
1.31 +{
1.32 + char *retval;
1.33 + if (free_segment)
1.34 + {
1.35 + mem_free(string->str);
1.36 + retval=NULL;
1.37 + }
1.38 + else
1.39 + retval=string->str;
1.40 + mem_free(string);
1.41 + return retval;
1.42 +}
1.43 +
1.44 +/*
1.45 + * Append a byte to string.
1.46 + */
1.47 +void string_append_c(String *string,char c)
1.48 +{
1.49 + if (string->len+1==string->alloc)
1.50 + {
1.51 + string->alloc*=2;
1.52 + string->str=mem_renew(char,string->str,string->alloc);
1.53 + }
1.54 + string->str[string->len++]=c;
1.55 + string->str[string->len]='\0';
1.56 +}
1.57 +
1.58 +/*
1.59 + * Append len bytes from s to string. len may be passed as <0 if s is
1.60 + * a nul-terminated string of unknown length.
1.61 + */
1.62 +void string_append_len(String *string,const char *s,ssize_t len)
1.63 +{
1.64 + if (len<0)
1.65 + len=strlen(s);
1.66 + if (string->len+len>=string->alloc)
1.67 + {
1.68 + while (string->len+len>=string->alloc)
1.69 + string->alloc*=2;
1.70 + string->str=mem_renew(char,string->str,string->alloc);
1.71 + }
1.72 + memcpy(string->str+string->len,s,len);
1.73 + string->len+=len;
1.74 + string->str[string->len]='\0';
1.75 +}
1.76 +
1.77 +/*
1.78 + * Sets the length of a String. If the length is less than the current length,
1.79 + * the string will be truncated. If the length is greater than the current
1.80 + * length, the contents of the newly added area are undefined. (However, as
1.81 + * always, string->str[string->len] will be a nul byte.)
1.82 + */
1.83 +void string_set_size(String *string,size_t len)
1.84 +{
1.85 + if (len>=string->alloc)
1.86 + {
1.87 + while (len>=string->alloc)
1.88 + string->alloc*=2;
1.89 + string->str=mem_renew(char,string->str,string->alloc);
1.90 + }
1.91 + string->len=len;
1.92 + string->str[string->len]='\0';
1.93 +}