Hackfix and re-enable strtoull and wcstoull, see bug #3798.
[sdcc.git] / sdcc / device / lib / strtol.c
blob99fb092c61e5321e9bc2ccbf8321ab0a14d2f095
1 /*---------------------------------------------------------------------
2 strtol() - convert a string to a long int and return it
4 Copyright (C) 2018-2023, Philipp Klaus Krause . krauseph@informatik.uni-freiburg.de
6 This library 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.
11 This library 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.
16 You should have received a copy of the GNU General Public License
17 along with this library; see the file COPYING. If not, write to the
18 Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
19 MA 02110-1301, USA.
21 As a special exception, if you link this library with other files,
22 some of which are compiled with SDCC, to produce an executable,
23 this library does not by itself cause the resulting executable to
24 be covered by the GNU General Public License. This exception does
25 not however invalidate any other reasons why the executable file
26 might be covered by the GNU General Public License.
27 -------------------------------------------------------------------------*/
29 #include <stdlib.h>
31 #include <stdbool.h>
32 #include <ctype.h>
33 #include <limits.h>
34 #include <errno.h>
36 #pragma disable_warning 196
38 long int strtol(const char *nptr, char **endptr, int base)
40 const char *ptr = nptr;
41 const char *rptr;
42 unsigned long int u;
43 bool neg;
45 while (isblank (*ptr))
46 ptr++;
48 neg = (*ptr == '-');
50 if (*ptr == '-')
52 neg = true;
53 ptr++;
55 else
56 neg = false;
58 // strtoul() would accept leading blanks or signs (that might come after '-' handled above)
59 if (neg && (isblank (*ptr) || *ptr == '-' || *ptr == '+'))
61 if (endptr)
62 *endptr = nptr;
63 return (0);
66 u = strtoul(ptr, &rptr, base);
68 // Check for conversion error
69 if (rptr == ptr)
71 if (endptr)
72 *endptr = nptr;
73 return (0);
76 if (endptr)
77 *endptr = rptr;
79 // Check for range error
80 if (!neg && u > LONG_MAX)
82 errno = ERANGE;
83 return (LONG_MAX);
85 else if (neg && u > -LONG_MIN)
87 errno = ERANGE;
88 return (LONG_MIN);
91 return (neg ? -u : u);