Handle invalid suffixes and overflow independently, so that
[gnulib.git] / lib / xstrtol.c
1 /* A more useful interface to strtol.
2
3    Copyright (C) 1995, 1996, 1998, 1999, 2000, 2001, 2003 Free
4    Software Foundation, Inc.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software Foundation,
18    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 /* Written by Jim Meyering. */
21
22 #if HAVE_CONFIG_H
23 # include <config.h>
24 #endif
25
26 #ifndef __strtol
27 # define __strtol strtol
28 # define __strtol_t long int
29 # define __xstrtol xstrtol
30 # define STRTOL_T_MINIMUM LONG_MIN
31 # define STRTOL_T_MAXIMUM LONG_MAX
32 #endif
33
34 /* Some pre-ANSI implementations (e.g. SunOS 4)
35    need stderr defined if assertion checking is enabled.  */
36 #include <stdio.h>
37
38 #include <assert.h>
39 #include <ctype.h>
40 #include <stdlib.h>
41 #include <string.h>
42
43 #include <errno.h>
44 #ifndef errno
45 extern int errno;
46 #endif
47
48 #include <limits.h>
49
50 /* The extra casts work around common compiler bugs.  */
51 #define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
52 #define TYPE_MINIMUM(t) ((t) (TYPE_SIGNED (t) \
53                               ? ~ (t) 0 << (sizeof (t) * CHAR_BIT - 1) \
54                               : (t) 0))
55 #define TYPE_MAXIMUM(t) ((t) (~ (t) 0 - TYPE_MINIMUM (t)))
56
57 #ifndef STRTOL_T_MINIMUM
58 # define STRTOL_T_MINIMUM TYPE_MINIMUM (__strtol_t)
59 # define STRTOL_T_MAXIMUM TYPE_MAXIMUM (__strtol_t)
60 #endif
61
62 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
63 # define IN_CTYPE_DOMAIN(c) 1
64 #else
65 # define IN_CTYPE_DOMAIN(c) isascii(c)
66 #endif
67
68 #define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c))
69
70 #include "xstrtol.h"
71
72 #if !HAVE_DECL_STRTOIMAX && !defined strtoimax
73 intmax_t strtoimax ();
74 #endif
75
76 #if !HAVE_DECL_STRTOUMAX && !defined strtoumax
77 uintmax_t strtoumax ();
78 #endif
79
80 static strtol_error
81 bkm_scale (__strtol_t *x, int scale_factor)
82 {
83   if (TYPE_SIGNED (__strtol_t) && *x < STRTOL_T_MINIMUM / scale_factor)
84     {
85       *x = STRTOL_T_MINIMUM;
86       return LONGINT_OVERFLOW;
87     }
88   if (STRTOL_T_MAXIMUM / scale_factor < *x)
89     {
90       *x = STRTOL_T_MAXIMUM;
91       return LONGINT_OVERFLOW;
92     }
93   *x *= scale_factor;
94   return LONGINT_OK;
95 }
96
97 static strtol_error
98 bkm_scale_by_power (__strtol_t *x, int base, int power)
99 {
100   strtol_error err = LONGINT_OK;
101   while (power--)
102     err |= bkm_scale (x, base);
103   return err;
104 }
105
106 /* FIXME: comment.  */
107
108 strtol_error
109 __xstrtol (const char *s, char **ptr, int strtol_base,
110            __strtol_t *val, const char *valid_suffixes)
111 {
112   char *t_ptr;
113   char **p;
114   __strtol_t tmp;
115   strtol_error err = LONGINT_OK;
116
117   assert (0 <= strtol_base && strtol_base <= 36);
118
119   p = (ptr ? ptr : &t_ptr);
120
121   if (! TYPE_SIGNED (__strtol_t))
122     {
123       const char *q = s;
124       while (ISSPACE ((unsigned char) *q))
125         ++q;
126       if (*q == '-')
127         return LONGINT_INVALID;
128     }
129
130   errno = 0;
131   tmp = __strtol (s, p, strtol_base);
132
133   if (*p == s)
134     {
135       /* If there is no number but there is a valid suffix, assume the
136          number is 1.  The string is invalid otherwise.  */
137       if (valid_suffixes && **p && strchr (valid_suffixes, **p))
138         tmp = 1;
139       else
140         return LONGINT_INVALID;
141     }
142   else if (errno != 0)
143     {
144       if (errno != ERANGE)
145         return LONGINT_INVALID;
146       err = LONGINT_OVERFLOW;
147     }
148
149   /* Let valid_suffixes == NULL mean `allow any suffix'.  */
150   /* FIXME: update all callers except the ones that allow suffixes
151      after the number, changing last parameter NULL to `""'.  */
152   if (!valid_suffixes)
153     {
154       *val = tmp;
155       return err;
156     }
157
158   if (**p != '\0')
159     {
160       int base = 1024;
161       int suffixes = 1;
162       strtol_error overflow;
163
164       if (!strchr (valid_suffixes, **p))
165         {
166           *val = tmp;
167           return err | LONGINT_INVALID_SUFFIX_CHAR;
168         }
169
170       if (strchr (valid_suffixes, '0'))
171         {
172           /* The ``valid suffix'' '0' is a special flag meaning that
173              an optional second suffix is allowed, which can change
174              the base.  A suffix "B" (e.g. "100MB") stands for a power
175              of 1000, whereas a suffix "iB" (e.g. "100MiB") stands for
176              a power of 1024.  If no suffix (e.g. "100M"), assume
177              power-of-1024.  */
178
179           switch (p[0][1])
180             {
181             case 'i':
182               if (p[0][2] == 'B')
183                 suffixes += 2;
184               break;
185
186             case 'B':
187             case 'D': /* 'D' is obsolescent */
188               base = 1000;
189               suffixes++;
190               break;
191             }
192         }
193
194       switch (**p)
195         {
196         case 'b':
197           overflow = bkm_scale (&tmp, 512);
198           break;
199
200         case 'B':
201           overflow = bkm_scale (&tmp, 1024);
202           break;
203
204         case 'c':
205           overflow = 0;
206           break;
207
208         case 'E': /* exa or exbi */
209           overflow = bkm_scale_by_power (&tmp, base, 6);
210           break;
211
212         case 'G': /* giga or gibi */
213         case 'g': /* 'g' is undocumented; for compatibility only */
214           overflow = bkm_scale_by_power (&tmp, base, 3);
215           break;
216
217         case 'k': /* kilo */
218         case 'K': /* kibi */
219           overflow = bkm_scale_by_power (&tmp, base, 1);
220           break;
221
222         case 'M': /* mega or mebi */
223         case 'm': /* 'm' is undocumented; for compatibility only */
224           overflow = bkm_scale_by_power (&tmp, base, 2);
225           break;
226
227         case 'P': /* peta or pebi */
228           overflow = bkm_scale_by_power (&tmp, base, 5);
229           break;
230
231         case 'T': /* tera or tebi */
232         case 't': /* 't' is undocumented; for compatibility only */
233           overflow = bkm_scale_by_power (&tmp, base, 4);
234           break;
235
236         case 'w':
237           overflow = bkm_scale (&tmp, 2);
238           break;
239
240         case 'Y': /* yotta or 2**80 */
241           overflow = bkm_scale_by_power (&tmp, base, 8);
242           break;
243
244         case 'Z': /* zetta or 2**70 */
245           overflow = bkm_scale_by_power (&tmp, base, 7);
246           break;
247
248         default:
249           *val = tmp;
250           return err | LONGINT_INVALID_SUFFIX_CHAR;
251           break;
252         }
253
254       err |= overflow;
255       *p += suffixes;
256       if (**p)
257         err |= LONGINT_INVALID_SUFFIX_CHAR;
258     }
259
260   *val = tmp;
261   return err;
262 }
263
264 #ifdef TESTING_XSTRTO
265
266 # include <stdio.h>
267 # include "error.h"
268
269 char *program_name;
270
271 int
272 main (int argc, char **argv)
273 {
274   strtol_error s_err;
275   int i;
276
277   program_name = argv[0];
278   for (i=1; i<argc; i++)
279     {
280       char *p;
281       __strtol_t val;
282
283       s_err = __xstrtol (argv[i], &p, 0, &val, "bckmw");
284       if (s_err == LONGINT_OK)
285         {
286           printf ("%s->%lu (%s)\n", argv[i], val, p);
287         }
288       else
289         {
290           STRTOL_FATAL_ERROR (argv[i], "arg", s_err);
291         }
292     }
293   exit (0);
294 }
295
296 #endif /* TESTING_XSTRTO */