summaryrefslogtreecommitdiff
path: root/src/string_to_uint.c
blob: 6fbd8c1686f8f7a07c4b915bddf22750991acb83 (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
/*
 * Copyright (c) 2001-2021 The strace developers.
 * All rights reserved.
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <errno.h>
#include <stdlib.h>
#include <string.h>

#include "string_to_uint.h"

long long
string_to_uint_ex(const char *const str, char **const endptr,
		  const unsigned long long max_val,
		  const char *const accepted_ending)
{
	char *end;
	long long val;

	if (!*str)
		return -1;

	errno = 0;
	val = strtoll(str, &end, 10);

	if (str == end || val < 0 || (unsigned long long) val > max_val
	    || (val == LLONG_MAX && errno == ERANGE))
		return -1;

	if (*end && (!accepted_ending || !strchr(accepted_ending, *end)))
		return -1;

	if (endptr)
		*endptr = end;

	return val;
}