Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
4 changes: 4 additions & 0 deletions src/bsoncxx/json.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -89,5 +89,9 @@ document::value BSONCXX_CALL from_json(stdx::string_view json) {
return document::value{buf, length, bson_free_deleter};
}

document::value BSONCXX_CALL operator"" _bson(const char* str, size_t) {
return from_json(str);
}

BSONCXX_INLINE_NAMESPACE_END
} // namespace bsoncxx
14 changes: 13 additions & 1 deletion src/bsoncxx/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ BSONCXX_API std::string BSONCXX_CALL to_json(document::view view,
ExtendedJsonMode mode = ExtendedJsonMode::k_legacy);

///
/// Constructs a new document::value from the provided JSON text
/// Constructs a new document::value from the provided JSON text.
///
/// @param 'json'
/// A string_view into a JSON document
Expand All @@ -68,6 +68,18 @@ BSONCXX_API std::string BSONCXX_CALL to_json(document::view view,
///
BSONCXX_API document::value BSONCXX_CALL from_json(stdx::string_view json);

///
/// Constructs a new document::value from the provided JSON text.
///
/// @param 'json'
/// A string into a JSON document
///
/// @returns A document::value if conversion worked.
///
/// @throws bsoncxx::exception with error details if the conversion failed.
///
BSONCXX_API document::value BSONCXX_CALL operator"" _bson(const char* json, size_t);

BSONCXX_INLINE_NAMESPACE_END
} // namespace bsoncxx

Expand Down
21 changes: 21 additions & 0 deletions src/bsoncxx/test/json.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,25 @@ TEST_CASE("CXX-1246: Canonical Extended JSON") {
output ==
R"({ "number" : { "$numberInt" : "42" }, "bin" : { "$binary" : { "base64": "ZGVhZGJlZWY=", "subType" : "04" } } })");
}

TEST_CASE("UDL _bson works like from_json()") {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For completeness' sake, please add a test for the empty document "{}"

using namespace bsoncxx;

SECTION("_bson and from_json() return the same value") {
auto expected_value = from_json(k_valid_json);
auto actual_value = R"({ "a" : 1, "b" : 2.0 })"_bson;
REQUIRE(actual_value == expected_value);
}

SECTION("_bson returns an empty document") {
REQUIRE("{}"_bson == from_json("{ }"));
REQUIRE("{}"_bson.view().empty());
}

SECTION("_bson throws an exception with invalid json") {
REQUIRE_THROWS_AS(R"({])"_bson, bsoncxx::exception);
REQUIRE_THROWS_AS(""_bson, bsoncxx::exception);
}
}

} // namespace