/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_itoa.c                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: hulamy <marvin@42.fr>                      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2019/11/25 13:59:01 by hulamy            #+#    #+#             */
/*   Updated: 2020/02/19 15:44:04 by hulamy           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

/**
 * Converts a long integer to its string representation and stores it in a pre-allocated buffer.
 *
 * @param nbr      The long integer to convert.
 * @param buffer   The buffer to store the resulting string. Must be pre-allocated.
 * @param buff_len  The size of the buffer.
 *                 Must be at least as large as the length of the number (including sign).
 *
 * @return         The buffer (if successful), or NULL if the buffer is too small or invalid.
 */

#include "libft.h"

char *ft_itoa_static(long int nbr, char *buffer, size_t buff_len)
{
	int is_negative;
	const char *min_str;
	size_t min_len;
	size_t i;

	if (buffer == NULL || buff_len == 0)
	{
		return NULL; // Invalid buffer or length
	}

	// Handle LONG_MIN separately
	if (nbr == LONG_MIN)
	{
		min_str = "-9223372036854775808";
		min_len = ft_strlen(min_str);
		if (buff_len < min_len)
		{
			return NULL; // Buffer too small for LONG_MIN
		}
		i = 0;
		while (i < min_len)
		{
			buffer[i] = min_str[i];
			i++;
		}
		buffer[min_len] = '\0'; // Null-terminate
		return buffer;
	}

	// Determine if the number is negative
	is_negative = nbr < 0;
	nbr = ft_labs(nbr);

	// Write the null terminator at the end
	buffer[buff_len - 1] = '\0';

	// Write the digits in reverse order
	i = buff_len - 2;
	do
	{
		buffer[i] = (nbr % 10) + '0';
		nbr /= 10;
		i--;
	} while (nbr != 0);

	// Add the negative sign if needed
	if (is_negative)
	{
		buffer[0] = '-';
	}

	return buffer;
}
