view src/str.c @ 14:2d7c810a1ac2 default tip

*: misc. cleanup
author Paper <paper@paper.us.eu.org>
date Fri, 03 May 2024 22:40:28 -0400
parents 0cc2555db371
children
line wrap: on
line source

#include "str.h"

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

/* rudimentary string functions so the code in edl.c isn't
 * as painful to read */

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) {
    if (str->capacity == 0)
        if (!EDL_internal_string_allocate(str, 1))
            return 0;

    /* increase capacity if needed */
    if (str->size + length + 1 >= str->capacity) {
        size_t capacity = 1;
        while (capacity < (str->size + length + 1))
            capacity *= 2;

        if (!EDL_internal_string_allocate(str, capacity))
            return 0;
    }

    memcpy(&str->data[str->size], data, length);
    str->size += length;

    return length;
}

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