ccm/lib/str.c

70 lines
1.1 KiB
C
Raw Normal View History

2024-03-18 17:20:40 +00:00
#include "str.h"
void str_init(str_t* self)
{
assert(self);
self->size = 0;
self->capacity = 0;
self->value = NULL;
}
void str_free(str_t* self)
{
assert(self);
if (self->value)
{
free(self->value);
}
}
ssize_t str_find(str_t* self, char c)
{
assert(self);
for (size_t i=0; i<self->size; i++)
{
if (self->value[i] == c)
{
return i;
}
}
return -1;
}
void str_push(str_t* self, char c)
{
assert(self);
if (self->value == NULL)
{
self->capacity = 1;
self->value = malloc(sizeof(char) * self->capacity);
}
if (self->size + 2 >= self->capacity)
{
self->capacity *= 2;
self->value = realloc(
self->value,
sizeof(char) * self->capacity
);
}
self->value[self->size] = c;
self->size++;
self->value[self->size] = '\0';
}
void str_push_cstr(str_t* self, char const* rhs)
{
assert(self);
assert(rhs);
for (size_t i=0; i<strlen(rhs); i++)
{
str_push(self, rhs[i]);
}
}