1 // Copyright 2016 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef QUICHE_COMMON_QUICHE_SIMPLE_ARENA_H_ 6 #define QUICHE_COMMON_QUICHE_SIMPLE_ARENA_H_ 7 8 #include <memory> 9 #include <vector> 10 11 #include "quiche/common/platform/api/quiche_export.h" 12 13 namespace quiche { 14 15 // Allocates large blocks of memory, and doles them out in smaller chunks. 16 // Not thread-safe. 17 class QUICHE_EXPORT QuicheSimpleArena { 18 public: 19 class QUICHE_EXPORT Status { 20 private: 21 friend class QuicheSimpleArena; 22 size_t bytes_allocated_; 23 24 public: Status()25 Status() : bytes_allocated_(0) {} bytes_allocated()26 size_t bytes_allocated() const { return bytes_allocated_; } 27 }; 28 29 // Blocks allocated by this arena will be at least |block_size| bytes. 30 explicit QuicheSimpleArena(size_t block_size); 31 ~QuicheSimpleArena(); 32 33 // Copy and assign are not allowed. 34 QuicheSimpleArena() = delete; 35 QuicheSimpleArena(const QuicheSimpleArena&) = delete; 36 QuicheSimpleArena& operator=(const QuicheSimpleArena&) = delete; 37 38 // Move is allowed. 39 QuicheSimpleArena(QuicheSimpleArena&& other); 40 QuicheSimpleArena& operator=(QuicheSimpleArena&& other); 41 42 char* Alloc(size_t size); 43 char* Realloc(char* original, size_t oldsize, size_t newsize); 44 char* Memdup(const char* data, size_t size); 45 46 // If |data| and |size| describe the most recent allocation made from this 47 // arena, the memory is reclaimed. Otherwise, this method is a no-op. 48 void Free(char* data, size_t size); 49 50 void Reset(); 51 status()52 Status status() const { return status_; } 53 54 private: 55 struct QUICHE_EXPORT Block { 56 std::unique_ptr<char[]> data; 57 size_t size = 0; 58 size_t used = 0; 59 60 explicit Block(size_t s); 61 ~Block(); 62 63 Block(Block&& other); 64 Block& operator=(Block&& other); 65 }; 66 67 void Reserve(size_t additional_space); 68 void AllocBlock(size_t size); 69 70 size_t block_size_; 71 std::vector<Block> blocks_; 72 Status status_; 73 }; 74 75 } // namespace quiche 76 77 #endif // QUICHE_COMMON_QUICHE_SIMPLE_ARENA_H_ 78