#include <stddef.h>

#include "str.h"

static bool intToIndex(String string, int i, size_t *out_index) {
	int val = 0;
	bool is_ok = true;
	if (i >= 0) {
		val = i;
	} else {
		val = string.size + 1 + i;
	}

	if (val < 0) {
		val = 0;
		is_ok = false;
	} else if (val > string.size) {
		val = string.size;
		is_ok = false;
	}

	*out_index = val;
	return is_ok;
}

bool StringSub(String string, int start, int end, String *out_substr) {

	size_t start_index = 0;
	bool start_ok = intToIndex(string, start, &start_index);
	size_t end_index = 0;
	bool end_ok = intToIndex(string, end, &end_index);

	if (string.size == 0 || start_index >= end_index) {
		out_substr->size=0;
		out_substr->buffer=NULL;
		return false;
	}

	out_substr->buffer = &string.buffer[start_index];
	out_substr->size = end_index - start_index;

	return start_ok && end_ok;
}
