blob: 4b0abf4456842fbc2fe2808a370d4ac302fed964 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// 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
vasilvvff082a02019-12-24 22:07:51 -080010#include <memory>
11
QUICHE teama6ef0a62019-03-07 20:34:33 -050012#include "net/third_party/quiche/src/quic/platform/api/quic_export.h"
13
14namespace quic {
15
16// Abstract base class for classes which allocate and delete buffers.
17class 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.
34 virtual void MarkAllocatorIdle() {}
35};
36
vasilvvff082a02019-12-24 22:07:51 -080037// A deleter that can be used to manage ownership of buffers allocated via
38// QuicBufferAllocator through std::unique_ptr.
39class QUIC_EXPORT_PRIVATE QuicBufferDeleter {
40 public:
41 explicit QuicBufferDeleter(QuicBufferAllocator* allocator)
42 : allocator_(allocator) {}
43
44 QuicBufferAllocator* allocator() { return allocator_; }
45 void operator()(char* buffer) { allocator_->Delete(buffer); }
46
47 private:
48 QuicBufferAllocator* allocator_;
49};
50
51using QuicUniqueBufferPtr = std::unique_ptr<char[], QuicBufferDeleter>;
52
53inline QuicUniqueBufferPtr MakeUniqueBuffer(QuicBufferAllocator* allocator,
54 size_t size) {
55 return QuicUniqueBufferPtr(allocator->New(size),
56 QuicBufferDeleter(allocator));
57}
58
QUICHE teama6ef0a62019-03-07 20:34:33 -050059} // namespace quic
60
61#endif // QUICHE_QUIC_CORE_QUIC_BUFFER_ALLOCATOR_H_