libite 2.6.1
strtonum.c
Go to the documentation of this file.
1/* $OpenBSD: strtonum.c,v 1.7 2013/04/17 18:40:58 tedu Exp $ */
2
3/*
4 * Copyright (c) 2004 Ted Unangst and Todd Miller
5 * All rights reserved.
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
27
28#include <errno.h>
29#include <limits.h>
30#include <stdlib.h>
31
32#ifndef strtonum
33#define INVALID 1
34#define TOOSMALL 2
35#define TOOLARGE 3
36
37#ifndef LLONG_MAX
38# define LLONG_MAX 0x7fffffffffffffffLL
39#endif
40
41#ifndef LLONG_MIN
42# define LLONG_MIN (-0x7fffffffffffffffLL - 1)
43#endif
44
74long long
75strtonum(const char *numstr, long long minval, long long maxval,
76 const char **errstrp)
77{
78 long long ll = 0;
79 int error = 0;
80 char *ep;
81 struct errval {
82 const char *errstr;
83 int err;
84 } ev[4] = {
85 { NULL, 0 },
86 { "invalid", EINVAL },
87 { "too small", ERANGE },
88 { "too large", ERANGE },
89 };
90
91 ev[0].err = errno;
92 errno = 0;
93 if (minval > maxval) {
94 error = INVALID;
95 } else {
96 ll = strtoll(numstr, &ep, 10);
97 if (errno == EINVAL || numstr == ep || *ep != '\0')
98 error = INVALID;
99 else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
100 error = TOOSMALL;
101 else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
102 error = TOOLARGE;
103 }
104 if (errstrp != NULL)
105 *errstrp = ev[error].errstr;
106 errno = ev[error].err;
107 if (error)
108 ll = 0;
109
110 return (ll);
111}
112#endif
#define TOOSMALL
Definition strtonum.c:34
#define LLONG_MAX
Definition strtonum.c:38
long long strtonum(const char *numstr, long long minval, long long maxval, const char **errstrp)
Definition strtonum.c:75
#define TOOLARGE
Definition strtonum.c:35
#define INVALID
Definition strtonum.c:33
#define LLONG_MIN
Definition strtonum.c:42