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 (51 lines) | stat: -rw-r--r-- 1,340 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
#ifndef FLEXBUF_WRITE_HPP_
#define FLEXBUF_WRITE_HPP_

#include <flatbuffers/flexbuffers.h>

#include <cstddef>
#include <ostream>
#include <sstream>
#include <vector>

#include "../Processors.hpp"
#include "../Ref.hpp"
#include "../internal/ptr_cast.hpp"
#include "../parsing/Parent.hpp"
#include "Parser.hpp"

namespace rfl {
namespace flexbuf {

template <class... Ps>
std::vector<uint8_t> to_buffer(const auto& _obj) {
  using T = std::remove_cvref_t<decltype(_obj)>;
  using ParentType = parsing::Parent<Writer>;
  const auto fbb = Ref<flexbuffers::Builder>::make();
  auto w = Writer(fbb);
  Parser<T, Processors<Ps...>>::write(w, _obj, typename ParentType::Root{});
  fbb->Finish();
  return fbb->GetBuffer();
}

/// Writes an object to flexbuf.
template <class... Ps>
std::vector<char> write(const auto& _obj) {
  const auto buffer = to_buffer<Ps...>(_obj);
  const auto data = internal::ptr_cast<const char*>(buffer.data());
  return std::vector<char>(data, data + buffer.size());
}

/// Writes an object to an ostream.
template <class... Ps>
std::ostream& write(const auto& _obj, std::ostream& _stream) {
  const auto buffer = to_buffer<Ps...>(_obj);
  const auto data = internal::ptr_cast<const char*>(buffer.data());
  _stream.write(data, buffer.size());
  return _stream;
}

}  // namespace flexbuf
}  // namespace rfl

#endif