at work
This commit is contained in:
51
clib/cstring.c
Normal file
51
clib/cstring.c
Normal file
@@ -0,0 +1,51 @@
|
||||
|
||||
/*
|
||||
*
|
||||
* Copyright 2023 Oleg Borodin <borodin@unix7.org>
|
||||
*
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include <cstring.h>
|
||||
|
||||
#define INIT_CAPA 64
|
||||
|
||||
/* String container */
|
||||
void* cstring_init(cstring_t* str) {
|
||||
str->data = malloc(INIT_CAPA + 1);
|
||||
if (str->data == NULL) return NULL;
|
||||
memset(str->data, '\0', INIT_CAPA + 1);
|
||||
str->capa = INIT_CAPA;
|
||||
str->size = 0;
|
||||
return str->data;
|
||||
}
|
||||
|
||||
|
||||
void* cstring_append(cstring_t* str, char* add) {
|
||||
size_t addsize = strlen(add);
|
||||
size_t newsize = str->size + addsize;
|
||||
if (newsize >= str->capa) {
|
||||
size_t newcapa = newsize + 1;
|
||||
char* newstr = realloc(str->data, newcapa);
|
||||
if (newstr == NULL) return NULL;
|
||||
str->data = newstr;
|
||||
str->capa = newcapa;
|
||||
}
|
||||
strcpy(&(str->data[str->size]), add);
|
||||
str->data[newsize + 1] = '\0';
|
||||
str->size = newsize;
|
||||
return str->data;
|
||||
}
|
||||
|
||||
char* cstring_getref(cstring_t* str) {
|
||||
return str->data;
|
||||
}
|
||||
|
||||
|
||||
void cstring_destroy(cstring_t* str) {
|
||||
if (str == NULL) return;
|
||||
free(str->data);
|
||||
}
|
||||
Reference in New Issue
Block a user