From 99acd0bcd78a923e7e51302188a125bdde287b7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20N=C3=BCtzi?= Date: Fri, 24 Aug 2018 19:57:57 +0200 Subject: [PATCH] DetachedBuffer cannot be rewrapped (#4885) * Simple ReleaseRaw implemented * [doc] * clear_buffer and clear_allocator introduced * auto * typos * rename because of -Werror=shadow --- include/flatbuffers/flatbuffers.h | 45 ++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h index 6453c3084..d0b96abc0 100644 --- a/include/flatbuffers/flatbuffers.h +++ b/include/flatbuffers/flatbuffers.h @@ -573,15 +573,12 @@ class vector_downward { scratch_(nullptr) {} ~vector_downward() { - if (buf_) Deallocate(allocator_, buf_, reserved_); - if (own_allocator_ && allocator_) { delete allocator_; } + clear_buffer(); + clear_allocator(); } void reset() { - if (buf_) { - Deallocate(allocator_, buf_, reserved_); - buf_ = nullptr; - } + clear_buffer(); clear(); } @@ -599,6 +596,29 @@ class vector_downward { scratch_ = buf_; } + void clear_allocator() { + if (own_allocator_ && allocator_) { delete allocator_; } + allocator_ = nullptr; + own_allocator_ = false; + } + + void clear_buffer() { + if (buf_) Deallocate(allocator_, buf_, reserved_); + buf_ = nullptr; + } + + // Relinquish the pointer to the caller. + uint8_t *release_raw(size_t &allocated_bytes, size_t &offset) { + auto *buf = buf_; + allocated_bytes = reserved_; + offset = static_cast(cur_ - buf_); + + buf_ = nullptr; + clear_allocator(); + clear(); + return buf; + } + // Relinquish the pointer to the caller. DetachedBuffer release() { DetachedBuffer fb(allocator_, own_allocator_, buf_, reserved_, cur_, @@ -827,6 +847,19 @@ class FlatBufferBuilder { return buf_.release(); } + /// @brief Get the released pointer to the serialized buffer. + /// @param The size of the memory block containing + /// the serialized `FlatBuffer`. + /// @param The offset from the released pointer where the finished + /// `FlatBuffer` starts. + /// @return A raw pointer to the start of the memory block containing + /// the serialized `FlatBuffer`. + /// @remark If the allocator is owned, it gets deleted during this call. + uint8_t *ReleaseRaw(size_t &size, size_t &offset) { + Finished(); + return buf_.release_raw(size, offset); + } + /// @brief get the minimum alignment this buffer needs to be accessed /// properly. This is only known once all elements have been written (after /// you call Finish()). You can use this information if you need to embed