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

char *sw_str_concat(char *a, char *b) {
	char *str;
	u32 len_a, len_b;

	len_a = strlen(a);
	len_b = strlen(b);

	str = malloc(len_a + len_b + 1);
	memcpy(str, a, len_a);
	memcpy(str + len_a, b, len_b);
	str[len_a + len_b] = 0;

	return str;
}

char *sw_str_concat3(char *a, char *b, char *c) {
	char *str;
	u32 len_a, len_b, len_c;

	len_a = strlen(a);
	len_b = strlen(b);
	len_c = strlen(c);

	str = malloc(len_a + len_b + len_c + 1);
	memcpy(str, a, len_a);
	memcpy(str + len_a, b, len_b);
	memcpy(str + len_a + len_b, c, len_c);
	str[len_a + len_b + len_c] = 0;

	return str;
}

char *sw_str_concat4(char *a, char *b, char *c, char *d) {
	char *str;
	u32 len_a, len_b, len_c, len_d;

	len_a = strlen(a);
	len_b = strlen(b);
	len_c = strlen(c);
	len_d = strlen(d);

	str = malloc(len_a + len_b + len_c + len_d + 1);
	memcpy(str, a, len_a);
	memcpy(str + len_a, b, len_b);
	memcpy(str + len_a + len_b, c, len_c);
	memcpy(str + len_a + len_b + len_c, d, len_d);
	str[len_a + len_b + len_c + len_d] = 0;

	return str;
}

char *sw_str_dup(char *str) {
	char *out;
	u32 len;

	len = strlen(str) + 1;

	out = malloc(len);
	memcpy(out, str, len);
	return out;
}

i32 sw_str_index(char *str, char *substr) {
	i32 i;

	for(i = 0; *str; ++i) {
		if(sw_str_startswith(str, substr)) {
			return i;
		}
		++str;
	}
	return -1;
}

void sw_str_split2(char *str, char *split, char **out1, char **out2) {
	i32 idx;
	i32 idx2;

	idx = sw_str_index(str, split);

	if(idx == -1) {
		*out1 = 0;
		*out2 = 0;
		return;
	}

	idx2 = idx + strlen(split);

	*out1 = sw_str_sub(str, 0, idx);
	*out2 = sw_str_sub(str, idx2, strlen(str) - idx2);
}

bool sw_str_startswith(char *str, char *start) {
	while(*start) {
		if(*str == 0 || *str != *start) {
			return false;
		}
		++str;
		++start;
	}
	return true;
}

char *sw_str_sub(char *str, u32 start, u32 len) {
	char *sub;

	len = u32_min(len, strlen(str));

	sub = malloc(len + 1);
	memcpy(sub, str + start, len);
	sub[len] = 0;

	return sub;
}
