From 1d0c37fc6687e48f662d4ac9feee809507de5fb7 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sat, 13 Jan 2024 18:27:26 +0100 Subject: [PATCH] Added functions for writing root --- include/rfl/bson/Writer.hpp | 46 ++++++++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 13 deletions(-) diff --git a/include/rfl/bson/Writer.hpp b/include/rfl/bson/Writer.hpp index 0b8586ab..9cacc957 100644 --- a/include/rfl/bson/Writer.hpp +++ b/include/rfl/bson/Writer.hpp @@ -21,7 +21,9 @@ namespace bson { /// Please refer to https://mongoc.org/libbson/current/api.html class Writer { - using ParentType = std::variant; + struct IsRoot {}; + + using ParentType = std::variant; public: struct BSONOutputArray { @@ -44,22 +46,32 @@ class Writer { using OutputObjectType = BSONOutputObject; using OutputVarType = BSONOutputVar; - Writer() : { bson_init(&doc_); } + Writer() : {} ~Writer() = default; - // TODO - OutputArrayType array_as_root(const size_t _size) const noexcept {} + OutputArrayType array_as_root(const size_t _size) const noexcept { + bson_array_builder_t* val = bson_array_builder_new(); + return OutputObjectType(val, IsRoot{}); + } - // TODO - OutputObjectType object_as_root(const size_t _size) const noexcept {} + OutputObjectType object_as_root(const size_t _size) const noexcept { + bson_t val; + bson_init(&val); + return OutputObjectType(val, IsRoot{}); + } - // TODO - OutputVarType null_as_root() const noexcept {} + OutputVarType null_as_root() const noexcept { + // Appears to be unsupported by the BSON C API. + return OutputVarType{}; + } - // TODO template - OutputVarType value_as_root(const T& _var) const noexcept {} + OutputVarType value_as_root(const T& _var) const noexcept { + static_assert(rfl::always_false_v, + "BSON only allows arrays or objects as its root."); + return OutputVarType{}; + } OutputArrayType add_array_to_array(const size_t _size, OutputArrayType* _parent) const noexcept { @@ -154,8 +166,12 @@ class Writer { using Type = std::remove_cvref_t; if constexpr (std::is_same()) { bson_array_builder_append_array_builder_end(_parent, _arr->val_); - } else { + } else if constexpr (std::is_same()) { bson_append_array_end(_parent, _arr->val_); + } else if constexpr (std::is_same()) { + bson_array_builder_build(_arr->val_, doc_); + } else { + static_assert(rfl::always_false_v, "Unsupported type."); } }; std::visit(handle, _arr->parent_); @@ -166,14 +182,18 @@ class Writer { using Type = std::remove_cvref_t; if constexpr (std::is_same()) { bson_array_builder_append_document_end(_parent, _arr->val_); - } else { + } else if constexpr (std::is_same()) { bson_append_document_end(_parent, _arr->val_); + } else if constexpr (std::is_same()) { + doc_ = _obj->val_; + } else { + static_assert(rfl::always_false_v, "Unsupported type."); } }; std::visit(handle, _arr->parent_); } - public: + private: bson_t doc_; };