1 // Protocol Buffers - Google's data interchange format 2 // Copyright 2023 Google LLC. All rights reserved. 3 // 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file or at 6 // https://developers.google.com/open-source/licenses/bsd 7 8 #ifndef UPB_MEM_ARENA_HPP_ 9 #define UPB_MEM_ARENA_HPP_ 10 11 #ifdef __cplusplus 12 13 #include <memory> 14 15 #include "upb/mem/arena.h" 16 17 namespace upb { 18 19 class Arena { 20 public: 21 // A simple arena with no initial memory block and the default allocator. Arena()22 Arena() : ptr_(upb_Arena_New(), upb_Arena_Free) {} Arena(char * initial_block,size_t size)23 Arena(char* initial_block, size_t size) 24 : ptr_(upb_Arena_Init(initial_block, size, &upb_alloc_global), 25 upb_Arena_Free) {} 26 ptr() const27 upb_Arena* ptr() const { return ptr_.get(); } 28 29 // Fuses the arenas together. 30 // This operation can only be performed on arenas with no initial blocks. Will 31 // return false if the fuse failed due to either arena having an initial 32 // block. Fuse(Arena & other)33 bool Fuse(Arena& other) { return upb_Arena_Fuse(ptr(), other.ptr()); } 34 35 protected: 36 std::unique_ptr<upb_Arena, decltype(&upb_Arena_Free)> ptr_; 37 }; 38 39 // InlinedArena seeds the arenas with a predefined amount of memory. No heap 40 // memory will be allocated until the initial block is exceeded. 41 template <int N> 42 class InlinedArena : public Arena { 43 public: InlinedArena()44 InlinedArena() : Arena(initial_block_, N) {} ~InlinedArena()45 ~InlinedArena() { 46 // Explicitly destroy the arena now so that it does not outlive 47 // initial_block_. 48 ptr_.reset(); 49 } 50 51 private: 52 InlinedArena(const InlinedArena&) = delete; 53 InlinedArena& operator=(const InlinedArena&) = delete; 54 55 char initial_block_[N]; 56 }; 57 58 } // namespace upb 59 60 #endif // __cplusplus 61 62 #endif // UPB_MEM_ARENA_HPP_ 63