xref: /aosp_15_r20/external/grpc-grpc/third_party/upb/upb/mem/arena.hpp (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
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 
Fuse(Arena & other)29   void Fuse(Arena& other) { upb_Arena_Fuse(ptr(), other.ptr()); }
30 
31  protected:
32   std::unique_ptr<upb_Arena, decltype(&upb_Arena_Free)> ptr_;
33 };
34 
35 // InlinedArena seeds the arenas with a predefined amount of memory. No heap
36 // memory will be allocated until the initial block is exceeded.
37 template <int N>
38 class InlinedArena : public Arena {
39  public:
InlinedArena()40   InlinedArena() : Arena(initial_block_, N) {}
~InlinedArena()41   ~InlinedArena() {
42     // Explicitly destroy the arena now so that it does not outlive
43     // initial_block_.
44     ptr_.reset();
45   }
46 
47  private:
48   InlinedArena(const InlinedArena&) = delete;
49   InlinedArena& operator=(const InlinedArena&) = delete;
50 
51   char initial_block_[N];
52 };
53 
54 }  // namespace upb
55 
56 #endif  // __cplusplus
57 
58 #endif  // UPB_MEM_ARENA_HPP_
59