pss-total/lib/include/ns_str.h

61 lines
1.3 KiB
C
Raw Normal View History

2024-05-24 21:54:17 +00:00
#ifndef NS_STR_H
#define NS_STR_H
#include <assert.h>
#include <stdlib.h>
#include <string.h>
struct Str_T {
char *arr;
size_t len;
size_t cap;
};
typedef struct Str_T Str;
static void ns_str_init_empty(Str *nstr, size_t capactiy) {
nstr->len = 0;
nstr->cap = capactiy;
nstr->arr = calloc(nstr->cap, sizeof(char));
}
static void ns_str_push_char(Str *nstr, char c) {
if (nstr->len + 2 > nstr->cap) {
nstr->cap += 8;
nstr->arr = realloc(nstr->arr, nstr->cap * sizeof(char));
assert(nstr->arr != NULL);
}
nstr->arr[nstr->len] = c;
nstr->len++;
nstr->arr[nstr->len] = '\0';
}
static void ns_str_push(Str *nstr, char *str) {
size_t strlen_str = strlen(str);
if (nstr->len + strlen_str + 1 > nstr->cap) {
nstr->cap = nstr->len + strlen_str + 8;
nstr->arr = realloc(nstr->arr, nstr->cap * sizeof(char));
assert(nstr->arr != NULL);
}
strncpy(nstr->arr + nstr->len, str, nstr->cap - nstr->len);
nstr->len = nstr->len + strlen_str;
}
static void ns_str_set(Str *nstr, char *str) {
size_t strlen_str = strlen(str);
nstr->cap = strlen_str + 1;
nstr->arr = realloc(nstr->arr, nstr->cap * sizeof(char));
assert(nstr->arr != NULL);
strncpy(nstr->arr, str, nstr->cap);
nstr->len = strlen_str;
}
static void ns_str_destroy(Str *nstr) {
free(nstr->arr);
nstr->arr = NULL;
nstr->len = 0;
nstr->cap = 0;
}
#endif