Skip to content
Open
Show file tree
Hide file tree
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
53 changes: 42 additions & 11 deletions include/msgpack/v2/x3_parse.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@
#include <cstdint>
#include <vector>

#if defined(__has_include)
#if __has_include(<version>)
#include <version>
#endif
#endif

// Since C++20 the standard library can say exactly whether an iterator walks contiguous memory.
#if defined(__cpp_lib_ranges) && __cpp_lib_ranges >= 201911L
#define MSGPACK_X3_EXACT_CONTIGUITY 1
#endif

#if __GNUC__ >= 4
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
Expand Down Expand Up @@ -124,6 +135,36 @@ struct index_size {
type_t type;
};

// Whether [first, last) is one block of memory, so that &*first can be read as last - first bytes.
//
// With C++20 the answer is exact: only an iterator that models std::contiguous_iterator is contiguous.
// Before that only an O(1) check is possible: a random-access range whose first and last elements are
// exactly size - 1 bytes apart is taken as contiguous. A container whose first and last blocks happen to
// be that far apart while a block between them lives elsewhere fools it (for example a std::deque with
// an allocator that hands its blocks out in a particular order), and the bytes after the first block are
// then read in place. An iterator that is not random access is never contiguous.
#if defined(MSGPACK_X3_EXACT_CONTIGUITY)
template <typename It>
inline bool is_contiguous(It, It) {
return std::contiguous_iterator<It>;
}
#else
template <typename It>
inline bool is_contiguous(It first, It last, std::random_access_iterator_tag) {
return first == last ||
reinterpret_cast<std::uintptr_t>(&*(last - 1)) - reinterpret_cast<std::uintptr_t>(&*first)
== static_cast<std::uintptr_t>(last - first - 1);
}
template <typename It>
inline bool is_contiguous(It, It, std::input_iterator_tag) {
return false;
}
template <typename It>
inline bool is_contiguous(It first, It last) {
return is_contiguous(first, last, typename std::iterator_traits<It>::iterator_category());
}
#endif

template <typename Visitor>
struct app_specific {
template <typename Vis>
Expand All @@ -139,23 +180,13 @@ struct app_specific {
char const* contiguous(Range const& r) {
auto first = r.begin();
auto last = r.end();
if (is_contiguous(first, last, typename std::iterator_traits<decltype(first)>::iterator_category())) {
if (is_contiguous(first, last)) {
return &*first;
}
buf.assign(first, last);
return buf.data();
}
private:
template <typename It>
static bool is_contiguous(It first, It last, std::random_access_iterator_tag) {
// the range is not empty here
return reinterpret_cast<std::uintptr_t>(&*(last - 1)) - reinterpret_cast<std::uintptr_t>(&*first)
== static_cast<std::uintptr_t>(last - first - 1);
}
template <typename It>
static bool is_contiguous(It, It, std::input_iterator_tag) {
return false;
}
std::vector<char> buf;
};

Expand Down
14 changes: 14 additions & 0 deletions include/msgpack/v2/x3_unpack.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
#include "msgpack/x3_unpack_decl.hpp"
#include "msgpack/x3_parse.hpp"

#include <cstddef>

namespace msgpack {

/// @cond
Expand All @@ -29,13 +31,25 @@ MSGPACK_API_VERSION_NAMESPACE(v2) {

namespace detail {

// Reference mode hands out pointers into the input, so it is only safe when
// the whole input is one contiguous block that the caller keeps alive.
// Buffering iterators such as boost::spirit::multi_pass reallocate their
// internal storage while parsing; for those (and any non-contiguous input,
// see is_contiguous in x3_parse.hpp) the data is always copied.
inline bool never_reference(msgpack::type::object_type, std::size_t, void*) {
return false;
}

template <typename Iterator>
inline void
unpack_imp(Iterator&& begin, Iterator&& end,
msgpack::zone& result_zone, msgpack::object& result, bool& referenced,
unpack_reference_func f, void* user_data,
unpack_limit const& limit)
{
if (f && !is_contiguous(begin, end)) {
f = never_reference;
}
create_object_visitor v(f, user_data, limit);
v.set_zone(result_zone);
referenced = false;
Expand Down
165 changes: 165 additions & 0 deletions test/msgpack_x3_parse.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@
#include <list>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <cstddef>
#include <cstdint>

#include <boost/spirit/include/support_multi_pass.hpp>

#define BOOST_TEST_MODULE MSGPACK_X3_PARSE
#include <boost/test/unit_test.hpp>
Expand Down Expand Up @@ -907,4 +913,163 @@ BOOST_AUTO_TEST_CASE(non_contiguous_list_bin) { check_non_contiguous_bin<std::li
BOOST_AUTO_TEST_CASE(non_contiguous_deque_ext) { check_non_contiguous_ext<std::deque<char> >(); }
BOOST_AUTO_TEST_CASE(non_contiguous_list_ext) { check_non_contiguous_ext<std::list<char> >(); }

BOOST_AUTO_TEST_CASE(is_contiguous_helper)
{
std::string s("0123456789");
std::vector<char> v(s.begin(), s.end());
std::list<char> l(s.begin(), s.end());
BOOST_CHECK(msgpack::v2::detail::is_contiguous(s.begin(), s.end()));
BOOST_CHECK(msgpack::v2::detail::is_contiguous(v.begin(), v.end()));
BOOST_CHECK(msgpack::v2::detail::is_contiguous(s.data(), s.data() + s.size()));
BOOST_CHECK(!msgpack::v2::detail::is_contiguous(l.begin(), l.end()));
}

#if defined(MSGPACK_X3_EXACT_CONTIGUITY)
// A random-access range that is not contiguous: element i is blocks[i / 8][i % 8]. The first and the
// last block sit at the two ends of one array and the block between them lives elsewhere, so the first
// and the last element are exactly size - 1 bytes apart. The endpoint check before C++20 cannot tell it
// from a contiguous range; with C++20 the iterator is not a std::contiguous_iterator and the data is copied.
class segmented_iterator {
public:
typedef std::random_access_iterator_tag iterator_category;
typedef char value_type;
typedef std::ptrdiff_t difference_type;
typedef char const* pointer;
typedef char const& reference;
segmented_iterator() : blocks_(nullptr), i_(0) {}
segmented_iterator(char const* const* blocks, difference_type i) : blocks_(blocks), i_(i) {}
reference operator*() const { return blocks_[i_ / 8][i_ % 8]; }
pointer operator->() const { return &**this; }
reference operator[](difference_type n) const { return *(*this + n); }
segmented_iterator& operator++() { ++i_; return *this; }
segmented_iterator operator++(int) { segmented_iterator t(*this); ++i_; return t; }
segmented_iterator& operator--() { --i_; return *this; }
segmented_iterator operator--(int) { segmented_iterator t(*this); --i_; return t; }
segmented_iterator& operator+=(difference_type n) { i_ += n; return *this; }
segmented_iterator& operator-=(difference_type n) { i_ -= n; return *this; }
friend segmented_iterator operator+(segmented_iterator a, difference_type n) { return a += n; }
friend segmented_iterator operator+(difference_type n, segmented_iterator a) { return a += n; }
friend segmented_iterator operator-(segmented_iterator a, difference_type n) { return a -= n; }
friend difference_type operator-(segmented_iterator const& a, segmented_iterator const& b) { return a.i_ - b.i_; }
friend bool operator==(segmented_iterator const& a, segmented_iterator const& b) { return a.i_ == b.i_; }
friend bool operator!=(segmented_iterator const& a, segmented_iterator const& b) { return a.i_ != b.i_; }
friend bool operator<(segmented_iterator const& a, segmented_iterator const& b) { return a.i_ < b.i_; }
friend bool operator>(segmented_iterator const& a, segmented_iterator const& b) { return a.i_ > b.i_; }
friend bool operator<=(segmented_iterator const& a, segmented_iterator const& b) { return a.i_ <= b.i_; }
friend bool operator>=(segmented_iterator const& a, segmented_iterator const& b) { return a.i_ >= b.i_; }
private:
char const* const* blocks_;
difference_type i_;
};

// bin8 with 22 bytes of payload is 24 bytes, laid out in three blocks of 8: the first and the last
// block at the two ends of one arena, the middle block elsewhere.
struct segmented_bin {
std::vector<char> payload;
char arena[24];
char middle[8];
char const* blocks[3];
// blocks points into this object's own arrays
segmented_bin(segmented_bin const&) = delete;
segmented_bin& operator=(segmented_bin const&) = delete;
segmented_bin() : payload(22) {
std::string msg("\xc4\x16", 2);
for (std::size_t i = 0; i < payload.size(); ++i) payload[i] = static_cast<char>('a' + i);
msg.append(payload.begin(), payload.end());
std::fill(arena, arena + 24, 'X');
std::copy(msg.begin(), msg.begin() + 8, arena);
std::copy(msg.begin() + 16, msg.end(), arena + 16);
std::copy(msg.begin() + 8, msg.begin() + 16, middle);
blocks[0] = arena; blocks[1] = middle; blocks[2] = arena + 16;
}
segmented_iterator begin() const { return segmented_iterator(blocks, 0); }
segmented_iterator end() const { return segmented_iterator(blocks, 24); }
};

BOOST_AUTO_TEST_CASE(non_contiguous_segmented_bin_cxx20)
{
segmented_bin m;
BOOST_REQUIRE_EQUAL(reinterpret_cast<std::uintptr_t>(&*(m.end() - 1)) - reinterpret_cast<std::uintptr_t>(&*m.begin()), 23u);
BOOST_CHECK(!msgpack::v2::detail::is_contiguous(m.begin(), m.end()));

auto oh = msgpack::unpack(m.begin(), m.end());
BOOST_CHECK(oh.get().as<std::vector<char> >() == m.payload);
}
#endif // defined(MSGPACK_X3_EXACT_CONTIGUITY)

// Reference mode (zero-copy) must only hand out pointers into the caller's
// own contiguous input. A buffering input iterator such as
// boost::spirit::multi_pass keeps its data in an internal buffer that is
// reallocated while parsing, so those pointers would dangle.
static bool reference_all(msgpack::type::object_type, std::size_t, void*) { return true; }

static std::string pack_strings(int n, std::size_t len) {
std::stringstream ss;
msgpack::packer<std::stringstream> pk(ss);
pk.pack_array(static_cast<uint32_t>(n));
for (int i = 0; i < n; ++i) {
std::string e(len, static_cast<char>('A' + i));
pk.pack_str(static_cast<uint32_t>(e.size()));
pk.pack_str_body(e.data(), static_cast<uint32_t>(e.size()));
}
return ss.str();
}

BOOST_AUTO_TEST_CASE(reference_multi_pass)
{
const int n = 8;
std::string src = pack_strings(n, 600);
std::istringstream iss(src);
iss.unsetf(std::ios::skipws);
typedef std::istreambuf_iterator<char> base_it;
boost::spirit::multi_pass<base_it> first{base_it(iss)};
boost::spirit::multi_pass<base_it> last{base_it()};

bool referenced = true;
auto oh = msgpack::unpack(first, last, referenced, reference_all, nullptr, msgpack::unpack_limit());
BOOST_CHECK(!referenced);
msgpack::object const& o = oh.get();
BOOST_REQUIRE_EQUAL(o.type, msgpack::type::ARRAY);
BOOST_REQUIRE_EQUAL(o.via.array.size, static_cast<uint32_t>(n));
for (int i = 0; i < n; ++i) {
BOOST_CHECK_EQUAL(o.via.array.ptr[i].as<std::string>(), std::string(600, static_cast<char>('A' + i)));
}
}

BOOST_AUTO_TEST_CASE(reference_contiguous_still_zero_copy)
{
std::string src = pack_strings(2, 600);
{
bool referenced = false;
char const* b = src.data();
char const* e = src.data() + src.size();
auto oh = msgpack::unpack(b, e, referenced, reference_all, nullptr, msgpack::unpack_limit());
BOOST_CHECK(referenced);
char const* p = oh.get().via.array.ptr[0].via.str.ptr;
BOOST_CHECK(p >= src.data() && p < src.data() + src.size());
}
{
bool referenced = false;
auto b = src.cbegin();
auto e = src.cend();
auto oh = msgpack::unpack(b, e, referenced, reference_all, nullptr, msgpack::unpack_limit());
BOOST_CHECK(referenced);
char const* p = oh.get().via.array.ptr[0].via.str.ptr;
BOOST_CHECK(p >= src.data() && p < src.data() + src.size());
}
}

#if defined(MSGPACK_X3_EXACT_CONTIGUITY)
BOOST_AUTO_TEST_CASE(reference_segmented_cxx20)
{
segmented_bin m;
bool referenced = true;
auto b = m.begin();
auto e = m.end();
auto oh = msgpack::unpack(b, e, referenced, reference_all, nullptr, msgpack::unpack_limit());
BOOST_CHECK(!referenced);
BOOST_CHECK(oh.get().as<std::vector<char> >() == m.payload);
}
#endif // defined(MSGPACK_X3_EXACT_CONTIGUITY)

#endif // defined(MSGPACK_USE_X3_PARSE) && MSGPACK_DEFAULT_API_VERSION >= 2
Loading