add strtonum
[single-header-libcext.git] / strtonum.h
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
18 /* https://git.datadissipation.net */
19 #ifndef STRTONUM_H_
20 #define STRTONUM_H_ 1
21
22 #ifdef STRTONUM_INCLUDE_LIBC
23 #include <errno.h>
24 #include <limits.h>
25 #include <stdlib.h>
26 #endif /* STRTONUM_INCLUDE_LIBC */
27
28 #ifndef HAVE_STRTONUM
29 #define strtonum i_strtonum_
30 long long i_strtonum_(const char *numstr, long long minval, long long maxval,
31 const char **errstrp);
32 #endif /* !HAVE_STRTONUM */
33
34 #ifdef STRTONUM_IMPLEMENTATION
35 #define I_INVALID_ 1
36 #define I_TOOSMALL_ 2
37 #define I_TOOLARGE 3
38
39 long long
40 i_strtonum_(const char *numstr, long long minval, long long maxval,
41 const char **errstrp)
42 {
43 long long ll = 0;
44 int error = 0;
45 char *ep;
46 struct errval {
47 const char *errstr;
48 int err;
49 } ev[4] = {
50 { NULL, 0 },
51 { "invalid", EINVAL },
52 { "too small", ERANGE },
53 { "too large", ERANGE },
54 };
55
56 ev[0].err = errno;
57 errno = 0;
58 if (minval > maxval) {
59 error = I_INVALID_;
60 } else {
61 ll = strtoll(numstr, &ep, 10);
62 if (numstr == ep || *ep != '\0')
63 error = I_INVALID_;
64 else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
65 error = I_TOOSMALL_;
66 else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
67 error = I_TOOLARGE;
68 }
69 if (errstrp != NULL)
70 *errstrp = ev[error].errstr;
71 errno = ev[error].err;
72 if (error)
73 ll = 0;
74
75 return (ll);
76 }
77 #endif /* STRTONUM_IMPLEMENTATION */
78 #endif /* !STRTONUM_H_ */