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