Added BSON support; #22

This commit is contained in:
Patrick Urbanke
2024-01-19 16:09:26 +01:00
parent 151e606264
commit 5a34c9bea8
82 changed files with 2267 additions and 14 deletions
+12
View File
@@ -0,0 +1,12 @@
#ifndef RFL_BSON_HPP_
#define RFL_BSON_HPP_
#include "bson/Parser.hpp"
#include "bson/Reader.hpp"
#include "bson/Writer.hpp"
#include "bson/load.hpp"
#include "bson/read.hpp"
#include "bson/save.hpp"
#include "bson/write.hpp"
#endif
+17
View File
@@ -0,0 +1,17 @@
#ifndef RFL_BSON_PARSER_HPP_
#define RFL_BSON_PARSER_HPP_
#include "../parsing/Parser.hpp"
#include "Reader.hpp"
#include "Writer.hpp"
namespace rfl {
namespace bson {
template <class T>
using Parser = parsing::Parser<Reader, Writer, T>;
}
} // namespace rfl
#endif
+228
View File
@@ -0,0 +1,228 @@
#ifndef RFL_BSON_READER_HPP_
#define RFL_BSON_READER_HPP_
#include <bson/bson.h>
#include <array>
#include <concepts>
#include <exception>
#include <map>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <vector>
#include "../Box.hpp"
#include "../Result.hpp"
#include "../always_false.hpp"
namespace rfl {
namespace bson {
/// Please refer to https://mongoc.org/libbson/current/api.html
struct Reader {
struct BSONValue {
bson_value_t val_;
};
struct BSONInputArray {
BSONValue* val_;
};
struct BSONInputObject {
BSONValue* val_;
};
struct BSONInputVar {
BSONValue* val_;
};
using InputArrayType = BSONInputArray;
using InputObjectType = BSONInputObject;
using InputVarType = BSONInputVar;
template <class T>
static constexpr bool has_custom_constructor = (requires(InputVarType var) {
T::from_bson_obj(var);
});
rfl::Result<InputVarType> get_field(
const std::string& _name, const InputObjectType& _obj) const noexcept {
bson_t b;
bson_iter_t iter;
const auto doc = _obj.val_->val_.value.v_doc;
if (bson_init_static(&b, doc.data, doc.data_len)) {
if (bson_iter_init(&iter, &b)) {
while (bson_iter_next(&iter)) {
auto key = std::string(bson_iter_key(&iter));
if (key == _name) {
return to_input_var(&iter);
}
}
}
}
return Error("No field named '" + _name + "' was found.");
}
bool is_empty(const InputVarType& _var) const noexcept {
return _var.val_->val_.value_type == BSON_TYPE_NULL;
}
template <class T>
rfl::Result<T> to_basic_type(const InputVarType& _var) const noexcept {
const auto btype = _var.val_->val_.value_type;
const auto value = _var.val_->val_.value;
if constexpr (std::is_same<std::remove_cvref_t<T>, std::string>()) {
switch (btype) {
case BSON_TYPE_UTF8:
return std::string(value.v_utf8.str, value.v_utf8.len);
case BSON_TYPE_SYMBOL:
return std::string(value.v_symbol.symbol, value.v_symbol.len);
default:
return rfl::Error(
"Could not cast to string. The type must be UTF8 or symbol.");
}
} else if constexpr (std::is_same<std::remove_cvref_t<T>, bool>()) {
if (btype != BSON_TYPE_BOOL) {
return rfl::Error("Could not cast to boolean.");
}
return value.v_bool;
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>() ||
std::is_integral<std::remove_cvref_t<T>>()) {
switch (btype) {
case BSON_TYPE_DOUBLE:
return static_cast<T>(value.v_double);
case BSON_TYPE_INT32:
return static_cast<T>(value.v_int32);
case BSON_TYPE_INT64:
return static_cast<T>(value.v_int64);
case BSON_TYPE_DATE_TIME:
return static_cast<T>(value.v_datetime);
default:
return rfl::Error(
"Could not cast to numeric value. The type must be double, "
"int32, int64 or date_time.");
}
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
}
rfl::Result<InputArrayType> to_array(
const InputVarType& _var) const noexcept {
const auto btype = _var.val_->val_.value_type;
if (btype != BSON_TYPE_ARRAY && btype != BSON_TYPE_DOCUMENT) {
return Error("Could not cast to an array.");
}
return InputArrayType{_var.val_};
}
template <size_t size, class FunctionType>
std::array<std::optional<InputVarType>, size> to_fields_array(
const FunctionType& _fct, const InputObjectType& _obj) const noexcept {
std::array<std::optional<InputVarType>, size> f_arr;
bson_t b;
bson_iter_t iter;
const auto doc = _obj.val_->val_.value.v_doc;
if (bson_init_static(&b, doc.data, doc.data_len)) {
if (bson_iter_init(&iter, &b)) {
while (bson_iter_next(&iter)) {
const char* k = bson_iter_key(&iter);
const auto ix = _fct(std::string_view(k));
if (ix != -1) {
f_arr[ix] = to_input_var(&iter);
}
}
}
}
return f_arr;
}
rfl::Result<std::vector<std::pair<std::string, InputVarType>>> to_map(
const InputObjectType& _obj) const noexcept {
std::vector<std::pair<std::string, InputVarType>> map;
bson_t b;
bson_iter_t iter;
const auto doc = _obj.val_->val_.value.v_doc;
if (bson_init_static(&b, doc.data, doc.data_len)) {
if (bson_iter_init(&iter, &b)) {
while (bson_iter_next(&iter)) {
auto key = std::string(bson_iter_key(&iter));
map.emplace_back(std::make_pair(std::move(key), to_input_var(&iter)));
}
}
}
return map;
}
rfl::Result<InputObjectType> to_object(
const InputVarType& _var) const noexcept {
const auto btype = _var.val_->val_.value_type;
if (btype != BSON_TYPE_DOCUMENT) {
return Error("Could not cast to a document.");
}
return InputObjectType{_var.val_};
}
std::vector<InputVarType> to_vec(const InputArrayType& _arr) const noexcept {
std::vector<InputVarType> vec;
bson_t b;
bson_iter_t iter;
const auto doc = _arr.val_->val_.value.v_doc;
if (bson_init_static(&b, doc.data, doc.data_len)) {
if (bson_iter_init(&iter, &b)) {
while (bson_iter_next(&iter)) {
vec.push_back(to_input_var(&iter));
}
}
}
return vec;
}
template <class T>
rfl::Result<T> use_custom_constructor(
const InputVarType& _var) const noexcept {
try {
return T::from_bson_obj(_var);
} catch (std::exception& e) {
return rfl::Error(e.what());
}
}
private:
struct BSONValues {
std::vector<rfl::Box<BSONValue>> vec_;
~BSONValues() {
for (auto& v : vec_) {
bson_value_destroy(&(v->val_));
}
}
};
private:
InputVarType to_input_var(bson_iter_t* _iter) const noexcept {
values_->vec_.emplace_back(rfl::Box<BSONValue>::make());
auto* last_value = values_->vec_.back().get();
bson_value_copy(bson_iter_value(_iter), &last_value->val_);
return InputVarType{last_value};
}
private:
/// Contains the values inside the object.
rfl::Ref<BSONValues> values_;
};
} // namespace bson
} // namespace rfl
#endif // JSON_PARSER_HPP_
+221
View File
@@ -0,0 +1,221 @@
#ifndef RFL_BSON_WRITER_HPP_
#define RFL_BSON_WRITER_HPP_
#include <bson/bson.h>
#include <exception>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <variant>
#include <vector>
#include "../Box.hpp"
#include "../Ref.hpp"
#include "../Result.hpp"
#include "../always_false.hpp"
namespace rfl {
namespace bson {
/// Please refer to https://mongoc.org/libbson/current/api.html
class Writer {
struct BSONType {
bson_t val_;
};
struct IsArray {
bson_array_builder_t* ptr_;
};
struct IsObject {
bson_t* ptr_;
};
struct IsRoot {};
using ParentType = std::variant<IsArray, IsObject, IsRoot>;
public:
struct BSONOutputArray {
BSONOutputArray(bson_array_builder_t* _val, ParentType _parent)
: parent_(_parent), val_(_val) {}
ParentType parent_;
bson_array_builder_t* val_;
};
struct BSONOutputObject {
BSONOutputObject(bson_t* _val, ParentType _parent)
: parent_(_parent), val_(_val) {}
ParentType parent_;
bson_t* val_;
};
struct BSONOutputVar {};
using OutputArrayType = BSONOutputArray;
using OutputObjectType = BSONOutputObject;
using OutputVarType = BSONOutputVar;
Writer(bson_t* _doc) : doc_(_doc) {}
~Writer() = default;
OutputArrayType array_as_root(const size_t _size) const noexcept {
bson_array_builder_t* val = bson_array_builder_new();
return OutputArrayType(val, IsRoot{});
}
OutputObjectType object_as_root(const size_t _size) const noexcept {
return OutputObjectType(doc_, IsRoot{});
}
OutputVarType null_as_root() const noexcept {
// Appears to be unsupported by the BSON C API.
return OutputVarType{};
}
template <class T>
OutputVarType value_as_root(const T& _var) const noexcept {
static_assert(rfl::always_false_v<T>,
"BSON only allows arrays or objects as its root.");
return OutputVarType{};
}
OutputArrayType add_array_to_array(const size_t _size,
OutputArrayType* _parent) const noexcept {
bson_array_builder_t* val;
bson_array_builder_append_array_builder_begin(_parent->val_, &val);
return OutputArrayType(val, IsArray{_parent->val_});
}
OutputArrayType add_array_to_object(
const std::string& _name, const size_t _size,
OutputObjectType* _parent) const noexcept {
bson_array_builder_t* val;
bson_append_array_builder_begin(_parent->val_, _name.c_str(),
static_cast<int>(_name.size()), &val);
return OutputArrayType(val, IsObject{_parent->val_});
}
OutputObjectType add_object_to_array(
const size_t _size, OutputArrayType* _parent) const noexcept {
subdocs_->emplace_back(rfl::Box<BSONType>());
bson_array_builder_append_document_begin(_parent->val_,
&(subdocs_->back()->val_));
return OutputObjectType(&subdocs_->back()->val_, IsArray{_parent->val_});
}
OutputObjectType add_object_to_object(
const std::string& _name, const size_t _size,
OutputObjectType* _parent) const noexcept {
subdocs_->emplace_back(rfl::Box<BSONType>());
bson_append_document_begin(_parent->val_, _name.c_str(),
static_cast<int>(_name.size()),
&(subdocs_->back()->val_));
return OutputObjectType(&subdocs_->back()->val_, IsObject{_parent->val_});
}
template <class T>
OutputVarType add_value_to_array(const T& _var,
OutputArrayType* _parent) const noexcept {
if constexpr (std::is_same<std::remove_cvref_t<T>, std::string>()) {
bson_array_builder_append_utf8(_parent->val_, _var.c_str(),
static_cast<int>(_var.size()));
} else if constexpr (std::is_same<std::remove_cvref_t<T>, bool>()) {
bson_array_builder_append_bool(_parent->val_, _var);
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>()) {
bson_array_builder_append_double(_parent->val_,
static_cast<double>(_var));
} else if constexpr (std::is_integral<std::remove_cvref_t<T>>()) {
bson_array_builder_append_int64(_parent->val_,
static_cast<std::int64_t>(_var));
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
return OutputVarType{};
}
template <class T>
OutputVarType add_value_to_object(const std::string& _name, const T& _var,
OutputObjectType* _parent) const noexcept {
if constexpr (std::is_same<std::remove_cvref_t<T>, std::string>()) {
bson_append_utf8(_parent->val_, _name.c_str(),
static_cast<int>(_name.size()), _var.c_str(),
static_cast<int>(_var.size()));
} else if constexpr (std::is_same<std::remove_cvref_t<T>, bool>()) {
bson_append_bool(_parent->val_, _name.c_str(),
static_cast<int>(_name.size()), _var);
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>()) {
bson_append_double(_parent->val_, _name.c_str(),
static_cast<int>(_name.size()),
static_cast<double>(_var));
} else if constexpr (std::is_integral<std::remove_cvref_t<T>>()) {
bson_append_int64(_parent->val_, _name.c_str(),
static_cast<int>(_name.size()),
static_cast<std::int64_t>(_var));
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
return OutputVarType{};
}
OutputVarType add_null_to_array(OutputArrayType* _parent) const noexcept {
bson_array_builder_append_null(_parent->val_);
return OutputVarType{};
}
OutputVarType add_null_to_object(const std::string& _name,
OutputObjectType* _parent) const noexcept {
bson_append_null(_parent->val_, _name.c_str(),
static_cast<int>(_name.size()));
return OutputVarType{};
}
void end_array(OutputArrayType* _arr) const noexcept {
const auto handle = [&](const auto _parent) {
using Type = std::remove_cvref_t<decltype(_parent)>;
if constexpr (std::is_same<Type, IsArray>()) {
bson_array_builder_append_array_builder_end(_parent.ptr_, _arr->val_);
} else if constexpr (std::is_same<Type, IsObject>()) {
bson_append_array_builder_end(_parent.ptr_, _arr->val_);
} else if constexpr (std::is_same<Type, IsRoot>()) {
bson_array_builder_build(_arr->val_, doc_);
} else {
static_assert(rfl::always_false_v<Type>, "Unsupported type.");
}
};
std::visit(handle, _arr->parent_);
}
void end_object(OutputObjectType* _obj) const noexcept {
const auto handle = [&](const auto _parent) {
using Type = std::remove_cvref_t<decltype(_parent)>;
if constexpr (std::is_same<Type, IsArray>()) {
bson_array_builder_append_document_end(_parent.ptr_, _obj->val_);
} else if constexpr (std::is_same<Type, IsObject>()) {
bson_append_document_end(_parent.ptr_, _obj->val_);
} else if constexpr (std::is_same<Type, IsRoot>()) {
} else {
static_assert(rfl::always_false_v<Type>, "Unsupported type.");
}
};
std::visit(handle, _obj->parent_);
}
private:
/// Pointer to the main document. In BSON, documents are what are usually
/// called objects.
bson_t* const doc_;
/// Contain all of the subdocuments.
const rfl::Ref<std::vector<rfl::Box<BSONType>>> subdocs_;
};
} // namespace bson
} // namespace rfl
#endif // BSON_PARSER_HPP_
+20
View File
@@ -0,0 +1,20 @@
#ifndef RFL_BSON_LOAD_HPP_
#define RFL_BSON_LOAD_HPP_
#include "../Result.hpp"
#include "../io/load_bytes.hpp"
#include "read.hpp"
namespace rfl {
namespace bson {
template <class T>
Result<T> load(const std::string& _fname) {
const auto read_bytes = [](const auto& _bytes) { return read<T>(_bytes); };
return rfl::io::load_bytes(_fname).and_then(read_bytes);
}
} // namespace bson
} // namespace rfl
#endif
+57
View File
@@ -0,0 +1,57 @@
#ifndef RFL_BSON_READ_HPP_
#define RFL_BSON_READ_HPP_
#include <bson/bson.h>
#include <istream>
#include <string>
#include "../internal/wrap_in_rfl_array_t.hpp"
#include "Parser.hpp"
#include "Reader.hpp"
namespace rfl {
namespace bson {
using InputObjectType = typename Reader::InputObjectType;
using InputVarType = typename Reader::InputVarType;
/// Parses an object from a BSON var.
template <class T>
auto read(const InputVarType& _obj) {
const auto r = Reader();
return Parser<T>::read(r, _obj);
}
/// Parses an object from flexbuf using reflection.
template <class T>
Result<internal::wrap_in_rfl_array_t<T>> read(char* _bytes,
const size_t _size) {
Reader::BSONValue value;
value.val_.value.v_doc.data_len = static_cast<uint32_t>(_size);
value.val_.value.v_doc.data = reinterpret_cast<uint8_t*>(_bytes);
value.val_.value_type = BSON_TYPE_DOCUMENT;
auto doc = InputVarType{&value};
auto result = read<T>(doc);
return result;
}
/// Parses an object from BSON using reflection.
template <class T>
auto read(const std::vector<char>& _bytes) {
auto bytes = _bytes;
return read<T>(bytes.data(), bytes.size());
}
/// Parses an object from a stream.
template <class T>
auto read(std::istream& _stream) {
std::istreambuf_iterator<char> begin(_stream), end;
auto bytes = std::vector<char>(begin, end);
return read<T>(bytes.data(), bytes.size());
}
} // namespace bson
} // namespace rfl
#endif
+26
View File
@@ -0,0 +1,26 @@
#ifndef RFL_BSON_SAVE_HPP_
#define RFL_BSON_SAVE_HPP_
#include <fstream>
#include <iostream>
#include <string>
#include "../Result.hpp"
#include "../io/save_bytes.hpp"
#include "write.hpp"
namespace rfl {
namespace bson {
template <class T>
Result<Nothing> save(const std::string& _fname, const T& _obj) {
const auto write_func = [](const auto& _obj, auto& _stream) -> auto& {
return write(_obj, _stream);
};
return rfl::io::save_bytes(_fname, _obj, write_func);
}
} // namespace bson
} // namespace rfl
#endif
+58
View File
@@ -0,0 +1,58 @@
#ifndef RFL_BSON_WRITE_HPP_
#define RFL_BSON_WRITE_HPP_
#include <bson/bson.h>
#include <ostream>
#include <sstream>
#include <string>
#include <utility>
#include "../parsing/Parent.hpp"
#include "Parser.hpp"
namespace rfl {
namespace bson {
/// Returns BSON bytes. Careful: It is the responsibility of the caller to call
/// bson_free on the returned pointer.
template <class T>
std::pair<uint8_t*, size_t> to_buffer(const T& _obj) noexcept {
using ParentType = parsing::Parent<Writer>;
bson_t* doc = nullptr;
uint8_t* buf = nullptr;
size_t buflen = 0;
bson_writer_t* bson_writer =
bson_writer_new(&buf, &buflen, 0, bson_realloc_ctx, NULL);
bson_writer_begin(bson_writer, &doc);
const auto rfl_writer = Writer(doc);
Parser<T>::write(rfl_writer, _obj, typename ParentType::Root{});
bson_writer_end(bson_writer);
const auto len = bson_writer_get_length(bson_writer);
bson_writer_destroy(bson_writer);
return std::make_pair(buf, len);
}
/// Returns BSON bytes.
template <class T>
std::vector<char> write(const T& _obj) noexcept {
auto [buf, len] = to_buffer(_obj);
const auto result = std::vector<char>(reinterpret_cast<char*>(buf),
reinterpret_cast<char*>(buf) + len);
bson_free(buf);
return result;
}
/// Writes a BSON into an ostream.
template <class T>
std::ostream& write(const T& _obj, std::ostream& _stream) noexcept {
auto [buf, len] = to_buffer(_obj);
_stream.write(reinterpret_cast<const char*>(buf), len);
bson_free(buf);
return _stream;
}
} // namespace bson
} // namespace rfl
#endif // BSON_PARSER_HPP_
+2 -2
View File
@@ -1,5 +1,5 @@
#ifndef FLEXBUF_FLEXBUF_HPP_
#define FLEXBUF_FLEXBUF_HPP_
#ifndef RFL_FLEXBUF_HPP_
#define RFL_FLEXBUF_HPP_
#include "flexbuf/Parser.hpp"
#include "flexbuf/Reader.hpp"