xref: /freebsd/contrib/diff/lib/strtoimax.c (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
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 #elif HAVE_STDINT_H
27 # include <stdint.h>
28 #endif
29 
30 #include <stdlib.h>
31 
32 /* Verify a requirement at compile-time (unlike assert, which is runtime).  */
33 #define verify(name, assertion) struct name { char a[(assertion) ? 1 : -1]; }
34 
35 #ifdef UNSIGNED
36 # ifndef HAVE_DECL_STRTOULL
37 "this configure-time declaration test was not run"
38 # endif
39 # if !HAVE_DECL_STRTOULL && HAVE_UNSIGNED_LONG_LONG
40 unsigned long long strtoull (char const *, char **, int);
41 # endif
42 
43 #else
44 
45 # ifndef HAVE_DECL_STRTOLL
46 "this configure-time declaration test was not run"
47 # endif
48 # if !HAVE_DECL_STRTOLL && HAVE_UNSIGNED_LONG_LONG
49 long long strtoll (char const *, char **, int);
50 # endif
51 #endif
52 
53 #ifdef UNSIGNED
54 # undef HAVE_LONG_LONG
55 # define HAVE_LONG_LONG HAVE_UNSIGNED_LONG_LONG
56 # define INT uintmax_t
57 # define strtoimax strtoumax
58 # define strtol strtoul
59 # define strtoll strtoull
60 #else
61 # define INT intmax_t
62 #endif
63 
64 INT
65 strtoimax (char const *ptr, char **endptr, int base)
66 {
67 #if HAVE_LONG_LONG
68   verify (size_is_that_of_long_or_long_long,
69 	  (sizeof (INT) == sizeof (long)
70 	   || sizeof (INT) == sizeof (long long)));
71 
72   if (sizeof (INT) != sizeof (long))
73     return strtoll (ptr, endptr, base);
74 #else
75   verify (size_is_that_of_long,
76 	  sizeof (INT) == sizeof (long));
77 #endif
78 
79   return strtol (ptr, endptr, base);
80 }
81