1 /* Test inttostr functions, and incidentally, INT_BUFSIZE_BOUND
2 Copyright (C) 2010-2011 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. */
30 #define STREQ(a, b) (strcmp (a, b) == 0)
31 #define FMT(T) (TYPE_SIGNED (T) ? "%jd" : "%ju")
32 #define CAST_VAL(T,V) (TYPE_SIGNED (T) ? (intmax_t) (V) : (uintmax_t) (V))
33 #define V_min(T) (CAST_VAL (T, TYPE_MINIMUM (T)))
34 #define V_max(T) (CAST_VAL (T, TYPE_MAXIMUM (T)))
35 #define IS_TIGHT(T) (_GL_SIGNED_TYPE_OR_EXPR (T) == TYPE_SIGNED (T))
36 #define ISDIGIT(c) ((unsigned int) (c) - '0' <= 9)
38 /* Verify that an inttostr function works as advertised.
39 Convert maximum and minimum (per-type, T) values using both snprintf --
40 with a cast to intmax_t or uintmax_t -- and FN, and compare the
41 resulting strings. Use malloc for the inttostr buffer, so that if
42 we ever exceed the usually-tight INT_BUFSIZE_BOUND, tools like
43 valgrind will detect the failure. */
48 char *buf = malloc (INT_BUFSIZE_BOUND (T)); \
52 ASSERT (snprintf (ref, sizeof ref, FMT (T), V_min (T)) < sizeof ref); \
53 ASSERT (STREQ ((p = Fn (TYPE_MINIMUM (T), buf)), ref)); \
54 /* Ensure that INT_BUFSIZE_BOUND is tight for signed types. */ \
55 ASSERT (! TYPE_SIGNED (T) || (p == buf && *p == '-')); \
56 ASSERT (snprintf (ref, sizeof ref, FMT (T), V_max (T)) < sizeof ref); \
57 ASSERT (STREQ ((p = Fn (TYPE_MAXIMUM (T), buf)), ref)); \
58 /* For unsigned types, the bound is not always tight. */ \
59 ASSERT (! IS_TIGHT (T) || TYPE_SIGNED (T) \
60 || (p == buf && ISDIGIT (*p))); \
69 char *b = malloc (b_size);
72 /* Ideally we would rely on the snprintf-posix module, in which case
73 this guard would not be required, but due to limitations in gnulib's
74 implementation (see modules/snprintf-posix), we cannot. */
75 if (snprintf (b, b_size, "%ju", (uintmax_t) 3) == 1
76 && b[0] == '3' && b[1] == '\0')
79 CK (unsigned int, uinttostr);
81 CK (uintmax_t, umaxtostr);
82 CK (intmax_t, imaxtostr);
86 /* snprintf doesn't accept %ju; skip this test. */