view src/str.c @ 5:a6ab6d9c0dac

readme: fix typos, str: remove outdated note our allocator is actually fairly smart now :)
author Paper <mrpapersonic@gmail.com>
date Mon, 25 Dec 2023 16:26:46 -0500
parents c2408abb258a
children 0c98b46eaf73
line wrap: on
line source

#include <stdlib.h>
#include <string.h>
#include "str.h"

int EDL_internal_string_init(EDL_internal_string* str) {
    if (!str)
        return 0;

    str->size = 0;
    str->capacity = 0;
    str->data = NULL;
    return 1;
}

int EDL_internal_string_allocate(EDL_internal_string* str, size_t new_capacity) {
    if (new_capacity == str->capacity)
        return 1; // nothing to do

    str->data = realloc(str->data, new_capacity * sizeof(char));
	if (!str->data)
		return 0;

	if (new_capacity > str->capacity)
		memset(&str->data[str->capacity], 0, (new_capacity - str->capacity) * sizeof(char));

	str->capacity = new_capacity;

	return 1;
}

int EDL_internal_string_append(EDL_internal_string* str, const char* data, const size_t length) {
    {
        size_t capacity = 1;
        while (capacity < (str->size + length + 1))
            capacity *= 2;

        if (capacity < str->capacity || !EDL_internal_string_allocate(str, capacity))
            return 0;
    }

    strncat(str->data, data, length);
    str->size += length;

    return 1;
}

void EDL_internal_string_free(EDL_internal_string* str) {
    if (str->data)
        free(str->data);
}