#include "minishell.h"

char *ms_strdup(const char *s)
{
	char *out;
	size_t len;

	if (!s)
		return NULL;
	len = strlen(s);
	out = (char *)malloc(len + 1);
	if (!out)
		return NULL;
	memcpy(out, s, len);
	out[len] = '\0';
	return out;
}

char *ms_strndup(const char *s, size_t n)
{
	char *out;
	if (!s)
		return NULL;
	out = (char *)malloc(n + 1);
	if (!out)
		return NULL;
	memcpy(out, s, n);
	out[n] = '\0';
	return out;
}

char *ms_substr(const char *s, size_t start, size_t len)
{
	size_t slen;
	if (!s)
		return NULL;
	slen = strlen(s);
	if (start >= slen)
		return ms_strdup("");
	if (start + len > slen)
		len = slen - start;
	return ms_strndup(s + start, len);
}

char *ms_strjoin(const char *a, const char *b)
{
	size_t la;
	size_t lb;
	char *out;

	if (!a || !b)
		return NULL;
	la = strlen(a);
	lb = strlen(b);
	out = (char *)malloc(la + lb + 1);
	if (!out)
		return NULL;
	memcpy(out, a, la);
	memcpy(out + la, b, lb);
	out[la + lb] = '\0';
	return out;
}

char *ms_strjoin3(const char *a, const char *b, const char *c)
{
	char *ab;
	char *abc;

	ab = ms_strjoin(a, b);
	if (!ab)
		return NULL;
	abc = ms_strjoin(ab, c);
	free(ab);
	return abc;
}

char *ms_itoa(int n)
{
	char buf[32];
	int i;
	int neg;
	long nb;

	nb = n;
	neg = (nb < 0);
	if (neg)
		nb = -nb;
	i = 30;
	buf[31] = '\0';
	if (nb == 0)
		buf[i--] = '0';
	while (nb > 0)
	{
		buf[i--] = (char)('0' + (nb % 10));
		nb /= 10;
	}
	if (neg)
		buf[i--] = '-';
	return ms_strdup(&buf[i + 1]);
}
