Created
October 21, 2023 06:13
-
-
Save devansh42/b452cf7f2e6bfad4274fa686da89bbbf to your computer and use it in GitHub Desktop.
Cool Dynamic String Implementation in C inspired by Redis SDS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "stdio.h" | |
#include "string.h" | |
#include "stdlib.h" | |
// HEADER_SIZE would help us to move pointer to and fro | |
// usually, sizeof(unsigned int) is 4 bytes | |
// so this will be 8 bytes | |
#define HEADER_SIZE 2 * sizeof(unsigned int) | |
struct DynamicStr | |
{ | |
unsigned int len; | |
unsigned int capacity; | |
char data[]; | |
}; | |
typedef struct DynamicStr DStr; // To make our lives easier | |
const DStr* get_dstr(const char *d); | |
char *newString(const char *data) | |
{ | |
DStr *new_str; | |
int len = strlen(data); | |
int struct_size = HEADER_SIZE + len + 1; // Reserving memory of length, | |
new_str = (DStr *)malloc(struct_size); // Allocate memory for struct | |
new_str->len = len; | |
new_str->capacity = len; | |
memcpy(new_str->data, data, len); // Copy source string content to new string | |
new_str->data[len + 1] = '\0'; // Adding a null terminator | |
return new_str->data; | |
} | |
unsigned int len(const char *d) | |
{ | |
return get_dstr(d)->len; | |
} | |
const DStr* get_dstr(const char *d) | |
{ | |
DStr *dstr = (DStr *)(d - HEADER_SIZE); // This moves str pointer HEADER_SIZE slots back | |
// so that we can get the starting position of DStr | |
return dstr; | |
} | |
int main() | |
{ | |
char *new_str = newString("Hello World"); | |
printf("Dynamic String: %s", new_str); | |
printf("Dynamic String Length: %u", len(new_str)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment