3e12cc637a4a536f425b71c0cd23f6a901ac4e0d
[gnulib.git] / lib / strtoimax.c
1 /* Convert string representation of a number into an intmax_t value.
2    Copyright (C) 1999, 2001, 2002, 2003 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Written by Paul Eggert. */
19
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #if HAVE_INTTYPES_H
25 # include <inttypes.h>
26 #else
27 # if HAVE_STDINT_H
28 #  include <stdint.h>
29 # endif
30 #endif
31
32 #if HAVE_STDLIB_H
33 # include <stdlib.h>
34 #endif
35
36 /* Verify a requirement at compile-time (unlike assert, which is runtime).  */
37 #define verify(name, assertion) struct name { char a[(assertion) ? 1 : -1]; }
38
39 #ifdef UNSIGNED
40 # ifndef HAVE_DECL_STRTOUL
41 "this configure-time declaration test was not run"
42 # endif
43 # if !HAVE_DECL_STRTOUL
44 unsigned long strtoul (char const *, char **, int);
45 # endif
46 # ifndef HAVE_DECL_STRTOULL
47 "this configure-time declaration test was not run"
48 # endif
49 # if !HAVE_DECL_STRTOULL && HAVE_UNSIGNED_LONG_LONG
50 unsigned long long strtoull (char const *, char **, int);
51 # endif
52
53 #else
54
55 # ifndef HAVE_DECL_STRTOL
56 "this configure-time declaration test was not run"
57 # endif
58 # if !HAVE_DECL_STRTOL
59 long strtol (char const *, char **, int);
60 # endif
61 # ifndef HAVE_DECL_STRTOLL
62 "this configure-time declaration test was not run"
63 # endif
64 # if !HAVE_DECL_STRTOLL && HAVE_UNSIGNED_LONG_LONG
65 long long strtoll (char const *, char **, int);
66 # endif
67 #endif
68
69 #ifdef UNSIGNED
70 # undef HAVE_LONG_LONG
71 # define HAVE_LONG_LONG HAVE_UNSIGNED_LONG_LONG
72 # define INT uintmax_t
73 # define strtoimax strtoumax
74 # define strtol strtoul
75 # define strtoll strtoull
76 #else
77 # define INT intmax_t
78 #endif
79
80 INT
81 strtoimax (char const *ptr, char **endptr, int base)
82 {
83 #if HAVE_LONG_LONG
84   verify (size_is_that_of_long_or_long_long,
85           (sizeof (INT) == sizeof (long)
86            || sizeof (INT) == sizeof (long long)));
87
88   if (sizeof (INT) != sizeof (long))
89     return strtoll (ptr, endptr, base);
90 #else
91   verify (size_is_that_of_long,
92           sizeof (INT) == sizeof (long));
93 #endif
94
95   return strtol (ptr, endptr, base);
96 }