1 // Copyright (c) 2012 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_QUIC_CORE_QUIC_BUFFER_ALLOCATOR_H_
6 #define QUICHE_QUIC_CORE_QUIC_BUFFER_ALLOCATOR_H_
7 
8 #include <stddef.h>
9 
10 #include <memory>
11 
12 #include "net/third_party/quiche/src/quic/platform/api/quic_export.h"
13 
14 namespace quic {
15 
16 // Abstract base class for classes which allocate and delete buffers.
17 class QUIC_EXPORT_PRIVATE QuicBufferAllocator {
18  public:
19   virtual ~QuicBufferAllocator();
20 
21   // Returns or allocates a new buffer of |size|. Never returns null.
22   virtual char* New(size_t size) = 0;
23 
24   // Returns or allocates a new buffer of |size| if |flag_enable| is true.
25   // Otherwise, returns a buffer that is compatible with this class directly
26   // with operator new. Never returns null.
27   virtual char* New(size_t size, bool flag_enable) = 0;
28 
29   // Releases a buffer.
30   virtual void Delete(char* buffer) = 0;
31 
32   // Marks the allocator as being idle. Serves as a hint to notify the allocator
33   // that it should release any resources it's still holding on to.
MarkAllocatorIdle()34   virtual void MarkAllocatorIdle() {}
35 };
36 
37 // A deleter that can be used to manage ownership of buffers allocated via
38 // QuicBufferAllocator through std::unique_ptr.
39 class QUIC_EXPORT_PRIVATE QuicBufferDeleter {
40  public:
QuicBufferDeleter(QuicBufferAllocator * allocator)41   explicit QuicBufferDeleter(QuicBufferAllocator* allocator)
42       : allocator_(allocator) {}
43 
allocator()44   QuicBufferAllocator* allocator() { return allocator_; }
operator()45   void operator()(char* buffer) { allocator_->Delete(buffer); }
46 
47  private:
48   QuicBufferAllocator* allocator_;
49 };
50 
51 using QuicUniqueBufferPtr = std::unique_ptr<char[], QuicBufferDeleter>;
52 
MakeUniqueBuffer(QuicBufferAllocator * allocator,size_t size)53 inline QuicUniqueBufferPtr MakeUniqueBuffer(QuicBufferAllocator* allocator,
54                                             size_t size) {
55   return QuicUniqueBufferPtr(allocator->New(size),
56                              QuicBufferDeleter(allocator));
57 }
58 
59 }  // namespace quic
60 
61 #endif  // QUICHE_QUIC_CORE_QUIC_BUFFER_ALLOCATOR_H_
62