diff --git a/src/bsoncxx/json.cpp b/src/bsoncxx/json.cpp index 2cd81dbe35..21de2a5304 100644 --- a/src/bsoncxx/json.cpp +++ b/src/bsoncxx/json.cpp @@ -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 len) { + return from_json(stdx::string_view{str, len}); +} + BSONCXX_INLINE_NAMESPACE_END } // namespace bsoncxx diff --git a/src/bsoncxx/json.hpp b/src/bsoncxx/json.hpp index b7603c98bf..1353701cac 100644 --- a/src/bsoncxx/json.hpp +++ b/src/bsoncxx/json.hpp @@ -57,10 +57,10 @@ 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 +/// A string_view into a JSON document. /// /// @returns A document::value if conversion worked. /// @@ -68,6 +68,22 @@ 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. This is the UDL version of +/// from_json(). +/// +/// @param 'json' +/// A string into a JSON document. +/// +/// @param 'len' +/// The length of the JSON string. This is calculated automatically upon use of the UDL. +/// +/// @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 len); + BSONCXX_INLINE_NAMESPACE_END } // namespace bsoncxx diff --git a/src/bsoncxx/test/json.cpp b/src/bsoncxx/test/json.cpp index ad34dbda98..d8c756dc29 100644 --- a/src/bsoncxx/test/json.cpp +++ b/src/bsoncxx/test/json.cpp @@ -112,4 +112,27 @@ 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()") { + 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); + REQUIRE("[1, 2, 3]"_bson == from_json("[1, 2, 3]")); + } + + 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