aboutsummaryrefslogtreecommitdiff
path: root/src/str/ft_strtol.c
blob: 447f1af0ff5133b20922bfdfd40b1172e8e1b853 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_strtol.c                                        :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/01/15 10:26:45 by cacharle          #+#    #+#             */
/*   Updated: 2020/01/15 11:39:34 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "libft.h"

#define STRTOL_STD_BASE "0123456789abcdefghijklmnopqrstuvwxyz"

static int	strtol_handle_base(int base, const char **str)
{
	if (base != 16 && base != 0)
		return (base);
	if (base == 16 && **str == '0' && (*str)[1] == 'x')
	{
		*str += 2;
		return (base);
	}
	if (**str == '0')
	{
		(*str)++;
		if (**str == 'x')
		{
			(*str)++;
			return (16);
		}
		else
			return (8);
	}
	return (10);
}

static long	errno_return(int err)
{
	errno = err;
	return (0);
}

/*
** If there is no digits doesn't put str in endptr like the original,
** instead it puts the address of the char after spaces and sign.
** Too much lines and annoyance, I can't be bothered.
*/

long		ft_strtol(const char *str, char **endptr, int base)
{
	t_bool		is_negative;
	long long	nb;
	char		base_str[37];

	if (base > 36)
		return (errno_return(EINVAL));
	while (ft_isspace(*str))
		str++;
	is_negative = *str == '-' ? TRUE : FALSE;
	if (*str == '-' || *str == '+')
		str++;
	base = strtol_handle_base(base, &str);
	ft_strncpy(base_str, STRTOL_STD_BASE, base);
	nb = 0;
	while (ft_strchr(base_str, *str) != NULL)
	{
		nb *= base;
		nb += ft_strchr(base_str, ft_tolower(*str)) - base_str;
		if (((long)nb ^ (long)(nb / base)) < 0)
			return (errno_return(ERANGE));
	}
	if (endptr != NULL)
		*endptr = (char*)str;
	return (is_negative ? -nb : nb);
}