30075ce9b63df3bef841ac63fcb847a75e67942e
[platform/upstream/bash.git] / lib / sh / strtoimax.c
1 /* Convert string representation of a number into an intmax_t value.
2    Copyright 1999, 2001 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.  Modified by Chet Ramey for Bash. */
19
20 #if HAVE_CONFIG_H
21 #  include <config.h>
22 #endif
23
24 #if HAVE_INTTYPES_H
25 #  include <inttypes.h>
26 #endif
27
28 #if HAVE_STDLIB_H
29 #  include <stdlib.h>
30 #endif
31
32 #include <stdc.h>
33
34 /* Verify a requirement at compile-time (unlike assert, which is runtime).  */
35 #define verify(name, assertion) struct name { char a[(assertion) ? 1 : -1]; }
36
37 #ifndef HAVE_DECL_STRTOL
38 "this configure-time declaration test was not run"
39 #endif
40 #if !HAVE_DECL_STRTOL
41 extern long strtol __P((const char *, char **, int));
42 #endif
43
44 #ifndef HAVE_DECL_STRTOLL
45 "this configure-time declaration test was not run"
46 #endif
47 #if !HAVE_DECL_STRTOLL && HAVE_LONG_LONG
48 extern long long strtoll __P((const char *, char **, int));
49 #endif
50
51 intmax_t
52 strtoimax (ptr, endptr, base)
53      const char *ptr;
54      char **endptr;
55      int base;
56 {
57 #if HAVE_LONG_LONG
58   verify(size_is_that_of_long_or_long_long,
59          (sizeof (intmax_t) == sizeof (long) ||
60           sizeof (intmax_t) == sizeof (long long)));
61
62   if (sizeof (intmax_t) != sizeof (long))
63     return (strtoll (ptr, endptr, base));
64 #else
65   verify (size_is_that_of_long, sizeof (intmax_t) == sizeof (long));
66 #endif
67
68   return (strtol (ptr, endptr, base));
69 }
70
71 #ifdef TESTING
72 # include <stdio.h>
73 int
74 main ()
75 {
76   char *p, *endptr;
77   intmax_t x;
78 #if HAVE_LONG_LONG
79   long long y;
80 #endif
81   long z;
82   
83   printf ("sizeof intmax_t: %d\n", sizeof (intmax_t));
84
85 #if HAVE_LONG_LONG
86   printf ("sizeof long long: %d\n", sizeof (long long));
87 #endif
88   printf ("sizeof long: %d\n", sizeof (long));
89
90   x = strtoimax("42", &endptr, 10);
91 #if HAVE_LONG_LONG
92   y = strtoll("42", &endptr, 10);
93 #else
94   y = -1;
95 #endif
96   z = strtol("42", &endptr, 10);
97
98   printf ("%lld %lld %ld\n", x, y, z);
99
100   exit (0);
101 }
102 #endif