1 // Copyright 2018 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/base/datagram_buffer.h"
6
7 #include "base/memory/ptr_util.h"
8
9 #include <cstring>
10
11 namespace net {
12
DatagramBufferPool(size_t max_buffer_size)13 DatagramBufferPool::DatagramBufferPool(size_t max_buffer_size)
14 : max_buffer_size_(max_buffer_size) {}
15
16 DatagramBufferPool::~DatagramBufferPool() = default;
17
Enqueue(const char * buffer,size_t buf_len,DatagramBuffers * buffers)18 void DatagramBufferPool::Enqueue(const char* buffer,
19 size_t buf_len,
20 DatagramBuffers* buffers) {
21 DCHECK_LE(buf_len, max_buffer_size_);
22 std::unique_ptr<DatagramBuffer> datagram_buffer;
23 if (free_list_.empty()) {
24 datagram_buffer = base::WrapUnique(new DatagramBuffer(max_buffer_size_));
25 } else {
26 datagram_buffer = std::move(free_list_.front());
27 free_list_.pop_front();
28 }
29 datagram_buffer->Set(buffer, buf_len);
30 buffers->emplace_back(std::move(datagram_buffer));
31 }
32
Dequeue(DatagramBuffers * buffers)33 void DatagramBufferPool::Dequeue(DatagramBuffers* buffers) {
34 if (buffers->size() == 0)
35 return;
36
37 free_list_.splice(free_list_.cend(), *buffers);
38 }
39
DatagramBuffer(size_t max_buffer_size)40 DatagramBuffer::DatagramBuffer(size_t max_buffer_size)
41 : data_(std::make_unique<char[]>(max_buffer_size)) {}
42
43 DatagramBuffer::~DatagramBuffer() = default;
44
Set(const char * buffer,size_t buf_len)45 void DatagramBuffer::Set(const char* buffer, size_t buf_len) {
46 length_ = buf_len;
47 std::memcpy(data_.get(), buffer, buf_len);
48 }
49
data() const50 char* DatagramBuffer::data() const {
51 return data_.get();
52 }
53
length() const54 size_t DatagramBuffer::length() const {
55 return length_;
56 }
57
58 } // namespace net
59