Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unit test to make sure iterator_input_adapter advances iterators correctly #3548

Merged
merged 1 commit into from
Jul 23, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions tests/src/unit-deserialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ SOFTWARE.
using nlohmann::json;

#include <iostream>
#include <iterator>
#include <sstream>
#include <valarray>

Expand Down Expand Up @@ -184,6 +185,52 @@ struct SaxEventLoggerExitAfterStartArray : public SaxEventLogger
return false;
}
};

template <typename T>
class proxy_iterator
{
public:
using iterator = typename T::iterator;
using value_type = typename std::iterator_traits<iterator>::value_type;
using reference = typename std::iterator_traits<iterator>::reference;
using pointer = typename std::iterator_traits<iterator>::pointer;
using difference_type =
typename std::iterator_traits<iterator>::difference_type;
using iterator_category = std::input_iterator_tag;

proxy_iterator() = default;
explicit proxy_iterator(iterator& it) : m_it(std::addressof(it)) {}

proxy_iterator& operator++()
{
++*m_it;
return *this;
}

proxy_iterator& operator--()
{
--*m_it;
return *this;
}

bool operator==(const proxy_iterator& rhs) const
{
return (m_it && rhs.m_it) ? (*m_it == *rhs.m_it) : (m_it == rhs.m_it);
}

bool operator!=(const proxy_iterator& rhs) const
{
return !(*this == rhs);
}

reference operator*() const
{
return **m_it;
}

private:
iterator* m_it = nullptr;
};
} // namespace

TEST_CASE("deserialization")
Expand Down Expand Up @@ -538,6 +585,28 @@ TEST_CASE("deserialization")
CHECK(l.events.size() == 1);
CHECK(l.events == std::vector<std::string>({"parse_error(1)"}));
}

SECTION("iterator_input_adapter advances iterators correctly")
{
using nlohmann::json;
using nlohmann::detail::input_format_t;
using nlohmann::detail::json_sax_dom_parser;
using proxy = proxy_iterator<std::string>;

std::string str1 = "[1]";
std::string str2 = "[2]";
std::string str = str1 + str2;

auto first = str.begin();
auto last = str.end();
json j;
json_sax_dom_parser<json> sax(j, true);

CHECK(json::sax_parse(proxy(first), proxy(last), &sax,
input_format_t::json, false));
CHECK(j.dump() == str1);
CHECK(std::string(first, last) == str2);
}
}

// these cases are required for 100% line coverage
Expand Down