71 lines
1.2 KiB
C
71 lines
1.2 KiB
C
|
#include "str.h"
|
||
|
|
||
|
void str_init(struct str* self)
|
||
|
{
|
||
|
assert(self);
|
||
|
self->size = 0;
|
||
|
self->capacity = 0;
|
||
|
self->value = NULL;
|
||
|
}
|
||
|
|
||
|
void str_free(struct str* self)
|
||
|
{
|
||
|
assert(self);
|
||
|
free(self->value);
|
||
|
self->value = NULL;
|
||
|
self->size = 0;
|
||
|
self->capacity = 0;
|
||
|
}
|
||
|
|
||
|
void str_push(struct str* self, char element)
|
||
|
{
|
||
|
assert(self);
|
||
|
|
||
|
if (self->capacity == 0)
|
||
|
{
|
||
|
self->capacity = 1;
|
||
|
self->value = calloc(self->capacity, sizeof(char));
|
||
|
}
|
||
|
|
||
|
if (self->size + 2 >= self->capacity)
|
||
|
{
|
||
|
self->capacity *= 2;
|
||
|
char* data = realloc(self->value, sizeof(char) * self->capacity);
|
||
|
assert(data);
|
||
|
self->value = data;
|
||
|
}
|
||
|
|
||
|
self->value[self->size] = element;
|
||
|
self->size++;
|
||
|
self->value[self->size] = '\0';
|
||
|
}
|
||
|
|
||
|
void str_extend(struct str* self, char const* rhs)
|
||
|
{
|
||
|
assert(self);
|
||
|
assert(rhs);
|
||
|
|
||
|
size_t sz = strlen(rhs);
|
||
|
|
||
|
for (size_t i=0; i<sz; i++)
|
||
|
{
|
||
|
str_push(self, rhs[i]);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void str_format(struct str* self, char const* format, ...)
|
||
|
{
|
||
|
assert(self);
|
||
|
assert(format);
|
||
|
char buffer[MK_STRLEN];
|
||
|
|
||
|
va_list lst;
|
||
|
va_start(lst, format);
|
||
|
|
||
|
vsnprintf(buffer, MK_STRLEN, format, lst);
|
||
|
|
||
|
va_end(lst);
|
||
|
|
||
|
str_extend(self, buffer);
|
||
|
}
|