19ec6603andre/*-
29ec6603andre * Copyright (c) 2004 Ted Unangst and Todd Miller
39ec6603andre * All rights reserved.
49ec6603andre *
59ec6603andre * Permission to use, copy, modify, and distribute this software for any
69ec6603andre * purpose with or without fee is hereby granted, provided that the above
79ec6603andre * copyright notice and this permission notice appear in all copies.
89ec6603andre *
99ec6603andre * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
109ec6603andre * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
119ec6603andre * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
129ec6603andre * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
139ec6603andre * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
149ec6603andre * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
159ec6603andre * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
169ec6603andre *
172db0fe8pfg *	$OpenBSD: strtonum.c,v 1.7 2013/04/17 18:40:58 tedu Exp $
189ec6603andre */
199ec6603andre
209ec6603andre#include <sys/cdefs.h>
219ec6603andre__FBSDID("$FreeBSD$");
229ec6603andre
239ec6603andre#include <errno.h>
249ec6603andre#include <limits.h>
259ec6603andre#include <stdlib.h>
269ec6603andre
272db0fe8pfg#define	INVALID		1
282db0fe8pfg#define	TOOSMALL	2
292db0fe8pfg#define	TOOLARGE	3
309ec6603andre
319ec6603andrelong long
329ec6603andrestrtonum(const char *numstr, long long minval, long long maxval,
339ec6603andre    const char **errstrp)
349ec6603andre{
359ec6603andre	long long ll = 0;
369ec6603andre	int error = 0;
372db0fe8pfg	char *ep;
389ec6603andre	struct errval {
399ec6603andre		const char *errstr;
409ec6603andre		int err;
419ec6603andre	} ev[4] = {
429ec6603andre		{ NULL,		0 },
439ec6603andre		{ "invalid",	EINVAL },
449ec6603andre		{ "too small",	ERANGE },
459ec6603andre		{ "too large",	ERANGE },
469ec6603andre	};
479ec6603andre
489ec6603andre	ev[0].err = errno;
499ec6603andre	errno = 0;
502db0fe8pfg	if (minval > maxval) {
519ec6603andre		error = INVALID;
522db0fe8pfg	} else {
539ec6603andre		ll = strtoll(numstr, &ep, 10);
5493d3ecbache		if (errno == EINVAL || numstr == ep || *ep != '\0')
559ec6603andre			error = INVALID;
569ec6603andre		else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
579ec6603andre			error = TOOSMALL;
589ec6603andre		else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
599ec6603andre			error = TOOLARGE;
609ec6603andre	}
619ec6603andre	if (errstrp != NULL)
629ec6603andre		*errstrp = ev[error].errstr;
639ec6603andre	errno = ev[error].err;
649ec6603andre	if (error)
659ec6603andre		ll = 0;
669ec6603andre
679ec6603andre	return (ll);
689ec6603andre}
69