Advertisement
VictorCacciari

SmartStr

Feb 21st, 2012
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.27 KB | None | 0 0
  1. typedef struct SmartStr_st
  2. {
  3.     char*   buff; //the actual string,
  4.     int size; //the number of allocated bytes in our buffer,
  5.     int len;  //the length of the data inside the buffer.
  6. } SmartStr;
  7.  
  8. /*
  9.     Just some simple constructors, the returned object has 'size'
  10.     bytes allocated for the buffer and length = 0.
  11.     (or strlen(text)+1 bytes allocated)
  12. */
  13. SmartStr*   smart_str_empty_new(int size);
  14. SmartStr*   smart_str_new(char* text);
  15.  
  16. /*
  17.     our realloc function
  18.     ps.: this is declared and defined in the implementation ('.c') file since
  19.     it's a private function.
  20.  
  21.     This function will expand the buffer. The final size will be 'str->size' + 'space'.
  22. */
  23. static void smart_str_expand(SmartStr* str, int space)
  24. {
  25. char* aux = (char*)malloc(sizeof(char)*(str->size + space));
  26.  
  27.     strcpy(aux, str->buffer);
  28.     free(str->buffer);
  29.     str->buffer = aux;
  30.     str->size += space;
  31. }
  32.  
  33. /*
  34.     And finally, the append functions:
  35. */
  36. SmartStr* smart_str_raw_append(SmartStr* a, char* b, int blength)
  37. {
  38.     if (a->size < (a->len + blength))
  39.         smart_str_expand(a, a->length + blength);
  40.  
  41.     strcat(a->buffer, b);
  42.     return a; //The return is just for compatibility with other string libraries.
  43. }
  44.  
  45. SmartStr* smart_str_append(SmartStr* a, SmartStr* b)
  46. {
  47.     return smart_str_raw_append(a, b->buffer, b->len);
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement