1755a16fdes/*	$OpenBSD: strtonum.c,v 1.6 2004/08/03 19:38:01 millert Exp $	*/
2755a16fdes
3755a16fdes/*
4755a16fdes * Copyright (c) 2004 Ted Unangst and Todd Miller
5755a16fdes * All rights reserved.
6755a16fdes *
7755a16fdes * Permission to use, copy, modify, and distribute this software for any
8755a16fdes * purpose with or without fee is hereby granted, provided that the above
9755a16fdes * copyright notice and this permission notice appear in all copies.
10755a16fdes *
11755a16fdes * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12755a16fdes * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13755a16fdes * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14755a16fdes * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15755a16fdes * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16755a16fdes * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17755a16fdes * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18755a16fdes */
19755a16fdes
204485037des/* OPENBSD ORIGINAL: lib/libc/stdlib/strtonum.c */
214485037des
22755a16fdes#include "includes.h"
232f35ce4des
24755a16fdes#ifndef HAVE_STRTONUM
252f35ce4des#include <stdlib.h>
26755a16fdes#include <limits.h>
272f35ce4des#include <errno.h>
28755a16fdes
29755a16fdes#define INVALID 	1
30755a16fdes#define TOOSMALL 	2
31755a16fdes#define TOOLARGE 	3
32755a16fdes
33755a16fdeslong long
34755a16fdesstrtonum(const char *numstr, long long minval, long long maxval,
35755a16fdes    const char **errstrp)
36755a16fdes{
37755a16fdes	long long ll = 0;
38755a16fdes	char *ep;
39755a16fdes	int error = 0;
40755a16fdes	struct errval {
41755a16fdes		const char *errstr;
42755a16fdes		int err;
43755a16fdes	} ev[4] = {
44755a16fdes		{ NULL,		0 },
45755a16fdes		{ "invalid",	EINVAL },
46755a16fdes		{ "too small",	ERANGE },
47755a16fdes		{ "too large",	ERANGE },
48755a16fdes	};
49755a16fdes
50755a16fdes	ev[0].err = errno;
51755a16fdes	errno = 0;
52755a16fdes	if (minval > maxval)
53755a16fdes		error = INVALID;
54755a16fdes	else {
55755a16fdes		ll = strtoll(numstr, &ep, 10);
56755a16fdes		if (numstr == ep || *ep != '\0')
57755a16fdes			error = INVALID;
58755a16fdes		else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
59755a16fdes			error = TOOSMALL;
60755a16fdes		else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
61755a16fdes			error = TOOLARGE;
62755a16fdes	}
63755a16fdes	if (errstrp != NULL)
64755a16fdes		*errstrp = ev[error].errstr;
65755a16fdes	errno = ev[error].err;
66755a16fdes	if (error)
67755a16fdes		ll = 0;
68755a16fdes
69755a16fdes	return (ll);
70755a16fdes}
71755a16fdes
72755a16fdes#endif /* HAVE_STRTONUM */
73