Austin Schuh | 3c9f92c | 2024-04-30 17:56:42 -0700 | [diff] [blame] | 1 | #ifndef AOS_FLATBUFFERS_ALIGNED_ALLOCATOR_H_ |
| 2 | #define AOS_FLATBUFFERS_ALIGNED_ALLOCATOR_H_ |
| 3 | |
| 4 | #include <memory> |
| 5 | #include <optional> |
| 6 | #include <span> |
| 7 | |
| 8 | #include "glog/logging.h" |
| 9 | |
| 10 | #include "aos/containers/resizeable_buffer.h" |
| 11 | #include "aos/events/event_loop.h" |
| 12 | #include "aos/flatbuffers/base.h" |
| 13 | #include "aos/ipc_lib/data_alignment.h" |
| 14 | |
| 15 | namespace aos::fbs { |
| 16 | |
| 17 | // Allocator that uses an AllocatorResizeableBuffer to allow arbitrary-sized |
| 18 | // allocations. Aligns the end of the buffer to an alignment of |
| 19 | // kChannelDataAlignment. |
| 20 | class AlignedVectorAllocator : public fbs::Allocator { |
| 21 | public: |
| 22 | static constexpr size_t kAlignment = aos::kChannelDataAlignment; |
| 23 | AlignedVectorAllocator() {} |
| 24 | ~AlignedVectorAllocator(); |
| 25 | |
| 26 | std::optional<std::span<uint8_t>> Allocate(size_t size, size_t alignment, |
| 27 | fbs::SetZero set_zero) override; |
| 28 | |
| 29 | std::optional<std::span<uint8_t>> InsertBytes(void *insertion_point, |
| 30 | size_t bytes, size_t alignment, |
| 31 | fbs::SetZero set_zero) override; |
| 32 | |
| 33 | std::span<uint8_t> RemoveBytes(std::span<uint8_t> remove_bytes) override; |
| 34 | |
| 35 | void Deallocate(std::span<uint8_t>) override; |
| 36 | |
| 37 | aos::SharedSpan Release(); |
| 38 | |
| 39 | private: |
| 40 | struct SharedSpanHolder { |
| 41 | aos::AllocatorResizeableBuffer< |
| 42 | aos::AlignedReallocator<kChannelDataAlignment>> |
| 43 | buffer; |
| 44 | absl::Span<const uint8_t> span; |
| 45 | }; |
| 46 | uint8_t *data() { return buffer_.data() + buffer_.size() - allocated_size_; } |
| 47 | |
| 48 | aos::AllocatorResizeableBuffer<aos::AlignedReallocator<kChannelDataAlignment>> |
| 49 | buffer_; |
| 50 | |
| 51 | size_t allocated_size_ = 0u; |
| 52 | bool released_ = false; |
| 53 | }; |
| 54 | |
| 55 | } // namespace aos::fbs |
| 56 | |
| 57 | #endif // AOS_FLATBUFFERS_ALIGNED_ALLOCATOR_H_ |