1ecbd8afbapt#include "config.h"
2ecbd8afbapt
3ecbd8afbapt#if HAVE_STRTONUM
4ecbd8afbapt
5ecbd8afbaptint dummy;
6ecbd8afbapt
7ecbd8afbapt#else
8ecbd8afbapt
9ecbd8afbapt/*	$Id: compat_strtonum.c,v 1.1 2015/02/16 14:56:22 schwarze Exp $	*/
10ecbd8afbapt/*	$OpenBSD: strtonum.c,v 1.7 2013/04/17 18:40:58 tedu Exp $	*/
11ecbd8afbapt
12ecbd8afbapt/*
13ecbd8afbapt * Copyright (c) 2004 Ted Unangst and Todd Miller
14ecbd8afbapt * All rights reserved.
15ecbd8afbapt *
16ecbd8afbapt * Permission to use, copy, modify, and distribute this software for any
17ecbd8afbapt * purpose with or without fee is hereby granted, provided that the above
18ecbd8afbapt * copyright notice and this permission notice appear in all copies.
19ecbd8afbapt *
20ecbd8afbapt * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
21ecbd8afbapt * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
22ecbd8afbapt * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
23ecbd8afbapt * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
24ecbd8afbapt * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
25ecbd8afbapt * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
26ecbd8afbapt * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27ecbd8afbapt */
28ecbd8afbapt
29ecbd8afbapt#include <errno.h>
30ecbd8afbapt#include <limits.h>
31ecbd8afbapt#include <stdlib.h>
32ecbd8afbapt
33ecbd8afbapt#define	INVALID		1
34ecbd8afbapt#define	TOOSMALL	2
35ecbd8afbapt#define	TOOLARGE	3
36ecbd8afbapt
37ecbd8afbaptlong long
38ecbd8afbaptstrtonum(const char *numstr, long long minval, long long maxval,
39ecbd8afbapt    const char **errstrp)
40ecbd8afbapt{
41ecbd8afbapt	long long ll = 0;
42ecbd8afbapt	int error = 0;
43ecbd8afbapt	char *ep;
44ecbd8afbapt	struct errval {
45ecbd8afbapt		const char *errstr;
46ecbd8afbapt		int err;
47ecbd8afbapt	} ev[4] = {
48ecbd8afbapt		{ NULL,		0 },
49ecbd8afbapt		{ "invalid",	EINVAL },
50ecbd8afbapt		{ "too small",	ERANGE },
51ecbd8afbapt		{ "too large",	ERANGE },
52ecbd8afbapt	};
53ecbd8afbapt
54ecbd8afbapt	ev[0].err = errno;
55ecbd8afbapt	errno = 0;
56ecbd8afbapt	if (minval > maxval) {
57ecbd8afbapt		error = INVALID;
58ecbd8afbapt	} else {
59ecbd8afbapt		ll = strtoll(numstr, &ep, 10);
60ecbd8afbapt		if (numstr == ep || *ep != '\0')
61ecbd8afbapt			error = INVALID;
62ecbd8afbapt		else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
63ecbd8afbapt			error = TOOSMALL;
64ecbd8afbapt		else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
65ecbd8afbapt			error = TOOLARGE;
66ecbd8afbapt	}
67ecbd8afbapt	if (errstrp != NULL)
68ecbd8afbapt		*errstrp = ev[error].errstr;
69ecbd8afbapt	errno = ev[error].err;
70ecbd8afbapt	if (error)
71ecbd8afbapt		ll = 0;
72ecbd8afbapt
73ecbd8afbapt	return (ll);
74ecbd8afbapt}
75ecbd8afbapt
76ecbd8afbapt#endif /* !HAVE_STRTONUM */
77