Skip to content

Instantly share code, notes, and snippets.

@jhurliman
Created October 18, 2024 22:39
Show Gist options
  • Save jhurliman/e5fb356b46e00bdaf522583f4bdc0e78 to your computer and use it in GitHub Desktop.
Save jhurliman/e5fb356b46e00bdaf522583f4bdc0e78 to your computer and use it in GitHub Desktop.
Wrap a std::vector<uint8_t> with a flatbuffers::Allocator
// Wraps an existing std::vector<uint8_t> as a flatbuffers::Allocator
class VectorAllocator : public flatbuffers::Allocator {
public:
explicit VectorAllocator(std::vector<uint8_t>& buffer)
: buffer_(buffer) {
buffer_.clear();
}
uint8_t* allocate(size_t size) override {
buffer_.resize(size);
return buffer_.data();
}
void deallocate(uint8_t* p, size_t size) override {
// No action needed; buffer is managed by std::vector
}
uint8_t* reallocate_downward(uint8_t* old_p, size_t old_size, size_t new_size, size_t in_use_back,
size_t in_use_front) override {
FLATBUFFERS_ASSERT(new_size > old_size); // vector_downward only grows
buffer_.resize(new_size);
memcpy(buffer_.data() + new_size - in_use_back, old_p + old_size - in_use_back, in_use_back);
memcpy(buffer_.data(), old_p, in_use_front);
return buffer_.data();
}
private:
std::vector<uint8_t>& buffer_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment