1//===-- Unittests for the scanf String Reader -----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "src/__support/CPP/string_view.h"
10#include "src/stdio/scanf_core/reader.h"
11
12#include "test/UnitTest/Test.h"
13
14TEST(LlvmLibcScanfStringReaderTest, Constructor) {
15 char str[10];
16 // buff_len justneeds to be a big number. The specific value isn't important
17 // in the real world.
18 LIBC_NAMESPACE::scanf_core::ReadBuffer rb{.buffer: const_cast<char *>(str), .buff_len: 1000000};
19 LIBC_NAMESPACE::scanf_core::Reader reader(&rb);
20}
21
22TEST(LlvmLibcScanfStringReaderTest, SimpleRead) {
23 const char *str = "abc";
24 LIBC_NAMESPACE::scanf_core::ReadBuffer rb{.buffer: const_cast<char *>(str), .buff_len: 1000000};
25 LIBC_NAMESPACE::scanf_core::Reader reader(&rb);
26
27 for (size_t i = 0; i < sizeof("abc"); ++i) {
28 ASSERT_EQ(str[i], reader.getc());
29 }
30}
31
32TEST(LlvmLibcScanfStringReaderTest, ReadAndReverse) {
33 const char *str = "abcDEF123";
34 LIBC_NAMESPACE::scanf_core::ReadBuffer rb{.buffer: const_cast<char *>(str), .buff_len: 1000000};
35 LIBC_NAMESPACE::scanf_core::Reader reader(&rb);
36
37 for (size_t i = 0; i < 5; ++i) {
38 ASSERT_EQ(str[i], reader.getc());
39 }
40
41 // Move back by 3, cursor should now be on 2
42 reader.ungetc(c: str[4]);
43 reader.ungetc(c: str[3]);
44 reader.ungetc(c: str[2]);
45
46 for (size_t i = 2; i < 7; ++i) {
47 ASSERT_EQ(str[i], reader.getc());
48 }
49
50 // Move back by 2, cursor should now be on 5
51 reader.ungetc(c: str[6]);
52 reader.ungetc(c: str[5]);
53
54 for (size_t i = 5; i < 10; ++i) {
55 ASSERT_EQ(str[i], reader.getc());
56 }
57
58 // Move back by 10, which should be back to the start.
59 for (size_t i = 0; i < 10; ++i) {
60 reader.ungetc(c: str[9 - i]);
61 }
62
63 // Check the whole string.
64 for (size_t i = 0; i < sizeof("abcDEF123"); ++i) {
65 ASSERT_EQ(str[i], reader.getc());
66 }
67}
68

source code of libc/test/src/stdio/scanf_core/reader_test.cpp