2023-07-03 14:58:09 +03:00
|
|
|
#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)
|
|
|
|
{
|
2023-07-03 20:52:50 +03:00
|
|
|
size_t i;
|
|
|
|
for (i = 0; i < buffer->size; ++i) {
|
2023-07-03 14:58:09 +03:00
|
|
|
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)
|
|
|
|
{
|
2023-07-04 18:39:14 +03:00
|
|
|
if (buffer) free(buffer->buf);
|
2023-07-03 14:58:09 +03:00
|
|
|
}
|