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