1 // Copyright 2024 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 #pragma once 15 16 #include <algorithm> 17 #include <cstddef> 18 #include <initializer_list> 19 #include <optional> 20 21 #include "pw_allocator/synchronized_allocator.h" 22 #include "pw_allocator/testing.h" 23 #include "pw_assert/assert.h" 24 #include "pw_multibuf/simple_allocator.h" 25 26 namespace pw::multibuf::test { 27 28 /// Simple, self-contained `pw::multibuf::MultiBufAllocator` for test use. 29 template <size_t kDataSizeBytes = 1024, size_t kMetaSizeBytes = kDataSizeBytes> 30 class SimpleAllocatorForTest : public SimpleAllocator { 31 public: 32 /// Size of the data area. data_size_bytes()33 static constexpr size_t data_size_bytes() { return kDataSizeBytes; } 34 SimpleAllocatorForTest()35 SimpleAllocatorForTest() 36 : SimpleAllocator(data_area_, meta_alloc_), meta_alloc_(alloc_) {} 37 38 /// Allocates a `MultiBuf` and initializes its contents to the provided data. BufWith(std::initializer_list<std::byte> data)39 MultiBuf BufWith(std::initializer_list<std::byte> data) { 40 std::optional<MultiBuf> buffer = Allocate(data.size()); 41 PW_ASSERT(buffer.has_value()); 42 std::copy(data.begin(), data.end(), buffer->begin()); 43 return *std::move(buffer); 44 } 45 46 private: 47 std::byte data_area_[kDataSizeBytes]; 48 allocator::test::AllocatorForTest<kMetaSizeBytes> alloc_; 49 allocator::SynchronizedAllocator<sync::Mutex> meta_alloc_; 50 }; 51 52 } // namespace pw::multibuf::test 53