1/* Convert string representation of a number into an uintmax_t value. 2 Copyright 1999-2005 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_STRTOUL 38"this configure-time declaration test was not run" 39#endif 40#if !HAVE_DECL_STRTOUL 41extern unsigned long strtoul __P((const char *, char **, int)); 42#endif 43 44#ifndef HAVE_DECL_STRTOULL 45"this configure-time declaration test was not run" 46#endif 47#if !HAVE_DECL_STRTOULL && HAVE_UNSIGNED_LONG_LONG 48extern unsigned long long strtoull __P((const char *, char **, int)); 49#endif 50 51#ifdef strtoumax 52#undef strtoumax 53#endif 54 55uintmax_t 56strtoumax (ptr, endptr, base) 57 const char *ptr; 58 char **endptr; 59 int base; 60{ 61#if HAVE_UNSIGNED_LONG_LONG 62 verify (size_is_that_of_unsigned_long_or_unsigned_long_long, 63 (sizeof (uintmax_t) == sizeof (unsigned long) || 64 sizeof (uintmax_t) == sizeof (unsigned long long))); 65 66 if (sizeof (uintmax_t) != sizeof (unsigned long)) 67 return (strtoull (ptr, endptr, base)); 68#else 69 verify (size_is_that_of_unsigned_long, sizeof (uintmax_t) == sizeof (unsigned long)); 70#endif 71 72 return (strtoul (ptr, endptr, base)); 73} 74 75#ifdef TESTING 76# include <stdio.h> 77int 78main () 79{ 80 char *p, *endptr; 81 uintmax_t x; 82#if HAVE_UNSIGNED_LONG_LONG 83 unsigned long long y; 84#endif 85 unsigned long z; 86 87 printf ("sizeof uintmax_t: %d\n", sizeof (uintmax_t)); 88 89#if HAVE_UNSIGNED_LONG_LONG 90 printf ("sizeof unsigned long long: %d\n", sizeof (unsigned long long)); 91#endif 92 printf ("sizeof unsigned long: %d\n", sizeof (unsigned long)); 93 94 x = strtoumax("42", &endptr, 10); 95#if HAVE_LONG_LONG 96 y = strtoull("42", &endptr, 10); 97#else 98 y = 0; 99#endif 100 z = strtoul("42", &endptr, 10); 101 102 printf ("%llu %llu %lu\n", x, y, z); 103 104 exit (0); 105} 106#endif 107