blob: 6f6fc11fcf0932e1c19ab5cacb4d4c8851cdba9b [file] [log] [blame]
Austin Schuhe93d8642019-10-13 15:27:07 -07001#ifndef AOS_FLATBUFFERS_H_
2#define AOS_FLATBUFFERS_H_
3
4#include "flatbuffers/flatbuffers.h"
5
6namespace aos {
7
8// TODO(austin): FlatbufferBase ? We can associate the type table with it, and
9// make it generic.
10
11// This object associates the message type with the memory storing the
12// flatbuffer. This only stores root tables.
13//
14// From a usage point of view, pointers to the data are very different than
15// pointers to the tables.
16template <typename T>
17class Flatbuffer {
18 public:
19 // Builds a Flatbuffer by taking ownership of the buffer.
20 Flatbuffer(flatbuffers::DetachedBuffer &&buffer)
21 : buffer_(::std::move(buffer)) {}
22
23 // Builds a flatbuffer by taking ownership of the buffer from the other
24 // flatbuffer.
25 Flatbuffer(Flatbuffer &&fb) : buffer_(::std::move(fb.buffer_)) {}
26 Flatbuffer &operator=(Flatbuffer &&fb) {
27 ::std::swap(buffer_, fb.buffer_);
28 return *this;
29 }
30
31 // Constructs an empty flatbuffer of type T.
32 static Flatbuffer<T> Empty() {
33 flatbuffers::FlatBufferBuilder fbb;
34 fbb.ForceDefaults(1);
35 const auto end = fbb.EndTable(fbb.StartTable());
36 fbb.Finish(flatbuffers::Offset<flatbuffers::Table>(end));
37 return Flatbuffer<T>(fbb.Release());
38 }
39
40 // Returns the MiniReflectTypeTable for T.
41 static const flatbuffers::TypeTable *MiniReflectTypeTable() {
42 return T::MiniReflectTypeTable();
43 }
44
45 // Returns a message from the buffer.
46 const T &message() const { return *flatbuffers::GetRoot<T>(buffer_.data()); }
47 // Returns a mutable message. It can be mutated via the flatbuffer rules.
48 T *mutable_message() {
49 return flatbuffers::GetMutableRoot<T>(buffer_.data());
50 }
51
52 // Returns references to the buffer, and the data.
53 const flatbuffers::DetachedBuffer &buffer() const { return buffer_; }
54 const uint8_t *data() const { return buffer_.data(); }
55
56 private:
57 flatbuffers::DetachedBuffer buffer_;
58};
59
60// TODO(austin): Need a fixed buffer version of Flatbuffer.
61// TODO(austin): Need a way to get our hands on the max size. Can start with
62// "large" for now.
63
64} // namespace aos
65
66#endif // AOS_FLATBUFFERS_H_