tst_swprintf.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include <array_length.h>
  2. #include <errno.h>
  3. #include <stdio.h>
  4. #include <support/check.h>
  5. #include <sys/types.h>
  6. #include <wchar.h>
  7. static wchar_t buf[100];
  8. static const struct
  9. {
  10. size_t n;
  11. const char *str;
  12. ssize_t exp;
  13. } tests[] =
  14. {
  15. { array_length (buf), "hello world", 11 },
  16. { 0, "hello world", -1 },
  17. { 1, "hello world", -1 },
  18. { 2, "hello world", -1 },
  19. { 11, "hello world", -1 },
  20. { 12, "hello world", 11 },
  21. { 0, "", -1 },
  22. { array_length (buf), "", 0 }
  23. };
  24. static int
  25. do_test (void)
  26. {
  27. size_t n;
  28. TEST_COMPARE (swprintf (buf, array_length (buf), L"Hello %s", "world"), 11);
  29. TEST_COMPARE_STRING_WIDE (buf, L"Hello world");
  30. TEST_COMPARE (swprintf (buf, array_length (buf), L"Is this >%g< 3.1?", 3.1),
  31. 18);
  32. TEST_COMPARE_STRING_WIDE (buf, L"Is this >3.1< 3.1?");
  33. for (n = 0; n < array_length (tests); ++n)
  34. {
  35. wmemset (buf, 0xabcd, array_length (buf));
  36. errno = 0;
  37. ssize_t res = swprintf (buf, tests[n].n, L"%s", tests[n].str);
  38. if (tests[n].exp < 0 && res >= 0)
  39. {
  40. support_record_failure ();
  41. printf ("swprintf (buf, %zu, L\"%%s\", \"%s\") expected to fail\n",
  42. tests[n].n, tests[n].str);
  43. }
  44. else if (tests[n].exp >= 0 && tests[n].exp != res)
  45. {
  46. support_record_failure ();
  47. printf ("\
  48. swprintf (buf, %zu, L\"%%s\", \"%s\") expected to return %zd, but got %zd\n",
  49. tests[n].n, tests[n].str, tests[n].exp, res);
  50. }
  51. else if (res < 0
  52. && tests[n].n > 0
  53. && wcsnlen (buf, array_length (buf)) == array_length (buf))
  54. {
  55. support_record_failure ();
  56. printf ("\
  57. error: swprintf (buf, %zu, L\"%%s\", \"%s\") missing null terminator\n",
  58. tests[n].n, tests[n].str);
  59. }
  60. else if (res < 0
  61. && tests[n].n > 0
  62. && wcsnlen (buf, array_length (buf)) < array_length (buf)
  63. && buf[wcsnlen (buf, array_length (buf)) + 1] != 0xabcd)
  64. {
  65. support_record_failure ();
  66. printf ("\
  67. error: swprintf (buf, %zu, L\"%%s\", \"%s\") out of bounds write\n",
  68. tests[n].n, tests[n].str);
  69. }
  70. if (res < 0 && tests[n].n < 0)
  71. TEST_COMPARE (errno, E2BIG);
  72. printf ("swprintf (buf, %zu, L\"%%s\", \"%s\") OK\n",
  73. tests[n].n, tests[n].str);
  74. }
  75. TEST_COMPARE (swprintf (buf, array_length (buf), L"%.0s", "foo"), 0);
  76. TEST_COMPARE_STRING_WIDE (buf, L"");
  77. TEST_COMPARE (swprintf (buf, array_length (buf), L"%.0ls", L"foo"), 0);
  78. TEST_COMPARE_STRING_WIDE (buf, L"");
  79. return 0;
  80. }
  81. #include <support/test-driver.c>