Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- enum stringType {
- stringTypeFixed,
- stringTypeHeap
- };
- typedef struct _string {
- char *buffer;
- int length;
- int bufSize;
- enum stringType type;
- } *string;
- int LowestPow2(int min) {
- int result = 1;
- while(result < min) {
- result *= 2;
- }
- return result;
- }
- void string_CheckSize(string str, int minSize) {
- if(str->bufSize >= minSize) {
- return;
- }
- if(str->type == stringTypeFixed) {
- printf("size limit exceeded for fixed string");
- exit(1);
- }
- str->bufSize = LowestPow2(minSize);
- str->buffer = realloc(str->buffer, str->bufSize);
- }
- void string_copy(string dest, string source) {
- string_CheckSize(dest, source->length);
- memcpy(dest->buffer, source->buffer, source->length);
- dest->length = source->length;
- }
- void string_print(string str) {
- for(int i = 0; i < str->length; i++) {
- fputc(str->buffer[i], stdout);
- }
- }
- #define STACK_STRING(size) &(struct _string) { \
- .type = stringTypeFixed, .buffer = (char[size]) {}, .length = 0, .bufSize = size \
- }
- #define HEAP_STRING(size) &(struct _string) { \
- .type = stringTypeHeap, .buffer = malloc(size), .length = 0, .bufSize = size \
- }
- #define STRING_LITERAL(literal) &(struct _string) { \
- .type = stringTypeFixed, .buffer = literal, .length = strlen(literal), .bufSize = strlen(literal) + 1 \
- }
- int main() {
- string stackString = STACK_STRING(32);
- string_copy(stackString, STRING_LITERAL("hello pls\n"));
- string heapString = HEAP_STRING(2);
- string_copy(heapString, STRING_LITERAL("This string is too long and will trigger a realloc.\n"));
- string_print(stackString);
- string_print(heapString);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement