test_fmt.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright (c) 2022 Agustina Arzille.
  3. *
  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.
  8. *
  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.
  13. *
  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/>.
  16. *
  17. */
  18. #include <string.h>
  19. #include <kern/error.h>
  20. #include <kern/fmt.h>
  21. #include <kern/init.h>
  22. #include <kern/log.h>
  23. #include <test/test.h>
  24. struct test_stream
  25. {
  26. struct stream base;
  27. char *buf;
  28. uint32_t len;
  29. };
  30. static void
  31. test_stream_write (struct stream *stream, const void *data, uint32_t bytes)
  32. {
  33. _Auto sp = (struct test_stream *) stream;
  34. for (uint32_t i = 0; i < bytes; ++i)
  35. {
  36. int ch = ((const char *)data)[i];
  37. sp->buf[sp->len + i] = ch < 'A' || ch > 'Z' ? ch : ((ch - 'A') + 'a');
  38. }
  39. sp->len += bytes;
  40. }
  41. static const struct stream_ops test_stream_ops =
  42. {
  43. .write = test_stream_write
  44. };
  45. static void
  46. test_sscanf (void)
  47. {
  48. int x1, x2;
  49. char c1, c2;
  50. int rv = fmt_sscanf ("123 qx -45", "%d %c%c %d", &x1, &c1, &c2, &x2);
  51. test_assert_eq (rv, 4);
  52. test_assert_eq (x1, 123);
  53. test_assert_eq (c1, 'q');
  54. test_assert_eq (c2, 'x');
  55. test_assert_eq (x2, -45);
  56. }
  57. TEST_INLINE (fmt)
  58. {
  59. char buf[32];
  60. int rv = fmt_sprintf (buf, "hello %d %s", -4, "???");
  61. test_assert_eq (rv, 12);
  62. test_assert_streq (buf, "hello -4 ???");
  63. rv = fmt_snprintf (buf, 4, "abc%d", 33);
  64. test_assert_eq (rv, 5);
  65. buf[rv - 1] = '\0';
  66. test_assert_streq (buf, "abc3");
  67. struct test_stream stream = { .buf = buf, .len = 0 };
  68. stream_init (&stream.base, &test_stream_ops);
  69. rv = fmt_xprintf (&stream.base, "HELLO %d", -1);
  70. test_assert_gt (rv, 0);
  71. buf[rv] = '\0';
  72. test_assert_streq (buf, "hello -1");
  73. test_sscanf ();
  74. return (TEST_OK);
  75. }