Fix for LP64 architectures; Add some more tests.
[bertos.git] / mware / sprintf_test.c
1 /*!
2  * \file
3  * <!--
4  * Copyright 2004, 2005 Develer S.r.l. (http://www.develer.com/)
5  * This file is part of DevLib - See README.devlib for information.
6  * -->
7  *
8  * \brief sprintf() implementation based on _formatted_write()
9  *
10  * \version $Id$
11  * \author Bernardo Innocenti <bernie@develer.com>
12  */
13
14 /*#*
15  *#* $Log$
16  *#* Revision 1.4  2005/11/04 17:43:27  bernie
17  *#* Fix for LP64 architectures; Add some more tests.
18  *#*
19  *#*/
20
21 #include "sprintf.c"
22 #include "formatwr.c"
23 #include "hex.c"
24 #include <cfg/compiler.h>
25 #include <mware/pgm.h>
26 #include <stdio.h>
27
28 #include <assert.h> /* assert() */
29 #include <string.h> /* strcmp() */
30
31
32 int main(UNUSED_ARG(int, argc), UNUSED_ARG(char **,argv))
33 {
34         char buf[256];
35         static const char test_string[] = "Hello, world!\n";
36         static const pgm_char test_string_pgm[] = "Hello, world!\n";
37
38         snprintf(buf, sizeof buf, "%s", test_string);
39         assert(strcmp(buf, test_string) == 0);
40
41         snprintf(buf, sizeof buf, "%S", test_string_pgm);
42         assert(strcmp(buf, test_string_pgm) == 0);
43
44 #define TEST(FMT, VALUE, EXPECT) do { \
45                 snprintf(buf, sizeof buf, FMT, VALUE); \
46                 assert(strcmp(buf, EXPECT) == 0); \
47         } while (0)
48
49         TEST("%d",       12345,        "12345");
50         TEST("%ld",  123456789L,   "123456789");
51         TEST("%ld",  -12345678L,   "-12345678");
52         TEST("%lu", 4294967295UL, "4294967295");
53         TEST("%hd",     -12345,       "-12345");
54         TEST("%hu",      65535UL,      "65535");
55
56         TEST("%8d",      123,       "     123");
57         TEST("%8d",     -123,       "    -123");
58         TEST("%-8d",     -123,      "-123    ");
59         TEST("%08d",     -123,      "-0000123");
60
61         TEST("%8.2f",  -123.456,    " -123.46");
62         TEST("%-8.2f", -123.456,    "-123.46 ");
63         TEST("%8.0f",  -123.456,    "    -123");
64
65 #undef TEST
66
67         /*
68          * Stress tests.
69          */
70         snprintf(buf, sizeof buf, "%s", NULL);
71         assert(strcmp(buf, "<NULL>") == 0);
72         snprintf(buf, sizeof buf, "%k");
73         assert(strcmp(buf, "???") == 0);
74         sprintf(NULL, test_string); /* must not crash */
75
76         return 0;
77 }
78