From e079e16682f5af42897a778fc7b03f9392843ba0 Mon Sep 17 00:00:00 2001 From: WiktorNowak Date: Mon, 13 Jan 2025 06:33:27 +0100 Subject: [PATCH] feat: add custom delimiter to file iterator --- include/rusty_iterators/file_iterator.hpp | 10 ++++++---- tests/file_iterator.test.cpp | 16 ++++++++++++++++ tests/test_delim.txt | 1 + 3 files changed, 23 insertions(+), 4 deletions(-) create mode 100644 tests/test_delim.txt diff --git a/include/rusty_iterators/file_iterator.hpp b/include/rusty_iterators/file_iterator.hpp index 146a6ff..a0d92d5 100644 --- a/include/rusty_iterators/file_iterator.hpp +++ b/include/rusty_iterators/file_iterator.hpp @@ -26,7 +26,7 @@ class FileIterator : public IterInterface> { public: - explicit FileIterator(const std::string& filePath) + explicit FileIterator(const std::string& filePath, char delimiter = '\n') { std::ifstream is{filePath}; if (!is.is_open()) @@ -34,7 +34,7 @@ class FileIterator throw std::runtime_error{"Could not open the file."}; } std::string nextLine; - while (std::getline(is, nextLine)) + while (std::getline(is, nextLine, delimiter)) { fileLines.push_back(std::move(nextLine)); } @@ -64,7 +64,8 @@ class FileIterator : public IterInterface> { public: - explicit FileIterator(const std::string& filePath) : is(filePath) + explicit FileIterator(const std::string& filePath, char delimiter = '\n') + : is(filePath), delimiter(delimiter) { if (!is.is_open()) { @@ -75,7 +76,7 @@ class FileIterator auto next() -> std::optional { std::string nextLine; - [[unlikely]] if (!std::getline(is, nextLine)) + [[unlikely]] if (!std::getline(is, nextLine, delimiter)) { return std::nullopt; } @@ -90,5 +91,6 @@ class FileIterator private: std::ifstream is; + char delimiter; }; } // namespace rusty_iterators::iterator diff --git a/tests/file_iterator.test.cpp b/tests/file_iterator.test.cpp index 199ab50..9d37e86 100644 --- a/tests/file_iterator.test.cpp +++ b/tests/file_iterator.test.cpp @@ -47,6 +47,14 @@ TEST(TestLazyFileIterator, TestSumIterator) ASSERT_EQ(it.sum(), std::string{"1234"}); } +TEST(TestLazyFileIterator, TestCustomDelimiter) +{ + auto testFileName = std::string{"./tests/test_delim.txt"}; + auto it = FileIterator{testFileName, ','}; + + EXPECT_THAT(it.collect(), ElementsAreArray({"1", "2", "3", "4", "5\n"})); +} + TEST(TestBufferedFileIterator, TestFileDoesNotExist) { auto testFileName = std::string{"./tests/abc.jpg"}; @@ -90,3 +98,11 @@ TEST(TestBufferedFileIterator, TestCopyBufferedIterator) EXPECT_THAT(it.collect(), ElementsAreArray({"3", "4"})); EXPECT_THAT(cp.collect(), ElementsAreArray({"2", "3", "4"})); } + +TEST(TestBufferedFileIterator, TestCustomDelimiter) +{ + auto testFileName = std::string{"./tests/test_delim.txt"}; + auto it = FileIterator{testFileName, ','}; + + EXPECT_THAT(it.collect(), ElementsAreArray({"1", "2", "3", "4", "5\n"})); +} diff --git a/tests/test_delim.txt b/tests/test_delim.txt new file mode 100644 index 0000000..2f110d5 --- /dev/null +++ b/tests/test_delim.txt @@ -0,0 +1 @@ +1,2,3,4,5