]>
Commit | Line | Data |
---|---|---|
8a3ff1aa | 1 | /* $OpenBSD: strtonum.c,v 1.6 2004/08/03 19:38:01 millert 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 | ||
f6d4fb87 | 20 | /* OPENBSD ORIGINAL: lib/libc/stdlib/strtonum.c */ |
21 | ||
8a3ff1aa | 22 | #include "includes.h" |
23 | #ifndef HAVE_STRTONUM | |
24 | #include <limits.h> | |
fec71b2f | 25 | #include <errno.h> |
8a3ff1aa | 26 | |
27 | #define INVALID 1 | |
28 | #define TOOSMALL 2 | |
29 | #define TOOLARGE 3 | |
30 | ||
31 | long long | |
32 | strtonum(const char *numstr, long long minval, long long maxval, | |
33 | const char **errstrp) | |
34 | { | |
35 | long long ll = 0; | |
36 | char *ep; | |
37 | int error = 0; | |
38 | struct errval { | |
39 | const char *errstr; | |
40 | int err; | |
41 | } ev[4] = { | |
42 | { NULL, 0 }, | |
43 | { "invalid", EINVAL }, | |
44 | { "too small", ERANGE }, | |
45 | { "too large", ERANGE }, | |
46 | }; | |
47 | ||
48 | ev[0].err = errno; | |
49 | errno = 0; | |
50 | if (minval > maxval) | |
51 | error = INVALID; | |
52 | else { | |
53 | ll = strtoll(numstr, &ep, 10); | |
54 | if (numstr == ep || *ep != '\0') | |
55 | error = INVALID; | |
56 | else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval) | |
57 | error = TOOSMALL; | |
58 | else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval) | |
59 | error = TOOLARGE; | |
60 | } | |
61 | if (errstrp != NULL) | |
62 | *errstrp = ev[error].errstr; | |
63 | errno = ev[error].err; | |
64 | if (error) | |
65 | ll = 0; | |
66 | ||
67 | return (ll); | |
68 | } | |
69 | ||
70 | #endif /* HAVE_STRTONUM */ |