Skip to content

Commit

Permalink
feat(buffer.hpp): take_n, peek_n, after_n, after_n_m return std::null…
Browse files Browse the repository at this point in the history
…opt when n is less than 0
  • Loading branch information
Adamska1008 committed Sep 15, 2024
1 parent 411ff86 commit 4f6daca
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
18 changes: 17 additions & 1 deletion src/buffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,12 @@ namespace myxml

std::optional<std::string_view> buffer::peek_n(int n) const
{
if (n < 0)
{
return std::nullopt;
}
auto [ptr, len] = this->base();
if (_offset >= len)
if (_offset + n >= len)
{
return std::nullopt;
}
Expand All @@ -45,6 +49,10 @@ namespace myxml

std::optional<char> buffer::after_n(int n) const
{
if (n < 0)
{
return std::nullopt;
}
auto [ptr, len] = this->base();
if (_offset + n > len)
{
Expand All @@ -55,6 +63,10 @@ namespace myxml

std::optional<std::string_view> buffer::after_n_m(int n, int m) const
{
if (n < 0 || m < 0)
{
return std::nullopt;
}
auto [ptr, len] = this->base();
if (_offset + n + m > len)
{
Expand All @@ -77,6 +89,10 @@ namespace myxml

std::optional<std::string_view> buffer::take_n(int n)
{
if (n < 0)
{
return std::nullopt;
}
auto [ptr, len] = this->base();
if (_offset + n > len)
{
Expand Down
18 changes: 17 additions & 1 deletion tests/buffer_test.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include <catch2/catch_test_macros.hpp>
#include "myxml/buffer.hpp"
#include "myxml/xmlfile.hpp"
#include <iostream>

TEST_CASE("String Buffer", "[buffer]")
{
Expand All @@ -12,12 +13,27 @@ TEST_CASE("String Buffer", "[buffer]")
REQUIRE(sb.take_n(3) == "Hel");
REQUIRE(sb.after_n(1) == 'o');
REQUIRE(sb.after_n_m(1, 2) == "o,");
REQUIRE(sb.peek_n(11) == std::nullopt);
REQUIRE(sb.take_n(11) == std::nullopt);
REQUIRE(sb.take_n(10) == "lo, world!");
REQUIRE(sb.take() == std::nullopt);
REQUIRE(sb.take_n(2) == std::nullopt);
REQUIRE(sb.peek() == std::nullopt);
REQUIRE(sb.peek_n(2) == std::nullopt);
}

SECTION("Location", "[buffer]")
SECTION("Take test")
{
myxml::string_buffer sb = "Hello";
REQUIRE(sb.take() == 'H');
REQUIRE(sb.take() == 'e');
REQUIRE(sb.take() == 'l');
REQUIRE(sb.take() == 'l');
REQUIRE(sb.take() == 'o');
REQUIRE(sb.take() == std::nullopt);
}

SECTION("Location")
{
myxml::string_buffer sb = "Hello, world!\nLine2";

Expand Down

0 comments on commit 4f6daca

Please sign in to comment.