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

RFC: Allow topic extraction via json::decode() #443

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
10 changes: 9 additions & 1 deletion libbroker/broker/format/json.cc
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,20 @@ size_t encode_to_buf(timestamp value, std::array<char, 32>& buf) {
return pos;
}

error decode(std::string_view str, variant& result) {
error decode(std::string_view str, variant& result, std::string* topic) {
// Parse the JSON text into a JSON object.
auto val = caf::json_value::parse_shallow(str);
if (!val)
return error{ec::invalid_json};
auto obj = val->to_object();

if (topic) {
auto maybe_topic = obj.value("topic");
if (maybe_topic.is_string())
*topic = std::string{maybe_topic.to_string().data(),
maybe_topic.to_string().size()};
}

// Try to convert the JSON structure into our binary serialization format.
std::vector<std::byte> buf;
buf.reserve(512); // Allocate some memory to avoid small allocations.
Expand Down
7 changes: 5 additions & 2 deletions libbroker/broker/format/json.hh
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include "broker/config.hh"
#include "broker/data.hh"
#include "broker/error.hh"
#include "broker/fwd.hh"
#include "broker/message.hh"

Expand Down Expand Up @@ -389,7 +390,9 @@ OutIter encode(const data_message& msg, OutIter out) {
/// Tries to decode a JSON object from `str`. On success, the result is stored
/// in `result` and the functions a default-constructed `error`. Otherwise, the
/// function returns a non-empty error and leaves `result` in an unspecified
/// state.
error decode(std::string_view str, variant& result);
/// state. If `topic` is not NULL and the top-level object contains a topic
/// key, it is stored into the string instance pointed to.
error decode(std::string_view str, variant& result,
std::string* topic = nullptr);

} // namespace broker::format::json::v1
Loading