0d487dd9be2dce33fbc458da46f70cde59ccf760
[oweals/busybox.git] / libbb / xatonum.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * ascii-to-numbers implementations for busybox
4  *
5  * Copyright (C) 2003  Manuel Novoa III  <mjn3@codepoet.org>
6  *
7  * Licensed under GPLv2, see file LICENSE in this tarball for details.
8  */
9
10 #include "libbb.h"
11
12 #define type long long
13 #define xstrtou(rest) xstrtoull##rest
14 #define xstrto(rest) xstrtoll##rest
15 #define xatou(rest) xatoull##rest
16 #define xato(rest) xatoll##rest
17 #define XSTR_UTYPE_MAX ULLONG_MAX
18 #define XSTR_TYPE_MAX LLONG_MAX
19 #define XSTR_TYPE_MIN LLONG_MIN
20 #define XSTR_STRTOU strtoull
21 #include "xatonum_template.c"
22 #undef type
23 #undef xstrtou
24 #undef xstrto
25 #undef xatou
26 #undef xato
27 #undef XSTR_UTYPE_MAX
28 #undef XSTR_TYPE_MAX
29 #undef XSTR_TYPE_MIN
30 #undef XSTR_STRTOU
31
32 #if ULONG_MAX != ULLONG_MAX
33 #define type long
34 #define xstrtou(rest) xstrtoul##rest
35 #define xstrto(rest) xstrtol##rest
36 #define xatou(rest) xatoul##rest
37 #define xato(rest) xatol##rest
38 #define XSTR_UTYPE_MAX ULONG_MAX
39 #define XSTR_TYPE_MAX LONG_MAX
40 #define XSTR_TYPE_MIN LONG_MIN
41 #define XSTR_STRTOU strtoul
42 #include "xatonum_template.c"
43 #undef type
44 #undef xstrtou
45 #undef xstrto
46 #undef xatou
47 #undef xato
48 #undef XSTR_UTYPE_MAX
49 #undef XSTR_TYPE_MAX
50 #undef XSTR_TYPE_MIN
51 #undef XSTR_STRTOU
52 #endif
53
54 #if UINT_MAX != ULONG_MAX
55 extern inline unsigned bb_strtoui(const char *str, char **end, int b)
56 {
57         unsigned long v = strtoul(str, end, b);
58         if (v > UINT_MAX) {
59                 errno = ERANGE;
60                 return UINT_MAX;
61         }
62         return v;
63 }
64 #define type int
65 #define xstrtou(rest) xstrtou##rest
66 #define xstrto(rest) xstrtoi##rest
67 #define xatou(rest) xatou##rest
68 #define xato(rest) xatoi##rest
69 #define XSTR_UTYPE_MAX UINT_MAX
70 #define XSTR_TYPE_MAX INT_MAX
71 #define XSTR_TYPE_MIN INT_MIN
72 /* libc has no strtoui, so we need to create/use our own */
73 #define XSTR_STRTOU bb_strtoui
74 #include "xatonum_template.c"
75 #undef type
76 #undef xstrtou
77 #undef xstrto
78 #undef xatou
79 #undef xato
80 #undef XSTR_UTYPE_MAX
81 #undef XSTR_TYPE_MAX
82 #undef XSTR_TYPE_MIN
83 #undef XSTR_STRTOU
84 #endif
85
86 /* A few special cases */
87
88 int xatoi_u(const char *numstr)
89 {
90         return xatou_range(numstr, 0, INT_MAX);
91 }
92
93 uint32_t xatou32(const char *numstr)
94 {
95         return xatoul_range(numstr, 0, 0xffffffff);
96 }
97
98 uint16_t xatou16(const char *numstr)
99 {
100         return xatou_range(numstr, 0, 0xffff);
101 }