Merge "C#: Allow ByteBuffer to use faster unsafe mode" into ub-games-master
[platform/upstream/flatbuffers.git] / docs / source / Internals.md
1 # FlatBuffer Internals
2
3 This section is entirely optional for the use of FlatBuffers. In normal
4 usage, you should never need the information contained herein. If you're
5 interested however, it should give you more of an appreciation of why
6 FlatBuffers is both efficient and convenient.
7
8 ### Format components
9
10 A FlatBuffer is a binary file and in-memory format consisting mostly of
11 scalars of various sizes, all aligned to their own size. Each scalar is
12 also always represented in little-endian format, as this corresponds to
13 all commonly used CPUs today. FlatBuffers will also work on big-endian
14 machines, but will be slightly slower because of additional
15 byte-swap intrinsics.
16
17 On purpose, the format leaves a lot of details about where exactly
18 things live in memory undefined, e.g. fields in a table can have any
19 order, and objects to some extend can be stored in many orders. This is
20 because the format doesn't need this information to be efficient, and it
21 leaves room for optimization and extension (for example, fields can be
22 packed in a way that is most compact). Instead, the format is defined in
23 terms of offsets and adjacency only. This may mean two different
24 implementations may produce different binaries given the same input
25 values, and this is perfectly valid.
26
27 ### Format identification
28
29 The format also doesn't contain information for format identification
30 and versioning, which is also by design. FlatBuffers is a statically typed
31 system, meaning the user of a buffer needs to know what kind of buffer
32 it is. FlatBuffers can of course be wrapped inside other containers
33 where needed, or you can use its union feature to dynamically identify
34 multiple possible sub-objects stored. Additionally, it can be used
35 together with the schema parser if full reflective capabilities are
36 desired.
37
38 Versioning is something that is intrinsically part of the format (the
39 optionality / extensibility of fields), so the format itself does not
40 need a version number (it's a meta-format, in a sense). We're hoping
41 that this format can accommodate all data needed. If format breaking
42 changes are ever necessary, it would become a new kind of format rather
43 than just a variation.
44
45 ### Offsets
46
47 The most important and generic offset type (see `flatbuffers.h`) is
48 `uoffset_t`, which is currently always a `uint32_t`, and is used to
49 refer to all tables/unions/strings/vectors (these are never stored
50 in-line). 32bit is
51 intentional, since we want to keep the format binary compatible between
52 32 and 64bit systems, and a 64bit offset would bloat the size for almost
53 all uses. A version of this format with 64bit (or 16bit) offsets is easy to set
54 when needed. Unsigned means they can only point in one direction, which
55 typically is forward (towards a higher memory location). Any backwards
56 offsets will be explicitly marked as such.
57
58 The format starts with an `uoffset_t` to the root object in the buffer.
59
60 We have two kinds of objects, structs and tables.
61
62 ### Structs
63
64 These are the simplest, and as mentioned, intended for simple data that
65 benefits from being extra efficient and doesn't need versioning /
66 extensibility. They are always stored inline in their parent (a struct,
67 table, or vector) for maximum compactness. Structs define a consistent
68 memory layout where all components are aligned to their size, and
69 structs aligned to their largest scalar member. This is done independent
70 of the alignment rules of the underlying compiler to guarantee a cross
71 platform compatible layout. This layout is then enforced in the generated
72 code.
73
74 ### Tables
75
76 These start with an `soffset_t` to a vtable. This is a signed version of
77 `uoffset_t`, since vtables may be stored anywhere relative to the object.
78 This offset is substracted (not added) from the object start to arrive at
79 the vtable start. This offset is followed by all the
80 fields as aligned scalars (or offsets). Unlike structs, not all fields
81 need to be present. There is no set order and layout.
82
83 To be able to access fields regardless of these uncertainties, we go
84 through a vtable of offsets. Vtables are shared between any objects that
85 happen to have the same vtable values.
86
87 The elements of a vtable are all of type `voffset_t`, which is
88 a `uint16_t`. The first element is the size of the vtable in bytes,
89 including the size element. The second one is the size of the object, in bytes
90 (including the vtable offset). This size could be used for streaming, to know
91 how many bytes to read to be able to access all fields of the object.
92 The remaining elements are the N offsets, where N is the amount of fields
93 declared in the schema when the code that constructed this buffer was
94 compiled (thus, the size of the table is N + 2).
95
96 All accessor functions in the generated code for tables contain the
97 offset into this table as a constant. This offset is checked against the
98 first field (the number of elements), to protect against newer code
99 reading older data. If this offset is out of range, or the vtable entry
100 is 0, that means the field is not present in this object, and the
101 default value is return. Otherwise, the entry is used as offset to the
102 field to be read.
103
104 ### Strings and Vectors
105
106 Strings are simply a vector of bytes, and are always
107 null-terminated. Vectors are stored as contiguous aligned scalar
108 elements prefixed by a 32bit element count (not including any
109 null termination).
110
111 ### Construction
112
113 The current implementation constructs these buffers backwards (starting
114 at the highest memory address of the buffer), since
115 that significantly reduces the amount of bookkeeping and simplifies the
116 construction API.
117
118 ### Code example
119
120 Here's an example of the code that gets generated for the `samples/monster.fbs`.
121 What follows is the entire file, broken up by comments:
122
123     // automatically generated, do not modify
124
125     #include "flatbuffers/flatbuffers.h"
126
127     namespace MyGame {
128     namespace Sample {
129
130 Nested namespace support.
131
132     enum {
133       Color_Red = 0,
134       Color_Green = 1,
135       Color_Blue = 2,
136     };
137
138     inline const char **EnumNamesColor() {
139       static const char *names[] = { "Red", "Green", "Blue", nullptr };
140       return names;
141     }
142
143     inline const char *EnumNameColor(int e) { return EnumNamesColor()[e]; }
144
145 Enums and convenient reverse lookup.
146
147     enum {
148       Any_NONE = 0,
149       Any_Monster = 1,
150     };
151
152     inline const char **EnumNamesAny() {
153       static const char *names[] = { "NONE", "Monster", nullptr };
154       return names;
155     }
156
157     inline const char *EnumNameAny(int e) { return EnumNamesAny()[e]; }
158
159 Unions share a lot with enums.
160
161     struct Vec3;
162     struct Monster;
163
164 Predeclare all data types since circular references between types are allowed
165 (circular references between object are not, though).
166
167     MANUALLY_ALIGNED_STRUCT(4) Vec3 {
168      private:
169       float x_;
170       float y_;
171       float z_;
172
173      public:
174       Vec3(float x, float y, float z)
175         : x_(flatbuffers::EndianScalar(x)), y_(flatbuffers::EndianScalar(y)), z_(flatbuffers::EndianScalar(z)) {}
176
177       float x() const { return flatbuffers::EndianScalar(x_); }
178       float y() const { return flatbuffers::EndianScalar(y_); }
179       float z() const { return flatbuffers::EndianScalar(z_); }
180     };
181     STRUCT_END(Vec3, 12);
182
183 These ugly macros do a couple of things: they turn off any padding the compiler
184 might normally do, since we add padding manually (though none in this example),
185 and they enforce alignment chosen by FlatBuffers. This ensures the layout of
186 this struct will look the same regardless of compiler and platform. Note that
187 the fields are private: this is because these store little endian scalars
188 regardless of platform (since this is part of the serialized data).
189 `EndianScalar` then converts back and forth, which is a no-op on all current
190 mobile and desktop platforms, and a single machine instruction on the few
191 remaining big endian platforms.
192
193     struct Monster : private flatbuffers::Table {
194       const Vec3 *pos() const { return GetStruct<const Vec3 *>(4); }
195       int16_t mana() const { return GetField<int16_t>(6, 150); }
196       int16_t hp() const { return GetField<int16_t>(8, 100); }
197       const flatbuffers::String *name() const { return GetPointer<const flatbuffers::String *>(10); }
198       const flatbuffers::Vector<uint8_t> *inventory() const { return GetPointer<const flatbuffers::Vector<uint8_t> *>(14); }
199       int8_t color() const { return GetField<int8_t>(16, 2); }
200     };
201
202 Tables are a bit more complicated. A table accessor struct is used to point at
203 the serialized data for a table, which always starts with an offset to its
204 vtable. It derives from `Table`, which contains the `GetField` helper functions.
205 GetField takes a vtable offset, and a default value. It will look in the vtable
206 at that offset. If the offset is out of bounds (data from an older version) or
207 the vtable entry is 0, the field is not present and the default is returned.
208 Otherwise, it uses the entry as an offset into the table to locate the field.
209
210     struct MonsterBuilder {
211       flatbuffers::FlatBufferBuilder &fbb_;
212       flatbuffers::uoffset_t start_;
213       void add_pos(const Vec3 *pos) { fbb_.AddStruct(4, pos); }
214       void add_mana(int16_t mana) { fbb_.AddElement<int16_t>(6, mana, 150); }
215       void add_hp(int16_t hp) { fbb_.AddElement<int16_t>(8, hp, 100); }
216       void add_name(flatbuffers::Offset<flatbuffers::String> name) { fbb_.AddOffset(10, name); }
217       void add_inventory(flatbuffers::Offset<flatbuffers::Vector<uint8_t>> inventory) { fbb_.AddOffset(14, inventory); }
218       void add_color(int8_t color) { fbb_.AddElement<int8_t>(16, color, 2); }
219       MonsterBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); }
220       flatbuffers::Offset<Monster> Finish() { return flatbuffers::Offset<Monster>(fbb_.EndTable(start_, 7)); }
221     };
222
223 `MonsterBuilder` is the base helper struct to construct a table using a
224 `FlatBufferBuilder`. You can add the fields in any order, and the `Finish`
225 call will ensure the correct vtable gets generated.
226
227     inline flatbuffers::Offset<Monster> CreateMonster(flatbuffers::FlatBufferBuilder &_fbb, const Vec3 *pos, int16_t mana, int16_t hp, flatbuffers::Offset<flatbuffers::String> name, flatbuffers::Offset<flatbuffers::Vector<uint8_t>> inventory, int8_t color) {
228       MonsterBuilder builder_(_fbb);
229       builder_.add_inventory(inventory);
230       builder_.add_name(name);
231       builder_.add_pos(pos);
232       builder_.add_hp(hp);
233       builder_.add_mana(mana);
234       builder_.add_color(color);
235       return builder_.Finish();
236     }
237
238 `CreateMonster` is a convenience function that calls all functions in
239 `MonsterBuilder` above for you. Note that if you pass values which are
240 defaults as arguments, it will not actually construct that field, so
241 you can probably use this function instead of the builder class in
242 almost all cases.
243
244     inline const Monster *GetMonster(const void *buf) { return flatbuffers::GetRoot<Monster>(buf); }
245
246 This function is only generated for the root table type, to be able to
247 start traversing a FlatBuffer from a raw buffer pointer.
248
249     }; // namespace MyGame
250     }; // namespace Sample
251
252