feat: (str) str_new_*, str_free

This commit is contained in:
thetek 2023-02-12 18:36:44 +01:00
parent d13172d535
commit 1b4bc3619a
2 changed files with 68 additions and 0 deletions

19
lib/inc/str.h Normal file
View File

@ -0,0 +1,19 @@
#ifndef CUTILS_STR_H_
#define CUTILS_STR_H_
#include <stddef.h>
typedef struct
{
char *str;
size_t len;
size_t cap;
} str_t;
void str_new (str_t *str);
void str_new_cap (str_t *str, size_t want_cap);
void str_new_from (str_t *str, const char *src);
void str_new_from_len (str_t *str, const char *src, size_t len);
void str_free (str_t *str);
#endif // CUTILS_STR_H_

49
lib/str.c Normal file
View File

@ -0,0 +1,49 @@
#include "str.h"
#include <stdlib.h>
#include <string.h>
#include "common.h"
#define STR_MIN_ALLOC 64
void
str_new (str_t *str)
{
str->str = smalloc (STR_MIN_ALLOC * sizeof (char));
str->len = 0;
str->cap = STR_MIN_ALLOC;
}
void
str_new_cap (str_t *str, size_t want_cap)
{
size_t cap;
cap = max (next_pow_of_two (want_cap), STR_MIN_ALLOC);
str->str = smalloc (cap);
str->len = 0;
str->cap = cap;
}
inline void
str_new_from (str_t *str, const char *src)
{
str_new_from_len (str, src, strlen (src));
}
void
str_new_from_len (str_t *str, const char *src, size_t len)
{
size_t cap;
cap = max (next_pow_of_two (len + 1), STR_MIN_ALLOC);
str->str = smalloc (cap * sizeof (char));
str->len = len;
str->cap = cap;
strcpy (str->str, src);
}
inline void
str_free (str_t *str)
{
free (str->str);
}