File: write.hpp

package info (click to toggle)
reflect-cpp 0.18.0%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 12,524 kB
  • sloc: cpp: 44,484; python: 131; makefile: 30; sh: 3
file content (66 lines) | stat: -rw-r--r-- 2,005 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#ifndef RFL_BSON_WRITE_HPP_
#define RFL_BSON_WRITE_HPP_

#include <bson/bson.h>

#include <ostream>
#include <sstream>
#include <string>
#include <utility>

#include "../Processors.hpp"
#include "../internal/ptr_cast.hpp"
#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... Ps>
std::pair<uint8_t*, size_t> to_buffer(const auto& _obj) noexcept {
  using T = std::remove_cvref_t<decltype(_obj)>;
  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);
  using ProcessorsType = Processors<Ps...>;
  static_assert(!ProcessorsType::no_field_names_,
                "The NoFieldNames processor is not supported for BSON, XML, "
                "TOML, or YAML.");
  Parser<T, ProcessorsType>::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... Ps>
std::vector<char> write(const auto& _obj) noexcept {
  auto [buf, len] = to_buffer<Ps...>(_obj);
  const auto result = std::vector<char>(internal::ptr_cast<char*>(buf),
                                        internal::ptr_cast<char*>(buf) + len);
  bson_free(buf);
  return result;
}

/// Writes a BSON into an ostream.
template <class... Ps>
std::ostream& write(const auto& _obj, std::ostream& _stream) noexcept {
  auto [buf, len] = to_buffer<Ps...>(_obj);
  _stream.write(internal::ptr_cast<const char*>(buf), len);
  bson_free(buf);
  return _stream;
}

}  // namespace bson
}  // namespace rfl

#endif