summaryrefslogtreecommitdiff
path: root/src/stdlib/strtoimax.c
blob: aeb0397f9ef944c0a0204da44f2853e7104567a3 (plain) (blame)
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
#include <inttypes.h>
#include <errno.h>
#include <ctype.h>

intmax_t strtoimax(const char *s1, char **p, int base)
{
	const unsigned char *s = (const void *)s1;
	int sign = 0;
	uintmax_t x;

	/* Initial whitespace */
	for (; isspace(*s); s++);

	/* Optional sign */
	if (*s == '-') sign = *s++;
	else if (*s == '+') s++;

	x = strtoumax((const void *)s, p, base);
	if (x > INTMAX_MAX) {
		if (!sign || -x != INTMAX_MIN)
			errno = ERANGE;
		return sign ? INTMAX_MIN : INTMAX_MAX;
	}
	return sign ? -x : x;
}