/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_int_utils.c                                     :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: thrieg <thrieg@student.42mulhouse.fr>      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/10/30 10:11:17 by alier             #+#    #+#             */
/*   Updated: 2025/02/16 19:03:36 by thrieg           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include <stdlib.h>
#include <errno.h>
#include "libft.h"

size_t	i_drep_len(int n)
{
	size_t	len;

	len = 0;
	if (n < 0)
		len++;
	while (1)
	{
		len++;
		n /= 10;
		if (n == 0)
			break ;
	}
	return (len);
}

/*
 * Reimplementation of libc atoi() but sets `errno` to `ERANGE` if an
 * domain error is encountered (overflow, underflow) or `EINVAL` if
 * no digits characters or invalid characters at end).
 */
int	ft_atoie(const char *nptr)
{
	int	n;
	int	mult;

	n = 0;
	mult = -1;
	while (ft_isspace(*nptr))
		nptr++;
	if (*nptr == '+' || *nptr == '-')
	{
		if (*nptr == '-')
			mult = 1;
		nptr++;
	}
	if (!ft_isdigit(*nptr))
		errno = EINVAL;
	while (ft_isdigit(*nptr))
	{
		n = safe_int_sub(safe_int_mul(n, 10), *nptr - '0');
		nptr++;
	}
	if (*nptr != '\0')
		errno = EINVAL;
	return (safe_int_mul(n, mult));
}

unsigned int	ft_max_uint(size_t len, unsigned int a[len])
{
	size_t			i;
	unsigned int	max;

	i = 0;
	max = 0;
	while (i < len)
	{
		if (a[i] > max)
			max = a[i];
		i++;
	}
	return (max);
}
