2 * Copyright (C) 2010 Nick Bowler.
4 * License GPLv3+: GNU GPL version 3 or later. See COPYING for terms.
5 * See <http://www.gnu.org/licenses/gpl.html> if you did not receive a copy.
6 * This is free software: you are free to change and redistribute it.
7 * There is NO WARRANTY, to the extent permitted by law.
15 static int check(const char *expect
, const char *fmt
, ...)
17 static char buf
[1024];
22 rc
= vsprintf(buf
, fmt
, ap
);
25 if (strcmp(expect
, buf
) != 0) {
26 puts("vsprintf: output did not match the expected value.");
27 printf(" got: \"%s\"\n", buf
);
28 printf(" expected: \"%s\"\n", expect
);
32 if (rc
!= strlen(expect
)) {
33 puts("vsprintf: return value did not match expectations.");
40 #define CHECK_SIMPLE(expect, ...) if (check(expect, __VA_ARGS__)) { \
41 puts("sprintf(" #__VA_ARGS__ ") failed."); \
42 return EXIT_FAILURE; \
48 CHECK_SIMPLE("%", "%%");
49 CHECK_SIMPLE("0", "%d", 0);
50 CHECK_SIMPLE("42", "%d", 42);
51 CHECK_SIMPLE("42", "%u", 42u);
52 CHECK_SIMPLE("1777", "%o", 0x3ffu
);
53 CHECK_SIMPLE("3ff", "%x", 0x3ffu
);
55 /* Minimum field widths */
56 CHECK_SIMPLE("[ 42]", "[%4d]", 42);
57 CHECK_SIMPLE("[ 42]", "[% 4d]", 42);
58 CHECK_SIMPLE("[ -42]", "[%4d]", -42);
59 CHECK_SIMPLE("[0042]", "[%04d]", 42);
60 CHECK_SIMPLE("[+042]", "[%+04d]", 42);
61 CHECK_SIMPLE("[ 042]", "[% 04d]", 42);
62 CHECK_SIMPLE("[ 42 ]", "[% -4d]", 42);
63 CHECK_SIMPLE("[42 ]", "[%-4d]", 42);
64 CHECK_SIMPLE("[42 ]", "[%-04d]", 42);
66 /* Integer precision */
67 CHECK_SIMPLE("", "%.d", 0);
68 CHECK_SIMPLE("0000", "%.4d", 0);
69 CHECK_SIMPLE(" 0042", "%6.4d", 42);
71 /* Integer alternate forms */
72 CHECK_SIMPLE("0", "%#o", 0u);
73 CHECK_SIMPLE("0", "%#x", 0u);
74 CHECK_SIMPLE("01", "%#o", 1u);
75 CHECK_SIMPLE("01", "%#.2o", 1u);
76 CHECK_SIMPLE("0x01", "%#.2x", 1u);
77 CHECK_SIMPLE("0x01", "%#04x", 1u);
79 /* Mutually exclusive options */
80 CHECK_SIMPLE("0 ", "%-05d", 0);
81 CHECK_SIMPLE(" 0", "%05.1d", 0);
82 CHECK_SIMPLE("+0", "%+ d", 0);
83 CHECK_SIMPLE("+ ", "%0- +5.d", 0);
85 /* Narrow types shall be converted prior to printing */
86 CHECK_SIMPLE("0", "%hhu", UCHAR_MAX
+1);
87 CHECK_SIMPLE("0", "%hu", USHRT_MAX
+1);