datagram_buffer.cc 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2018 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. #include "net/base/datagram_buffer.h"
  5. #include "base/memory/ptr_util.h"
  6. #include <cstring>
  7. namespace net {
  8. DatagramBufferPool::DatagramBufferPool(size_t max_buffer_size)
  9. : max_buffer_size_(max_buffer_size) {}
  10. DatagramBufferPool::~DatagramBufferPool() = default;
  11. void DatagramBufferPool::Enqueue(const char* buffer,
  12. size_t buf_len,
  13. DatagramBuffers* buffers) {
  14. DCHECK_LE(buf_len, max_buffer_size_);
  15. std::unique_ptr<DatagramBuffer> datagram_buffer;
  16. if (free_list_.empty()) {
  17. datagram_buffer = base::WrapUnique(new DatagramBuffer(max_buffer_size_));
  18. } else {
  19. datagram_buffer = std::move(free_list_.front());
  20. free_list_.pop_front();
  21. }
  22. datagram_buffer->Set(buffer, buf_len);
  23. buffers->emplace_back(std::move(datagram_buffer));
  24. }
  25. void DatagramBufferPool::Dequeue(DatagramBuffers* buffers) {
  26. if (buffers->size() == 0)
  27. return;
  28. free_list_.splice(free_list_.cend(), *buffers);
  29. }
  30. DatagramBuffer::DatagramBuffer(size_t max_buffer_size)
  31. : data_(std::make_unique<char[]>(max_buffer_size)) {}
  32. DatagramBuffer::~DatagramBuffer() = default;
  33. void DatagramBuffer::Set(const char* buffer, size_t buf_len) {
  34. length_ = buf_len;
  35. std::memcpy(data_.get(), buffer, buf_len);
  36. }
  37. char* DatagramBuffer::data() const {
  38. return data_.get();
  39. }
  40. size_t DatagramBuffer::length() const {
  41. return length_;
  42. }
  43. } // namespace net