James Kuszmaul | f5eb468 | 2023-09-22 17:16:59 -0700 | [diff] [blame] | 1 | #ifndef AOS_FLATBUFFERS_BASE_H_ |
| 2 | #define AOS_FLATBUFFERS_BASE_H_ |
| 3 | #include <iomanip> |
| 4 | #include <memory> |
| 5 | #include <optional> |
| 6 | #include <span> |
| 7 | |
| 8 | #include "flatbuffers/base.h" |
| 9 | #include "glog/logging.h" |
| 10 | namespace aos::fbs { |
| 11 | using ::flatbuffers::soffset_t; |
| 12 | using ::flatbuffers::uoffset_t; |
| 13 | using ::flatbuffers::voffset_t; |
| 14 | |
| 15 | // Returns the smallest multiple of alignment that is greater than or equal to |
| 16 | // size. |
| 17 | constexpr size_t PaddedSize(size_t size, size_t alignment) { |
| 18 | // We can be clever with bitwise operations by assuming that aligment is a |
| 19 | // power of two. Or we can just be clearer about what we mean and eat a few |
| 20 | // integer divides. |
| 21 | return (((size - 1) / alignment) + 1) * alignment; |
| 22 | } |
| 23 | |
| 24 | // Used as a parameter to methods where we are messing with memory and may or |
| 25 | // may not want to clear it to zeroes. |
| 26 | enum class SetZero { kYes, kNo }; |
| 27 | |
| 28 | class Allocator; |
| 29 | |
| 30 | // Parent type of any object that may need to dynamically change size at |
| 31 | // runtime. Used by the static table and vector types to request additional |
| 32 | // blocks of memory when needed. |
| 33 | // |
| 34 | // The way that this works is that every ResizeableObject has some number of |
| 35 | // children that are themselves ResizeableObject's and whose memory is entirely |
| 36 | // contained within their parent's memory. A ResizeableObject without a parent |
| 37 | // instead has an Allocator that it can use to allocate additional blocks |
| 38 | // of memory. Whenever a child needs to grow in size, it will make a call to |
| 39 | // InsertBytes() on its parent, which will percolate up until InsertBytes() gets |
| 40 | // called on the root allocator. If the insert succeeds, then every single child |
| 41 | // through the entire tree will get notified (this is because the allocator may |
| 42 | // have shifted the entire memory buffer, so any pointers may need to be |
| 43 | // updated). Child types will provide implementations of the GetObjects() method |
| 44 | // to both allow tree traversal as well as to allow the various internal offsets |
| 45 | // to be updated appropriately. |
| 46 | class ResizeableObject { |
| 47 | public: |
| 48 | // Returns the underlying memory buffer into which the flatbuffer will be |
| 49 | // serialized. |
| 50 | std::span<uint8_t> buffer() { return buffer_; } |
| 51 | std::span<const uint8_t> buffer() const { return buffer_; } |
| 52 | |
| 53 | // Updates the underlying memory buffer to new_buffer, with an indication of |
| 54 | // where bytes were inserted/removed from the buffer. It is assumed that |
| 55 | // new_buffer already has the state of the serialized flatbuffer |
| 56 | // copied into it. |
| 57 | // * When bytes have been inserted, modification_point will point to the first |
| 58 | // of the inserted bytes in new_buffer and bytes_inserted will be the number |
| 59 | // of new bytes. |
| 60 | // * Buffer shrinkage is not currently supported. |
| 61 | // * When bytes_inserted is zero, modification_point is ignored. |
| 62 | void UpdateBuffer(std::span<uint8_t> new_buffer, void *modification_point, |
| 63 | ssize_t bytes_inserted); |
| 64 | |
| 65 | protected: |
| 66 | // Data associated with a sub-object of this object. |
| 67 | struct SubObject { |
| 68 | // A direct pointer to the inline entry in the flatbuffer table data. The |
| 69 | // pointer must be valid, but the entry itself may be zero if the object is |
| 70 | // not actually populated. |
| 71 | // If *inline_entry is non-zero, this will get updated if any new memory got |
| 72 | // added/removed in-between inline_entry and the actual data pointed to be |
| 73 | // inline_entry. |
| 74 | uoffset_t *inline_entry; |
| 75 | // The actual child object. Should be nullptr if *inline_entry is zero; must |
| 76 | // be valid if *inline_entry is non-zero. |
| 77 | ResizeableObject *object; |
| 78 | // The nominal offset from buffer_.data() to object->buffer_.data(). |
| 79 | // Must be provided, and must always be valid, even if *inline_entry is |
| 80 | // zero. |
| 81 | // I.e., the following holds when object is not nullptr: |
| 82 | // SubObject object = parent.GetSubObject(index); |
| 83 | // CHECK_EQ(parent.buffer()->data() + *object.absolute_offset, |
| 84 | // object.object->buffer().data()); |
| 85 | size_t *absolute_offset; |
| 86 | }; |
| 87 | |
| 88 | ResizeableObject(std::span<uint8_t> buffer, ResizeableObject *parent) |
| 89 | : buffer_(buffer), parent_(parent) {} |
| 90 | ResizeableObject(std::span<uint8_t> buffer, Allocator *allocator) |
| 91 | : buffer_(buffer), allocator_(allocator) {} |
| 92 | ResizeableObject(std::span<uint8_t> buffer, |
| 93 | std::unique_ptr<Allocator> allocator) |
| 94 | : buffer_(buffer), |
| 95 | owned_allocator_(std::move(allocator)), |
| 96 | allocator_(owned_allocator_.get()) {} |
| 97 | ResizeableObject(const ResizeableObject &) = delete; |
| 98 | ResizeableObject &operator=(const ResizeableObject &) = delete; |
| 99 | // Users do not end up using the move constructor; however, it is needed to |
| 100 | // handle the fact that a ResizeableObject may be a member of an std::vector |
| 101 | // in the various generated types. |
James Kuszmaul | d4b4f1d | 2024-03-13 15:57:35 -0700 | [diff] [blame^] | 102 | ResizeableObject(ResizeableObject &&other); |
James Kuszmaul | f5eb468 | 2023-09-22 17:16:59 -0700 | [diff] [blame] | 103 | // Required alignment of this object. |
| 104 | virtual size_t Alignment() const = 0; |
| 105 | // Offset from the start of buffer() to the actual start of the object in |
| 106 | // question (this is important for vectors, where the vector itself cannot |
| 107 | // have internal padding, and so the start of the vector may be offset from |
| 108 | // the start of the buffer to handle alignment). |
| 109 | virtual size_t AbsoluteOffsetOffset() const = 0; |
| 110 | // Causes bytes bytes to be inserted between insertion_point - 1 and |
| 111 | // insertion_point. |
| 112 | // If requested, the new bytes will be cleared to zero; otherwise they will be |
| 113 | // left uninitialized. |
| 114 | // The insertion_point may not be equal to this->buffer_.data(); it may be a |
| 115 | // pointer just past the end of the buffer. This is to ease the |
| 116 | // implementation, and is merely a requirement that any buffer growth occur |
| 117 | // only on the inside or past the end of the vector, and not prior to the |
| 118 | // start of the vector. |
| 119 | // Returns true on success, false on failure (e.g., if the allocator has no |
| 120 | // memory available). |
| 121 | bool InsertBytes(void *insertion_point, size_t bytes, SetZero set_zero); |
| 122 | // Called *after* the internal buffer_ has been swapped out and *after* the |
| 123 | // object tree has been traversed and fixed. |
| 124 | virtual void ObserveBufferModification() {} |
| 125 | |
| 126 | // Returns the index'th sub object of this object. |
| 127 | // index must be less than NumberOfSubObjects(). |
| 128 | // This will include objects which are not currently populated but which may |
| 129 | // be populated in the future (so that we can track what the necessary offsets |
| 130 | // are when we do populate it). |
| 131 | virtual SubObject GetSubObject(size_t index) = 0; |
| 132 | // Number of sub-objects of this object. May be zero. |
| 133 | virtual size_t NumberOfSubObjects() const = 0; |
| 134 | |
| 135 | // Treating the supplied absolute_offset as an offset into the internal memory |
| 136 | // buffer, return the pointer to the underlying memory. |
| 137 | const void *PointerForAbsoluteOffset(const size_t absolute_offset) { |
| 138 | return buffer_.data() + absolute_offset; |
| 139 | } |
| 140 | // Returns a span at the requested offset into the buffer. terminal_alignment |
| 141 | // does not align the start of the buffer; instead, it ensures that the memory |
| 142 | // from absolute_offset + size until the next multiple of terminal_alignment |
| 143 | // is set to all zeroes. |
| 144 | std::span<uint8_t> BufferForObject(size_t absolute_offset, size_t size, |
| 145 | size_t terminal_alignment); |
| 146 | // When memory has been inserted/removed, this iterates over the sub-objects |
| 147 | // and notifies/adjusts them appropriately. |
| 148 | // This will be called after buffer_ has been updated, and: |
| 149 | // * For insertion, modification_point will point into the new buffer_ to the |
| 150 | // first of the newly inserted bytes. |
| 151 | // * Removal is not entirely implemented yet, but for removal, |
| 152 | // modification_point should point to the first byte after the removed |
| 153 | // chunk. |
| 154 | void FixObjects(void *modification_point, ssize_t bytes_inserted); |
| 155 | |
| 156 | Allocator *allocator() { return allocator_; } |
| 157 | |
| 158 | std::span<uint8_t> buffer_; |
| 159 | |
| 160 | private: |
| 161 | ResizeableObject *parent_ = nullptr; |
| 162 | std::unique_ptr<Allocator> owned_allocator_; |
| 163 | Allocator *allocator_ = nullptr; |
| 164 | }; |
| 165 | |
| 166 | // Interface to represent a memory allocator for use with ResizeableObject. |
| 167 | class Allocator { |
| 168 | public: |
| 169 | virtual ~Allocator() {} |
| 170 | // Allocates memory of the requested size and alignment. alignment is not |
| 171 | // guaranteed. |
| 172 | // On failure to allocate the requested size, returns nullopt; |
| 173 | // Never returns a partial span. |
| 174 | // The span will be initialized to zero upon request. |
| 175 | // Once Allocate() has been called once, it may not be called again until |
| 176 | // Deallocate() has been called. In order to adjust the size of the buffer, |
| 177 | // call InsertBytes() and RemoveBytes(). |
| 178 | [[nodiscard]] virtual std::optional<std::span<uint8_t>> Allocate( |
| 179 | size_t size, size_t alignment_hint, SetZero set_zero) = 0; |
| 180 | // Identical to Allocate(), but dies on failure. |
| 181 | [[nodiscard]] std::span<uint8_t> AllocateOrDie(size_t size, |
| 182 | size_t alignment_hint, |
| 183 | SetZero set_zero) { |
| 184 | std::optional<std::span<uint8_t>> span = |
| 185 | Allocate(size, alignment_hint, set_zero); |
| 186 | CHECK(span.has_value()) << ": Failed to allocate " << size << " bytes."; |
| 187 | CHECK_EQ(size, span.value().size()) |
| 188 | << ": Failed to allocate " << size << " bytes."; |
| 189 | return span.value(); |
| 190 | } |
| 191 | // Increases the size of the buffer by inserting bytes bytes immediately |
| 192 | // before insertion_point. |
| 193 | // alignment_hint specifies the alignment of the entire buffer, not of the |
| 194 | // inserted bytes. |
| 195 | // The returned span may or may not overlap with the original buffer in |
| 196 | // memory. |
| 197 | // The inserted bytes will be set to zero or uninitialized depending on the |
| 198 | // value of SetZero. |
| 199 | // insertion_point must be in (or 1 past the end of) the buffer. |
| 200 | // Returns nullopt on a failure to allocate the requested bytes. |
| 201 | [[nodiscard]] virtual std::optional<std::span<uint8_t>> InsertBytes( |
| 202 | void *insertion_point, size_t bytes, size_t alignment_hint, |
| 203 | SetZero set_zero) = 0; |
| 204 | // Removes the requested span of bytes from the buffer, returning the new |
| 205 | // buffer. |
| 206 | [[nodiscard]] virtual std::span<uint8_t> RemoveBytes( |
| 207 | std::span<uint8_t> remove_bytes) = 0; |
| 208 | // Deallocates the currently allocated buffer. The provided buffer must match |
| 209 | // the latest version of the buffer. |
| 210 | // If Allocate() has been called, Deallocate() must be called prior to |
| 211 | // destroying the Allocator. |
| 212 | virtual void Deallocate(std::span<uint8_t> buffer) = 0; |
| 213 | }; |
| 214 | |
| 215 | // Allocator that uses an std::vector to allow arbitrary-sized allocations. |
| 216 | // Does not provide any alignment guarantees. |
| 217 | class VectorAllocator : public Allocator { |
| 218 | public: |
| 219 | VectorAllocator() {} |
| 220 | ~VectorAllocator() { |
| 221 | CHECK(buffer_.empty()) |
| 222 | << ": Must deallocate before destroying the VectorAllocator."; |
| 223 | } |
| 224 | std::optional<std::span<uint8_t>> Allocate(size_t size, size_t /*alignment*/, |
| 225 | SetZero set_zero) override; |
| 226 | std::optional<std::span<uint8_t>> InsertBytes(void *insertion_point, |
| 227 | size_t bytes, |
| 228 | size_t /*alignment*/, |
| 229 | SetZero /*set_zero*/) override; |
| 230 | std::span<uint8_t> RemoveBytes(std::span<uint8_t> remove_bytes) override; |
| 231 | |
| 232 | void Deallocate(std::span<uint8_t>) override { |
| 233 | CHECK(!buffer_.empty()) |
| 234 | << ": Called Deallocate() without a prior allocation."; |
| 235 | buffer_.resize(0); |
| 236 | } |
| 237 | |
| 238 | private: |
| 239 | std::vector<uint8_t> buffer_; |
| 240 | }; |
| 241 | |
| 242 | // Allocator that allocates all of its memory within a provided span. To match |
| 243 | // the behavior of the FlatBufferBuilder, it will start its allocations at the |
| 244 | // end of the provided span. |
| 245 | // |
| 246 | // Attempts to allocate more memory than is present in the provided buffer will |
| 247 | // fail. |
| 248 | class SpanAllocator : public Allocator { |
| 249 | public: |
| 250 | SpanAllocator(std::span<uint8_t> buffer) : buffer_(buffer) {} |
| 251 | ~SpanAllocator() { |
| 252 | CHECK(!allocated_) |
| 253 | << ": Must deallocate before destroying the SpanAllocator."; |
| 254 | } |
| 255 | |
| 256 | std::optional<std::span<uint8_t>> Allocate(size_t size, size_t /*alignment*/, |
| 257 | SetZero set_zero) override; |
| 258 | |
| 259 | std::optional<std::span<uint8_t>> InsertBytes(void *insertion_point, |
| 260 | size_t bytes, |
| 261 | size_t /*alignment*/, |
| 262 | SetZero set_zero) override; |
| 263 | |
| 264 | std::span<uint8_t> RemoveBytes(std::span<uint8_t> remove_bytes) override; |
| 265 | |
| 266 | void Deallocate(std::span<uint8_t>) override; |
| 267 | |
| 268 | private: |
| 269 | std::span<uint8_t> buffer_; |
| 270 | bool allocated_ = false; |
| 271 | size_t allocated_size_ = 0; |
| 272 | }; |
| 273 | |
Maxwell Henderson | fb1e3bc | 2024-02-04 13:55:22 -0800 | [diff] [blame] | 274 | // Allocates and owns a fixed-size memory buffer on the stack. |
| 275 | // |
| 276 | // This provides a convenient Allocator for use with the aos::fbs::Builder |
| 277 | // in realtime code instead of trying to use the VectorAllocator. |
| 278 | template <std::size_t N> |
| 279 | class FixedStackAllocator : public SpanAllocator { |
| 280 | public: |
| 281 | FixedStackAllocator() : SpanAllocator({buffer_, sizeof(buffer_)}) {} |
| 282 | |
| 283 | private: |
| 284 | uint8_t buffer_[N]; |
| 285 | }; |
| 286 | |
James Kuszmaul | f5eb468 | 2023-09-22 17:16:59 -0700 | [diff] [blame] | 287 | namespace internal { |
| 288 | std::ostream &DebugBytes(std::span<const uint8_t> span, std::ostream &os); |
| 289 | inline void ClearSpan(std::span<uint8_t> span) { |
| 290 | memset(span.data(), 0, span.size()); |
| 291 | } |
| 292 | // std::span::subspan does not do bounds checking. |
| 293 | template <typename T> |
| 294 | inline std::span<T> GetSubSpan(std::span<T> span, size_t offset, |
| 295 | size_t count = std::dynamic_extent) { |
| 296 | if (count != std::dynamic_extent) { |
| 297 | CHECK_LE(offset + count, span.size()); |
| 298 | } |
| 299 | return span.subspan(offset, count); |
| 300 | } |
| 301 | // Normal users should never move any of the special flatbuffer types that we |
| 302 | // provide. However, they do need to be moveable in order to support the use of |
| 303 | // resizeable vectors. As such, we make all the move constructors private and |
| 304 | // friend the TableMover struct. The TableMover struct is then used in places |
| 305 | // that need to have moveable objects. It should never be used by a user. |
| 306 | template <typename T> |
| 307 | struct TableMover { |
| 308 | TableMover(std::span<uint8_t> buffer, ResizeableObject *parent) |
| 309 | : t(buffer, parent) {} |
| 310 | TableMover(std::span<uint8_t> buffer, Allocator *allocator) |
| 311 | : t(buffer, allocator) {} |
| 312 | TableMover(std::span<uint8_t> buffer, ::std::unique_ptr<Allocator> allocator) |
| 313 | : t(buffer, ::std::move(allocator)) {} |
| 314 | TableMover(TableMover &&) = default; |
| 315 | T t; |
| 316 | }; |
| 317 | } // namespace internal |
| 318 | } // namespace aos::fbs |
| 319 | #endif // AOS_FLATBUFFERS_BASE_H_ |