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

#include "common/membuild.h"
#include "common/path.h"

bool sfdo_membuild_setup(struct sfdo_membuild *membuild, size_t cap) {
	*membuild = (struct sfdo_membuild){
		.cap = cap,
	};
	if (cap > 0) {
		membuild->data = malloc(cap);
		if (membuild->data == NULL) {
			return false;
		}
	} else {
		membuild->data = NULL;
	}
	return true;
}

void sfdo_membuild_add(
		struct sfdo_membuild *membuild, const struct sfdo_string *items, size_t n_items) {
	for (size_t i = 0; i < n_items; i++) {
		const struct sfdo_string *item = &items[i];
		memcpy(&membuild->data[membuild->len], item->data, item->len);
		membuild->len += item->len;
	}
}

void sfdo_membuild_add_path_segment(struct sfdo_membuild *membuild, const char *data, size_t len) {
	memcpy(&membuild->data[membuild->len], data, len);
	membuild->len += len;
	if (sfdo_path_needs_extra_slash(data, len)) {
		membuild->data[membuild->len++] = '/';
	}
}

size_t sfdo_membuild_nulterm(struct sfdo_membuild *membuild) {
	size_t diff = membuild->len - membuild->last_nulterm_len;
	membuild->data[membuild->len++] = '\0';
	membuild->last_nulterm_len = membuild->len;
	return diff;
}
