2 83f0f95a 2022-09-29 op * Copyright (c) 2004 Ted Unangst and Todd Miller
3 83f0f95a 2022-09-29 op * All rights reserved.
5 83f0f95a 2022-09-29 op * Permission to use, copy, modify, and distribute this software for any
6 83f0f95a 2022-09-29 op * purpose with or without fee is hereby granted, provided that the above
7 83f0f95a 2022-09-29 op * copyright notice and this permission notice appear in all copies.
9 83f0f95a 2022-09-29 op * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 83f0f95a 2022-09-29 op * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 83f0f95a 2022-09-29 op * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 83f0f95a 2022-09-29 op * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 83f0f95a 2022-09-29 op * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 83f0f95a 2022-09-29 op * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 83f0f95a 2022-09-29 op * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 83f0f95a 2022-09-29 op #include <errno.h>
19 83f0f95a 2022-09-29 op #include <limits.h>
20 83f0f95a 2022-09-29 op #include <stdlib.h>
22 83f0f95a 2022-09-29 op #define INVALID 1
23 83f0f95a 2022-09-29 op #define TOOSMALL 2
24 83f0f95a 2022-09-29 op #define TOOLARGE 3
27 83f0f95a 2022-09-29 op strtonum(const char *numstr, long long minval, long long maxval,
28 83f0f95a 2022-09-29 op const char **errstrp)
30 83f0f95a 2022-09-29 op long long ll = 0;
31 83f0f95a 2022-09-29 op int error = 0;
33 83f0f95a 2022-09-29 op struct errval {
34 83f0f95a 2022-09-29 op const char *errstr;
38 83f0f95a 2022-09-29 op { "invalid", EINVAL },
39 83f0f95a 2022-09-29 op { "too small", ERANGE },
40 83f0f95a 2022-09-29 op { "too large", ERANGE },
43 83f0f95a 2022-09-29 op ev[0].err = errno;
45 83f0f95a 2022-09-29 op if (minval > maxval) {
46 83f0f95a 2022-09-29 op error = INVALID;
48 83f0f95a 2022-09-29 op ll = strtoll(numstr, &ep, 10);
49 83f0f95a 2022-09-29 op if (numstr == ep || *ep != '\0')
50 83f0f95a 2022-09-29 op error = INVALID;
51 83f0f95a 2022-09-29 op else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
52 83f0f95a 2022-09-29 op error = TOOSMALL;
53 83f0f95a 2022-09-29 op else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
54 83f0f95a 2022-09-29 op error = TOOLARGE;
56 83f0f95a 2022-09-29 op if (errstrp != NULL)
57 83f0f95a 2022-09-29 op *errstrp = ev[error].errstr;
58 83f0f95a 2022-09-29 op errno = ev[error].err;