gclib/gcstring.c
author ali <ali@juiblex.co.uk>
Tue Jan 24 23:54:05 2012 +0000 (2012-01-24)
changeset 0 c2f4c0285180
permissions -rw-r--r--
Initial version
     1 #include <stdlib.h>
     2 #include <string.h>
     3 #include <gclib/gcstring.h>
     4 #include <gclib/types.h>
     5 #include <gclib/mem.h>
     6 #include <gclib/strfuncs.h>
     7 
     8 /*
     9  * Strings which manage their own memory
    10  */
    11 
    12 String *string_new(const char *init)
    13 {
    14     String *string=mem_new(String,1);
    15     if (!init)
    16 	init="";
    17     string->len=strlen(init);
    18     string->alloc=string->len+1;
    19     string->str=str_dup(init);
    20     return string;
    21 }
    22 
    23 /*
    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).
    26  */
    27 char *string_free(String *string,boolean free_segment)
    28 {
    29     char *retval;
    30     if (free_segment)
    31     {
    32 	mem_free(string->str);
    33 	retval=NULL;
    34     }
    35     else
    36 	retval=string->str;
    37     mem_free(string);
    38     return retval;
    39 }
    40 
    41 /*
    42  * Append a byte to string.
    43  */
    44 void string_append_c(String *string,char c)
    45 {
    46     if (string->len+1==string->alloc)
    47     {
    48 	string->alloc*=2;
    49 	string->str=mem_renew(char,string->str,string->alloc);
    50     }
    51     string->str[string->len++]=c;
    52     string->str[string->len]='\0';
    53 }
    54 
    55 /*
    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.
    58  */
    59 void string_append_len(String *string,const char *s,ssize_t len)
    60 {
    61     if (len<0)
    62 	len=strlen(s);
    63     if (string->len+len>=string->alloc)
    64     {
    65 	while (string->len+len>=string->alloc)
    66 	    string->alloc*=2;
    67 	string->str=mem_renew(char,string->str,string->alloc);
    68     }
    69     memcpy(string->str+string->len,s,len);
    70     string->len+=len;
    71     string->str[string->len]='\0';
    72 }
    73 
    74 /*
    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.)
    79  */
    80 void string_set_size(String *string,size_t len)
    81 {
    82     if (len>=string->alloc)
    83     {
    84 	while (len>=string->alloc)
    85 	    string->alloc*=2;
    86 	string->str=mem_renew(char,string->str,string->alloc);
    87     }
    88     string->len=len;
    89     string->str[string->len]='\0';
    90 }