Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2014
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.67 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. enum stringType {
  6.     stringTypeFixed,
  7.     stringTypeHeap
  8. };
  9.  
  10. typedef struct _string {
  11.     char *buffer;
  12.     int length;
  13.     int bufSize;
  14.     enum stringType type;
  15. } *string;
  16.  
  17. int LowestPow2(int min) {
  18.     int result = 1;
  19.     while(result < min) {
  20.         result *= 2;
  21.     }
  22.     return result;
  23. }
  24.  
  25. void string_CheckSize(string str, int minSize) {
  26.     if(str->bufSize >= minSize) {
  27.         return;
  28.     }
  29.     if(str->type == stringTypeFixed) {
  30.         printf("size limit exceeded for fixed string");
  31.         exit(1);
  32.     }
  33.     str->bufSize = LowestPow2(minSize);
  34.     str->buffer = realloc(str->buffer, str->bufSize);
  35. }
  36.  
  37. void string_copy(string dest, string source) {
  38.     string_CheckSize(dest, source->length);
  39.     memcpy(dest->buffer, source->buffer, source->length);
  40.     dest->length = source->length;
  41. }
  42.  
  43. void string_print(string str) {
  44.     for(int i = 0; i < str->length; i++) {
  45.         fputc(str->buffer[i], stdout);
  46.     }
  47. }
  48.  
  49.  
  50. #define STACK_STRING(size) &(struct _string) { \
  51.     .type = stringTypeFixed, .buffer = (char[size]) {}, .length = 0, .bufSize = size \
  52. }
  53.  
  54. #define HEAP_STRING(size) &(struct _string) { \
  55.     .type = stringTypeHeap, .buffer = malloc(size), .length = 0, .bufSize = size \
  56. }
  57.  
  58. #define STRING_LITERAL(literal) &(struct _string) { \
  59.     .type = stringTypeFixed, .buffer = literal, .length = strlen(literal), .bufSize = strlen(literal) + 1 \
  60. }
  61.  
  62. int main() {
  63.     string stackString = STACK_STRING(32);
  64.     string_copy(stackString, STRING_LITERAL("hello pls\n"));
  65.  
  66.     string heapString = HEAP_STRING(2);
  67.     string_copy(heapString, STRING_LITERAL("This string is too long and will trigger a realloc.\n"));
  68.  
  69.     string_print(stackString);
  70.     string_print(heapString);
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement