/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_itoa.c                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: thrieg <thrieg@student.42mulhouse.fr>      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/10/15 15:29:15 by thrieg            #+#    #+#             */
/*   Updated: 2025/02/16 19:03:49 by thrieg           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "libft.h"

static void	ft_swap(char *a, char *b)
{
	char	c;

	c = *a;
	*a = *b;
	*b = c;
}

static void	ft_reverse_buff(char buff[11], size_t(len))
{
	size_t	index;

	if (buff[0] == '-')
	{
		index = 1;
		while ((len / 2) >= index)
		{
			ft_swap(&buff[index], &buff[len - index]);
			index++;
		}
	}
	else
	{
		index = 0;
		while (((len - 1) / 2) >= index)
		{
			ft_swap(&buff[index], &buff[len - index - 1]);
			index++;
		}
	}
}

static char	*subfunction(char *ret, char buff[11], size_t buff_len)
{
	ft_reverse_buff(buff, buff_len);
	ft_memcpy(ret, (const void *)buff, buff_len);
	ret[buff_len] = '\0';
	return (ret);
}

//only works if an int is 32 bits, I'll maybe change it later for the bonuses
char	*ft_itoa(int n)
{
	char	*ret;
	char	buff[11];
	size_t	buff_len;

	if (n <= -2147483648)
		return (ft_strdup("-2147483648"));
	if (n == 0)
		return (ft_strdup("0"));
	buff_len = 0;
	if (n < 0)
	{
		buff[0] = '-';
		buff_len++;
		n *= -1;
	}
	while (n > 0)
	{
		buff[buff_len++] = (n % 10) + '0';
		n /= 10;
	}
	ret = malloc(sizeof(char) * (buff_len) + 1);
	if (!ret)
		return (NULL);
	return (subfunction(ret, buff, buff_len));
}
