simple-discuss/src/string_buffer.c
2023-07-03 14:58:09 +03:00

54 lines
962 B
C

#include <stdlib.h>
#include "string_buffer.h"
/* TODO: better solution instead of abort */
void
sb_add_char(StringBuffer *buffer, char c)
{
if (buffer->size == buffer->capacity) {
buffer->capacity = 2 * buffer->capacity + 1;
if (!(buffer->buf = realloc(buffer->buf, buffer->capacity))) {
abort();
}
}
buffer->buf[buffer->size++] = c;
}
void
sb_add_string(StringBuffer *buffer, const char *str)
{
char c;
while ((c = *(str++))) {
sb_add_char(buffer, c);
}
}
size_t
sb_length(const StringBuffer *buffer)
{
return buffer->size;
}
void
sb_to_c_str(const StringBuffer *buffer, char *str)
{
for (size_t i = 0; i < buffer->size; ++i) {
str[i] = buffer->buf[i];
}
str[buffer->size] = '\0';
}
void
sb_init_empty(StringBuffer *buffer)
{
buffer->buf = NULL;
buffer->size = 0;
buffer->capacity = 0;
}
void
sb_free(StringBuffer *buffer)
{
free(buffer->buf);
}