eda2d2699853471d31919a0dc86c56e82a38cdaf
[gnulib.git] / lib / strtol.c
1 /* Convert string representation of a number into an integer value.
2
3    Copyright (C) 1991, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2003, 2005, 2006
4    Free Software Foundation, Inc.
5
6    NOTE: The canonical source of this file is maintained with the GNU C
7    Library.  Bugs can be reported to bug-glibc@gnu.org.
8
9    This program is free software; you can redistribute it and/or modify it
10    under the terms of the GNU General Public License as published by the
11    Free Software Foundation; either version 2, or (at your option) any
12    later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software Foundation,
21    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
22
23 #ifdef HAVE_CONFIG_H
24 # include <config.h>
25 #endif
26
27 #ifdef _LIBC
28 # define USE_NUMBER_GROUPING
29 #endif
30
31 #include <ctype.h>
32 #include <errno.h>
33 #ifndef __set_errno
34 # define __set_errno(Val) errno = (Val)
35 #endif
36
37 #include <limits.h>
38 #include <stddef.h>
39 #include <stdlib.h>
40 #include <string.h>
41
42 #ifdef USE_NUMBER_GROUPING
43 # include "../locale/localeinfo.h"
44 #endif
45
46 /* Nonzero if we are defining `strtoul' or `strtoull', operating on
47    unsigned integers.  */
48 #ifndef UNSIGNED
49 # define UNSIGNED 0
50 # define INT LONG int
51 #else
52 # define INT unsigned LONG int
53 #endif
54
55 /* Determine the name.  */
56 #ifdef USE_IN_EXTENDED_LOCALE_MODEL
57 # if UNSIGNED
58 #  ifdef USE_WIDE_CHAR
59 #   ifdef QUAD
60 #    define strtol __wcstoull_l
61 #   else
62 #    define strtol __wcstoul_l
63 #   endif
64 #  else
65 #   ifdef QUAD
66 #    define strtol __strtoull_l
67 #   else
68 #    define strtol __strtoul_l
69 #   endif
70 #  endif
71 # else
72 #  ifdef USE_WIDE_CHAR
73 #   ifdef QUAD
74 #    define strtol __wcstoll_l
75 #   else
76 #    define strtol __wcstol_l
77 #   endif
78 #  else
79 #   ifdef QUAD
80 #    define strtol __strtoll_l
81 #   else
82 #    define strtol __strtol_l
83 #   endif
84 #  endif
85 # endif
86 #else
87 # if UNSIGNED
88 #  ifdef USE_WIDE_CHAR
89 #   ifdef QUAD
90 #    define strtol wcstoull
91 #   else
92 #    define strtol wcstoul
93 #   endif
94 #  else
95 #   ifdef QUAD
96 #    define strtol strtoull
97 #   else
98 #    define strtol strtoul
99 #   endif
100 #  endif
101 # else
102 #  ifdef USE_WIDE_CHAR
103 #   ifdef QUAD
104 #    define strtol wcstoll
105 #   else
106 #    define strtol wcstol
107 #   endif
108 #  else
109 #   ifdef QUAD
110 #    define strtol strtoll
111 #   endif
112 #  endif
113 # endif
114 #endif
115
116 /* If QUAD is defined, we are defining `strtoll' or `strtoull',
117    operating on `long long int's.  */
118 #ifdef QUAD
119 # define LONG long long
120 # define STRTOL_LONG_MIN LONG_LONG_MIN
121 # define STRTOL_LONG_MAX LONG_LONG_MAX
122 # define STRTOL_ULONG_MAX ULONG_LONG_MAX
123
124 /* The extra casts in the following macros work around compiler bugs,
125    e.g., in Cray C 5.0.3.0.  */
126
127 /* True if negative values of the signed integer type T use two's
128    complement, ones' complement, or signed magnitude representation,
129    respectively.  Much GNU code assumes two's complement, but some
130    people like to be portable to all possible C hosts.  */
131 # define TYPE_TWOS_COMPLEMENT(t) ((t) ~ (t) 0 == (t) -1)
132 # define TYPE_ONES_COMPLEMENT(t) ((t) ~ (t) 0 == 0)
133 # define TYPE_SIGNED_MAGNITUDE(t) ((t) ~ (t) 0 < (t) -1)
134
135 /* True if the arithmetic type T is signed.  */
136 # define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
137
138 /* The maximum and minimum values for the integer type T.  These
139    macros have undefined behavior if T is signed and has padding bits.
140    If this is a problem for you, please let us know how to fix it for
141    your host.  */
142 # define TYPE_MINIMUM(t) \
143    ((t) (! TYPE_SIGNED (t) \
144          ? (t) 0 \
145          : TYPE_SIGNED_MAGNITUDE (t) \
146          ? ~ (t) 0 \
147          : ~ (t) 0 << (sizeof (t) * CHAR_BIT - 1)))
148 # define TYPE_MAXIMUM(t) \
149    ((t) (! TYPE_SIGNED (t) \
150          ? (t) -1 \
151          : ~ (~ (t) 0 << (sizeof (t) * CHAR_BIT - 1))))
152
153 # ifndef ULONG_LONG_MAX
154 #  define ULONG_LONG_MAX TYPE_MAXIMUM (unsigned long long)
155 # endif
156 # ifndef LONG_LONG_MAX
157 #  define LONG_LONG_MAX TYPE_MAXIMUM (long long int)
158 # endif
159 # ifndef LONG_LONG_MIN
160 #  define LONG_LONG_MIN TYPE_MINIMUM (long long int)
161 # endif
162
163 # if __GNUC__ == 2 && __GNUC_MINOR__ < 7
164    /* Work around gcc bug with using this constant.  */
165    static const unsigned long long int maxquad = ULONG_LONG_MAX;
166 #  undef STRTOL_ULONG_MAX
167 #  define STRTOL_ULONG_MAX maxquad
168 # endif
169 #else
170 # define LONG long
171 # define STRTOL_LONG_MIN LONG_MIN
172 # define STRTOL_LONG_MAX LONG_MAX
173 # define STRTOL_ULONG_MAX ULONG_MAX
174 #endif
175
176
177 /* We use this code also for the extended locale handling where the
178    function gets as an additional argument the locale which has to be
179    used.  To access the values we have to redefine the _NL_CURRENT
180    macro.  */
181 #ifdef USE_IN_EXTENDED_LOCALE_MODEL
182 # undef _NL_CURRENT
183 # define _NL_CURRENT(category, item) \
184   (current->values[_NL_ITEM_INDEX (item)].string)
185 # define LOCALE_PARAM , loc
186 # define LOCALE_PARAM_PROTO , __locale_t loc
187 #else
188 # define LOCALE_PARAM
189 # define LOCALE_PARAM_PROTO
190 #endif
191
192 #if defined _LIBC || defined HAVE_WCHAR_H
193 # include <wchar.h>
194 #endif
195
196 #ifdef USE_WIDE_CHAR
197 # include <wctype.h>
198 # define L_(Ch) L##Ch
199 # define UCHAR_TYPE wint_t
200 # define STRING_TYPE wchar_t
201 # ifdef USE_IN_EXTENDED_LOCALE_MODEL
202 #  define ISSPACE(Ch) __iswspace_l ((Ch), loc)
203 #  define ISALPHA(Ch) __iswalpha_l ((Ch), loc)
204 #  define TOUPPER(Ch) __towupper_l ((Ch), loc)
205 # else
206 #  define ISSPACE(Ch) iswspace (Ch)
207 #  define ISALPHA(Ch) iswalpha (Ch)
208 #  define TOUPPER(Ch) towupper (Ch)
209 # endif
210 #else
211 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
212 #  define IN_CTYPE_DOMAIN(c) 1
213 # else
214 #  define IN_CTYPE_DOMAIN(c) isascii(c)
215 # endif
216 # define L_(Ch) Ch
217 # define UCHAR_TYPE unsigned char
218 # define STRING_TYPE char
219 # ifdef USE_IN_EXTENDED_LOCALE_MODEL
220 #  define ISSPACE(Ch) __isspace_l ((Ch), loc)
221 #  define ISALPHA(Ch) __isalpha_l ((Ch), loc)
222 #  define TOUPPER(Ch) __toupper_l ((Ch), loc)
223 # else
224 #  define ISSPACE(Ch) (IN_CTYPE_DOMAIN (Ch) && isspace (Ch))
225 #  define ISALPHA(Ch) (IN_CTYPE_DOMAIN (Ch) && isalpha (Ch))
226 #  define TOUPPER(Ch) (IN_CTYPE_DOMAIN (Ch) ? toupper (Ch) : (Ch))
227 # endif
228 #endif
229
230 #define INTERNAL(X) INTERNAL1(X)
231 #define INTERNAL1(X) __##X##_internal
232 #define WEAKNAME(X) WEAKNAME1(X)
233
234 #ifdef USE_NUMBER_GROUPING
235 /* This file defines a function to check for correct grouping.  */
236 # include "grouping.h"
237 #endif
238
239
240
241 /* Convert NPTR to an `unsigned long int' or `long int' in base BASE.
242    If BASE is 0 the base is determined by the presence of a leading
243    zero, indicating octal or a leading "0x" or "0X", indicating hexadecimal.
244    If BASE is < 2 or > 36, it is reset to 10.
245    If ENDPTR is not NULL, a pointer to the character after the last
246    one converted is stored in *ENDPTR.  */
247
248 INT
249 INTERNAL (strtol) (const STRING_TYPE *nptr, STRING_TYPE **endptr,
250                    int base, int group LOCALE_PARAM_PROTO)
251 {
252   int negative;
253   register unsigned LONG int cutoff;
254   register unsigned int cutlim;
255   register unsigned LONG int i;
256   register const STRING_TYPE *s;
257   register UCHAR_TYPE c;
258   const STRING_TYPE *save, *end;
259   int overflow;
260
261 #ifdef USE_NUMBER_GROUPING
262 # ifdef USE_IN_EXTENDED_LOCALE_MODEL
263   struct locale_data *current = loc->__locales[LC_NUMERIC];
264 # endif
265   /* The thousands character of the current locale.  */
266   wchar_t thousands = L'\0';
267   /* The numeric grouping specification of the current locale,
268      in the format described in <locale.h>.  */
269   const char *grouping;
270
271   if (group)
272     {
273       grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
274       if (*grouping <= 0 || *grouping == CHAR_MAX)
275         grouping = NULL;
276       else
277         {
278           /* Figure out the thousands separator character.  */
279 # if defined _LIBC || defined _HAVE_BTOWC
280           thousands = __btowc (*_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP));
281           if (thousands == WEOF)
282             thousands = L'\0';
283 # endif
284           if (thousands == L'\0')
285             grouping = NULL;
286         }
287     }
288   else
289     grouping = NULL;
290 #endif
291
292   if (base < 0 || base == 1 || base > 36)
293     {
294       __set_errno (EINVAL);
295       return 0;
296     }
297
298   save = s = nptr;
299
300   /* Skip white space.  */
301   while (ISSPACE (*s))
302     ++s;
303   if (*s == L_('\0'))
304     goto noconv;
305
306   /* Check for a sign.  */
307   if (*s == L_('-'))
308     {
309       negative = 1;
310       ++s;
311     }
312   else if (*s == L_('+'))
313     {
314       negative = 0;
315       ++s;
316     }
317   else
318     negative = 0;
319
320   /* Recognize number prefix and if BASE is zero, figure it out ourselves.  */
321   if (*s == L_('0'))
322     {
323       if ((base == 0 || base == 16) && TOUPPER (s[1]) == L_('X'))
324         {
325           s += 2;
326           base = 16;
327         }
328       else if (base == 0)
329         base = 8;
330     }
331   else if (base == 0)
332     base = 10;
333
334   /* Save the pointer so we can check later if anything happened.  */
335   save = s;
336
337 #ifdef USE_NUMBER_GROUPING
338   if (group)
339     {
340       /* Find the end of the digit string and check its grouping.  */
341       end = s;
342       for (c = *end; c != L_('\0'); c = *++end)
343         if ((wchar_t) c != thousands
344             && ((wchar_t) c < L_('0') || (wchar_t) c > L_('9'))
345             && (!ISALPHA (c) || (int) (TOUPPER (c) - L_('A') + 10) >= base))
346           break;
347       if (*s == thousands)
348         end = s;
349       else
350         end = correctly_grouped_prefix (s, end, thousands, grouping);
351     }
352   else
353 #endif
354     end = NULL;
355
356   cutoff = STRTOL_ULONG_MAX / (unsigned LONG int) base;
357   cutlim = STRTOL_ULONG_MAX % (unsigned LONG int) base;
358
359   overflow = 0;
360   i = 0;
361   for (c = *s; c != L_('\0'); c = *++s)
362     {
363       if (s == end)
364         break;
365       if (c >= L_('0') && c <= L_('9'))
366         c -= L_('0');
367       else if (ISALPHA (c))
368         c = TOUPPER (c) - L_('A') + 10;
369       else
370         break;
371       if ((int) c >= base)
372         break;
373       /* Check for overflow.  */
374       if (i > cutoff || (i == cutoff && c > cutlim))
375         overflow = 1;
376       else
377         {
378           i *= (unsigned LONG int) base;
379           i += c;
380         }
381     }
382
383   /* Check if anything actually happened.  */
384   if (s == save)
385     goto noconv;
386
387   /* Store in ENDPTR the address of one character
388      past the last character we converted.  */
389   if (endptr != NULL)
390     *endptr = (STRING_TYPE *) s;
391
392 #if !UNSIGNED
393   /* Check for a value that is within the range of
394      `unsigned LONG int', but outside the range of `LONG int'.  */
395   if (overflow == 0
396       && i > (negative
397               ? -((unsigned LONG int) (STRTOL_LONG_MIN + 1)) + 1
398               : (unsigned LONG int) STRTOL_LONG_MAX))
399     overflow = 1;
400 #endif
401
402   if (overflow)
403     {
404       __set_errno (ERANGE);
405 #if UNSIGNED
406       return STRTOL_ULONG_MAX;
407 #else
408       return negative ? STRTOL_LONG_MIN : STRTOL_LONG_MAX;
409 #endif
410     }
411
412   /* Return the result of the appropriate sign.  */
413   return negative ? -i : i;
414
415 noconv:
416   /* We must handle a special case here: the base is 0 or 16 and the
417      first two characters are '0' and 'x', but the rest are no
418      hexadecimal digits.  This is no error case.  We return 0 and
419      ENDPTR points to the `x`.  */
420   if (endptr != NULL)
421     {
422       if (save - nptr >= 2 && TOUPPER (save[-1]) == L_('X')
423           && save[-2] == L_('0'))
424         *endptr = (STRING_TYPE *) &save[-1];
425       else
426         /*  There was no number to convert.  */
427         *endptr = (STRING_TYPE *) nptr;
428     }
429
430   return 0L;
431 }
432 \f
433 /* External user entry point.  */
434
435
436 INT
437 #ifdef weak_function
438 weak_function
439 #endif
440 strtol (const STRING_TYPE *nptr, STRING_TYPE **endptr,
441         int base LOCALE_PARAM_PROTO)
442 {
443   return INTERNAL (strtol) (nptr, endptr, base, 0 LOCALE_PARAM);
444 }