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