Skip to content

Instantly share code, notes, and snippets.

@Pagliacii
Created September 14, 2023 09:15
Show Gist options
  • Save Pagliacii/a2d25af0847e2f8e313dca8457f2078b to your computer and use it in GitHub Desktop.
Save Pagliacii/a2d25af0847e2f8e313dca8457f2078b to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char *sds;
typedef struct String {
int len;
int free;
char data[];
} String;
#define GET_STRING_LEN(data_ptr) (*((int *)((sds)(data_ptr) - sizeof(int) * 2)))
#define GET_STRING_FREE(data_ptr) (*((int *)((sds)(data_ptr) - sizeof(int))))
#define SET_STRING_LEN(data_ptr, new_len) \
do { \
int *len_ptr = (int *)((char *)(data_ptr) - sizeof(int) - sizeof(int)); \
*len_ptr = (new_len); \
} while (0)
#define SET_STRING_FREE(data_ptr, new_free) \
do { \
int *free_ptr = (int *)((char *)(data_ptr) - sizeof(int)); \
*free_ptr = (new_free); \
} while (0)
#define GET_STRING_PTR(data_ptr) ((String *)((sds)(data_ptr) - sizeof(int) * 2))
#define FREE_STRING(data_ptr) \
do { \
String *str_ptr = (String *)((sds)(data_ptr) - sizeof(int) * 2); \
free(str_ptr); \
} while (0)
sds new_string(int length) {
String *str = (String *)malloc(sizeof(String) + length + 1);
str->len = length;
str->free = 0;
return str->data;
}
sds init_string(const char *s) {
sds string = new_string(strlen(s));
snprintf(string, strlen(s) + 1, "%s", s);
return string;
}
sds append_string(sds a, const char *b) {
int length = strlen(b);
String *str = GET_STRING_PTR(a);
if (str->free < length) {
str->free += str->len + str->free + length;
str = realloc(str, sizeof(String) + str->len + str->free + length + 1);
} else {
str->free -= length;
}
strcpy(str->data + str->len, b);
str->len += length;
return str->data;
}
int main() {
sds string = init_string("Hello");
printf("[0] SDS: %s, Length: %d, Free: %d, strlen: %lu\n", string,
GET_STRING_LEN(string), GET_STRING_FREE(string), strlen(string));
string = append_string(string, " world");
printf("[1] SDS: %s, Length: %d, Free: %d, strlen: %lu\n", string,
GET_STRING_LEN(string), GET_STRING_FREE(string), strlen(string));
string = append_string(string, "!");
printf("[2] SDS: %s, Length: %d, Free: %d, strlen: %lu\n", string,
GET_STRING_LEN(string), GET_STRING_FREE(string), strlen(string));
string = append_string(string, " Hello world!");
printf("[3] SDS: %s, Length: %d, Free: %d, strlen: %lu\n", string,
GET_STRING_LEN(string), GET_STRING_FREE(string), strlen(string));
FREE_STRING(string);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment