1 /* Test inttostr functions, and incidentally, INT_BUFSIZE_BOUND
2 Copyright (C) 2010 Free Software Foundation, Inc.
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 3 of the License, or
7 (at your option) any later version.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Jim Meyering. */
29 #define STREQ(a, b) (strcmp (a, b) == 0)
30 #define FMT(T) (TYPE_SIGNED (T) ? "%jd" : "%ju")
31 #define CAST_VAL(T,V) (TYPE_SIGNED (T) ? (intmax_t) (V) : (uintmax_t) (V))
32 #define V_min(T) (CAST_VAL (T, TYPE_MINIMUM (T)))
33 #define V_max(T) (CAST_VAL (T, TYPE_MAXIMUM (T)))
34 #define IS_TIGHT(T) (signed_type_or_expr__(T) == TYPE_SIGNED (T))
35 #define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
37 /* Verify that an inttostr function works as advertised.
38 Convert maximum and minimum (per-type, T) values using both snprintf --
39 with a cast to intmax_t or uintmax_t -- and FN, and compare the
40 resulting strings. Use malloc for the inttostr buffer, so that if
41 we ever exceed the usually-tight INT_BUFSIZE_BOUND, tools like
42 valgrind will detect the failure. */
47 char *buf = malloc (INT_BUFSIZE_BOUND (T)); \
51 assert (snprintf (ref, sizeof ref, FMT (T), V_min (T)) < sizeof ref); \
52 assert (STREQ ((p = Fn (TYPE_MINIMUM (T), buf)), ref)); \
53 /* Ensure that INT_BUFSIZE_BOUND is tight for signed types. */ \
54 assert (! TYPE_SIGNED (T) || (p == buf && *p == '-')); \
55 assert (snprintf (ref, sizeof ref, FMT (T), V_max (T)) < sizeof ref); \
56 assert (STREQ ((p = Fn (TYPE_MAXIMUM (T), buf)), ref)); \
57 /* For unsigned types, the bound is not always tight. */ \
58 assert (! IS_TIGHT (T) || TYPE_SIGNED (T) \
59 || (p == buf && ISDIGIT (*p))); \
68 CK (unsigned int, uinttostr);
70 CK (uintmax_t, umaxtostr);
71 CK (intmax_t, imaxtostr);