Skip to content

Commit

Permalink
Enc: populate encoder with optional
Browse files Browse the repository at this point in the history
If passed optional is not empty, underlying value is encoded - optional
itself is not present in the resulting MsgPack. If the optional is empty,
it is encoded as MP_NIL.
  • Loading branch information
drewdzzz authored and alyapunov committed Nov 22, 2023
1 parent aefa525 commit 0aad721
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
6 changes: 6 additions & 0 deletions src/mpp/Enc.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,12 @@ encode(CONT &cont, tnt::CStr<C...> prefix,
} if constexpr(mpp::has_enc_rule_v<T>) {
const auto& rule = mpp::get_enc_rule<T>();
return encode(cont, prefix, ais, subst(rule, t), more...);
} else if constexpr(tnt::is_optional_v<U>) {
static_assert(!is_wrapped_family_v<T> && !is_wrapped_raw_v<T>);
if (u.has_value())
return encode(cont, prefix, ais, u.value(), more...);
else
return encode(cont, prefix, ais, nullptr, more...);
} else if constexpr(is_wrapped_raw_v<T>) {
if constexpr(std::is_base_of_v<ChildrenTag, U>) {
using V = typename U::type;
Expand Down
14 changes: 11 additions & 3 deletions test/EncDecTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1256,7 +1256,8 @@ test_optional()
bool ok;

TEST_CASE("number");
mpp::encode(buf, 100, nullptr);
mpp::encode(buf, std::optional<int>(100), std::optional<int>(),
std::optional<int>(42));

auto run = buf.begin<true>();
std::optional<int> opt_num;
Expand All @@ -1269,11 +1270,18 @@ test_optional()
fail_unless(ok);
fail_unless(!opt_num.has_value());

ok = mpp::decode(run, opt_num);
fail_unless(ok);
fail_unless(opt_num.has_value());
fail_unless(opt_num.value() == 42);

buf.flush();

TEST_CASE("containers with numbers");
int null_idx = 4;
mpp::encode(buf, mpp::as_arr(std::forward_as_tuple(0, 1, 2, 3, nullptr, 5)));
mpp::encode(buf, std::make_optional(mpp::as_arr(
std::forward_as_tuple(0, std::make_optional(1), 2, 3, std::optional<int>(), 5)
)));
mpp::encode(buf, nullptr);
std::vector<std::optional<int>> opt_num_arr;
std::set<std::optional<int>> opt_num_set;
Expand Down Expand Up @@ -1345,7 +1353,7 @@ test_optional()
TEST_CASE("objects");
Body wr;
wr.gen();
mpp::encode(buf, wr, nullptr);
mpp::encode(buf, std::optional<Body>(wr), std::optional<Body>());

run = buf.begin<true>();
std::optional<Body> rd;
Expand Down

0 comments on commit 0aad721

Please sign in to comment.