xref: /aosp_15_r20/external/pigweed/pw_multibuf/public/pw_multibuf/simple_allocator_for_test.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
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/testing.h"
22 #include "pw_assert/assert.h"
23 #include "pw_multibuf/simple_allocator.h"
24 
25 namespace pw::multibuf::test {
26 
27 /// Simple, self-contained `pw::multibuf::MultiBufAllocator` for test use.
28 template <size_t kDataSizeBytes = 1024, size_t kMetaSizeBytes = kDataSizeBytes>
29 class SimpleAllocatorForTest : public SimpleAllocator {
30  public:
31   /// Size of the data area.
data_size_bytes()32   static constexpr size_t data_size_bytes() { return kDataSizeBytes; }
33 
SimpleAllocatorForTest()34   SimpleAllocatorForTest() : SimpleAllocator(data_area_, meta_alloc_) {}
35 
36   /// Allocates a `MultiBuf` and initializes its contents to the provided data.
BufWith(std::initializer_list<std::byte> data)37   MultiBuf BufWith(std::initializer_list<std::byte> data) {
38     std::optional<MultiBuf> buffer = Allocate(data.size());
39     PW_ASSERT(buffer.has_value());
40     std::copy(data.begin(), data.end(), buffer->begin());
41     return *std::move(buffer);
42   }
43 
44  private:
45   std::byte data_area_[kDataSizeBytes];
46   allocator::test::SynchronizedAllocatorForTest<kMetaSizeBytes> meta_alloc_;
47 };
48 
49 }  // namespace pw::multibuf::test
50