.
[gnulib.git] / lib / strtol.c
1 /* strtol - Convert string representation of a number into an integer value.
2    Copyright (C) 1991, 92, 94, 95, 96, 97 Free Software Foundation, Inc.
3    NOTE: The canonical source of this file is maintained with the GNU C
4    Library.  Bugs can be reported to bug-glibc@prep.ai.mit.edu.
5
6    This program is free software; you can redistribute it and/or modify it
7    under the terms of the GNU General Public License as published by the
8    Free Software Foundation; either version 2, or (at your option) any
9    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 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #ifdef _LIBC
25 # define USE_NUMBER_GROUPING
26 # define STDC_HEADERS
27 # define HAVE_LIMITS_H
28 #endif
29
30 #include <ctype.h>
31 #include <errno.h>
32 #ifndef errno
33 extern int errno;
34 #endif
35 #ifndef __set_errno
36 # define __set_errno(Val) errno = (Val)
37 #endif
38
39 #ifdef HAVE_LIMITS_H
40 # include <limits.h>
41 #endif
42
43 #ifdef STDC_HEADERS
44 # include <stddef.h>
45 # include <stdlib.h>
46 # include <string.h>
47 #else
48 # ifndef NULL
49 #  define NULL 0
50 # endif
51 #endif
52
53 #ifdef USE_NUMBER_GROUPING
54 # include "../locale/localeinfo.h"
55 #endif
56
57 /* Nonzero if we are defining `strtoul' or `strtouq', operating on
58    unsigned integers.  */
59 #ifndef UNSIGNED
60 # define UNSIGNED 0
61 # define INT LONG int
62 #else
63 # define INT unsigned LONG int
64 #endif
65
66 /* Determine the name.  */
67 #if UNSIGNED
68 # ifdef USE_WIDE_CHAR
69 #  ifdef QUAD
70 #   define strtol wcstouq
71 #  else
72 #   define strtol wcstoul
73 #  endif
74 # else
75 #  ifdef QUAD
76 #   define strtol strtouq
77 #  else
78 #   define strtol strtoul
79 #  endif
80 # endif
81 #else
82 # ifdef USE_WIDE_CHAR
83 #  ifdef QUAD
84 #   define strtol wcstoq
85 #  else
86 #   define strtol wcstol
87 #  endif
88 # else
89 #  ifdef QUAD
90 #   define strtol strtoq
91 #  endif
92 # endif
93 #endif
94
95 /* If QUAD is defined, we are defining `strtoq' or `strtouq',
96    operating on `long long int's.  */
97 #ifdef QUAD
98 # define LONG long long
99 # undef LONG_MIN
100 # define LONG_MIN LONG_LONG_MIN
101 # undef LONG_MAX
102 # define LONG_MAX LONG_LONG_MAX
103 # undef ULONG_MAX
104 # define ULONG_MAX ULONG_LONG_MAX
105 # if __GNUC__ == 2 && __GNUC_MINOR__ < 7
106    /* Work around gcc bug with using this constant.  */
107    static const unsigned long long int maxquad = ULONG_LONG_MAX;
108 #  undef ULONG_MAX
109 #  define ULONG_MAX maxquad
110 # endif
111 #else
112 # define LONG long
113
114 #ifndef ULONG_MAX
115 # define ULONG_MAX ((unsigned long) ~(unsigned long) 0)
116 #endif
117 #ifndef LONG_MAX
118 # define LONG_MAX ((long int) (ULONG_MAX >> 1))
119 #endif
120 #endif
121
122 #ifdef USE_WIDE_CHAR
123 # include <wchar.h>
124 # include <wctype.h>
125 # define L_(Ch) L##Ch
126 # define UCHAR_TYPE wint_t
127 # define STRING_TYPE wchar_t
128 # define ISSPACE(Ch) iswspace (Ch)
129 # define ISALPHA(Ch) iswalpha (Ch)
130 # define TOUPPER(Ch) towupper (Ch)
131 #else
132 # if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
133 #  define IN_CTYPE_DOMAIN(c) 1
134 # else
135 #  define IN_CTYPE_DOMAIN(c) isascii(c)
136 # endif
137 # define L_(Ch) Ch
138 # define UCHAR_TYPE unsigned char
139 # define STRING_TYPE char
140 # define ISSPACE(Ch) (IN_CTYPE_DOMAIN (Ch) && isspace (Ch))
141 # define ISALPHA(Ch) (IN_CTYPE_DOMAIN (Ch) && isalpha (Ch))
142 # define TOUPPER(Ch) (IN_CTYPE_DOMAIN (Ch) ? toupper (Ch) : (Ch))
143 #endif
144
145 #ifdef __STDC__
146 # define INTERNAL(X) INTERNAL1(X)
147 # define INTERNAL1(X) __##X##_internal
148 # define WEAKNAME(X) WEAKNAME1(X)
149 #else
150 # define INTERNAL(X) __/**/X/**/_internal
151 #endif
152
153 #ifdef USE_NUMBER_GROUPING
154 /* This file defines a function to check for correct grouping.  */
155 # include "grouping.h"
156 #endif
157
158
159 /* Convert NPTR to an `unsigned long int' or `long int' in base BASE.
160    If BASE is 0 the base is determined by the presence of a leading
161    zero, indicating octal or a leading "0x" or "0X", indicating hexadecimal.
162    If BASE is < 2 or > 36, it is reset to 10.
163    If ENDPTR is not NULL, a pointer to the character after the last
164    one converted is stored in *ENDPTR.  */
165
166 INT
167 INTERNAL (strtol) (nptr, endptr, base, group)
168      const STRING_TYPE *nptr;
169      STRING_TYPE **endptr;
170      int base;
171      int group;
172 {
173   int negative;
174   register unsigned LONG int cutoff;
175   register unsigned int cutlim;
176   register unsigned LONG int i;
177   register const STRING_TYPE *s;
178   register UCHAR_TYPE c;
179   const STRING_TYPE *save, *end;
180   int overflow;
181
182 #ifdef USE_NUMBER_GROUPING
183   /* The thousands character of the current locale.  */
184   wchar_t thousands;
185   /* The numeric grouping specification of the current locale,
186      in the format described in <locale.h>.  */
187   const char *grouping;
188
189   if (group)
190     {
191       grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
192       if (*grouping <= 0 || *grouping == CHAR_MAX)
193         grouping = NULL;
194       else
195         {
196           /* Figure out the thousands separator character.  */
197           if (mbtowc (&thousands, _NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP),
198                       strlen (_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP))) <= 0)
199             thousands = (wchar_t) *_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP);
200           if (thousands == L'\0')
201             grouping = NULL;
202         }
203     }
204   else
205     grouping = NULL;
206 #endif
207
208   if (base < 0 || base == 1 || base > 36)
209     {
210       __set_errno (EINVAL);
211       return 0;
212     }
213
214   save = s = nptr;
215
216   /* Skip white space.  */
217   while (ISSPACE (*s))
218     ++s;
219   if (*s == L_('\0'))
220     goto noconv;
221
222   /* Check for a sign.  */
223   if (*s == L_('-'))
224     {
225       negative = 1;
226       ++s;
227     }
228   else if (*s == L_('+'))
229     {
230       negative = 0;
231       ++s;
232     }
233   else
234     negative = 0;
235
236   if (base == 16 && s[0] == L_('0') && TOUPPER (s[1]) == L_('X'))
237     s += 2;
238
239   /* If BASE is zero, figure it out ourselves.  */
240   if (base == 0)
241     if (*s == L_('0'))
242       {
243         if (TOUPPER (s[1]) == L_('X'))
244           {
245             s += 2;
246             base = 16;
247           }
248         else
249           base = 8;
250       }
251     else
252       base = 10;
253
254   /* Save the pointer so we can check later if anything happened.  */
255   save = s;
256
257 #ifdef USE_NUMBER_GROUPING
258   if (group)
259     {
260       /* Find the end of the digit string and check its grouping.  */
261       end = s;
262       for (c = *end; c != L_('\0'); c = *++end)
263         if ((wchar_t) c != thousands
264             && ((wchar_t) c < L_('0') || (wchar_t) c > L_('9'))
265             && (!ISALPHA (c) || (int) (TOUPPER (c) - L_('A') + 10) >= base))
266           break;
267       if (*s == thousands)
268         end = s;
269       else
270         end = correctly_grouped_prefix (s, end, thousands, grouping);
271     }
272   else
273 #endif
274     end = NULL;
275
276   cutoff = ULONG_MAX / (unsigned LONG int) base;
277   cutlim = ULONG_MAX % (unsigned LONG int) base;
278
279   overflow = 0;
280   i = 0;
281   for (c = *s; c != L_('\0'); c = *++s)
282     {
283       if (s == end)
284         break;
285       if (c >= L_('0') && c <= L_('9'))
286         c -= L_('0');
287       else if (ISALPHA (c))
288         c = TOUPPER (c) - L_('A') + 10;
289       else
290         break;
291       if ((int) c >= base)
292         break;
293       /* Check for overflow.  */
294       if (i > cutoff || (i == cutoff && c > cutlim))
295         overflow = 1;
296       else
297         {
298           i *= (unsigned LONG int) base;
299           i += c;
300         }
301     }
302
303   /* Check if anything actually happened.  */
304   if (s == save)
305     goto noconv;
306
307   /* Store in ENDPTR the address of one character
308      past the last character we converted.  */
309   if (endptr != NULL)
310     *endptr = (STRING_TYPE *) s;
311
312 #if !UNSIGNED
313   /* Check for a value that is within the range of
314      `unsigned LONG int', but outside the range of `LONG int'.  */
315   if (overflow == 0
316       && i > (negative
317               ? -((unsigned LONG int) (LONG_MIN + 1)) + 1
318               : (unsigned LONG int) LONG_MAX))
319     overflow = 1;
320 #else
321   overflow |= negative;
322 #endif
323
324   if (overflow)
325     {
326       __set_errno (ERANGE);
327 #if UNSIGNED
328       return ULONG_MAX;
329 #else
330       return negative ? LONG_MIN : LONG_MAX;
331 #endif
332     }
333
334   /* Return the result of the appropriate sign.  */
335   return (negative ? -i : i);
336
337 noconv:
338   /* We must handle a special case here: the base is 0 or 16 and the
339      first two characters are '0' and 'x', but the rest are no
340      hexadecimal digits.  This is no error case.  We return 0 and
341      ENDPTR points to the `x`.  */
342   if (endptr != NULL)
343     if (save - nptr >= 2 && TOUPPER (save[-1]) == L_('X')
344         && save[-2] == L_('0'))
345       *endptr = (STRING_TYPE *) &save[-1];
346     else
347       /*  There was no number to convert.  */
348       *endptr = (STRING_TYPE *) nptr;
349
350   return 0L;
351 }
352 \f
353 /* External user entry point.  */
354
355 #if _LIBC - 0 == 0
356 # undef PARAMS
357 # if defined (__STDC__) && __STDC__
358 #  define PARAMS(Args) Args
359 # else
360 #  define PARAMS(Args) ()
361 # endif
362
363 /* Prototype.  */
364 INT strtol PARAMS ((const STRING_TYPE *nptr, STRING_TYPE **endptr, int base));
365 #endif
366
367
368 INT
369 #ifdef weak_function
370 weak_function
371 #endif
372 strtol (nptr, endptr, base)
373      const STRING_TYPE *nptr;
374      STRING_TYPE **endptr;
375      int base;
376 {
377   return INTERNAL (strtol) (nptr, endptr, base, 0);
378 }