Add a builder option to enable/disable vtables deduplication. (#4132)

* Add a builder option to enable/disable vtables deduplication.

* address code review comments
This commit is contained in:
gbeili 2017-01-11 10:36:18 -08:00 committed by Wouter van Oortmerssen
parent b55f18649a
commit 1a21b54560
1 changed files with 16 additions and 8 deletions

View File

@ -647,7 +647,7 @@ FLATBUFFERS_FINAL_CLASS
const simple_allocator *allocator = nullptr)
: buf_(initial_size, allocator ? *allocator : default_allocator),
nested(false), finished(false), minalign_(1), force_defaults_(false),
string_pool(nullptr) {
dedup_vtables_(true), string_pool(nullptr) {
offsetbuf_.reserve(16); // Avoid first few reallocs.
vtables_.reserve(16);
EndianCheck();
@ -724,6 +724,10 @@ FLATBUFFERS_FINAL_CLASS
/// @param[in] bool fd When set to `true`, always serializes default values.
void ForceDefaults(bool fd) { force_defaults_ = fd; }
/// @brief By default vtables are deduped in order to save space.
/// @param[in] bool dedup When set to `true`, dedup vtables.
void DedupVtables(bool dedup) { dedup_vtables_ = dedup; }
/// @cond FLATBUFFERS_INTERNAL
void Pad(size_t num_bytes) { buf_.fill(num_bytes); }
@ -861,13 +865,15 @@ FLATBUFFERS_FINAL_CLASS
auto vt_use = GetSize();
// See if we already have generated a vtable with this exact same
// layout before. If so, make it point to the old one, remove this one.
for (auto it = vtables_.begin(); it != vtables_.end(); ++it) {
auto vt2 = reinterpret_cast<voffset_t *>(buf_.data_at(*it));
auto vt2_size = *vt2;
if (vt1_size != vt2_size || memcmp(vt2, vt1, vt1_size)) continue;
vt_use = *it;
buf_.pop(GetSize() - vtableoffsetloc);
break;
if (dedup_vtables_) {
for (auto it = vtables_.begin(); it != vtables_.end(); ++it) {
auto vt2 = reinterpret_cast<voffset_t *>(buf_.data_at(*it));
auto vt2_size = *vt2;
if (vt1_size != vt2_size || memcmp(vt2, vt1, vt1_size)) continue;
vt_use = *it;
buf_.pop(GetSize() - vtableoffsetloc);
break;
}
}
// If this is a new vtable, remember it.
if (vt_use == GetSize()) {
@ -1267,6 +1273,8 @@ FLATBUFFERS_FINAL_CLASS
bool force_defaults_; // Serialize values equal to their defaults anyway.
bool dedup_vtables_;
struct StringOffsetCompare {
StringOffsetCompare(const vector_downward &buf) : buf_(&buf) {}
bool operator() (const Offset<String> &a, const Offset<String> &b) const {