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
15 #include "pw_multibuf/from_span.h"
16
17 #include "pw_allocator/testing.h"
18 #include "pw_unit_test/framework.h"
19
20 namespace pw::multibuf {
21 namespace {
22
23 using ::pw::allocator::test::AllocatorForTest;
24
25 constexpr size_t kArbitraryBufferSize = 1024;
26 constexpr size_t kArbitraryMetaSize = 1024;
27
28 struct DestroyState {
29 size_t count = 0;
30 ByteSpan last_region = {};
31 };
32
TEST(SimpleAllocator,AllocateWholeDataAreaSizeSucceeds)33 TEST(SimpleAllocator, AllocateWholeDataAreaSizeSucceeds) {
34 std::array<std::byte, kArbitraryBufferSize> data_area;
35 AllocatorForTest<kArbitraryMetaSize> meta_alloc;
36 DestroyState destroy_state;
37 std::optional<MultiBuf> buf = pw::multibuf::FromSpan(
38 meta_alloc, data_area, [&destroy_state](ByteSpan span) {
39 ++destroy_state.count;
40 destroy_state.last_region = span;
41 });
42 ASSERT_TRUE(buf.has_value());
43 EXPECT_EQ(buf->size(), kArbitraryBufferSize);
44 ASSERT_TRUE(buf->IsContiguous());
45 EXPECT_EQ(buf->ContiguousSpan()->data(), data_area.data());
46 EXPECT_EQ(destroy_state.count, 0u);
47 buf = std::nullopt;
48 EXPECT_EQ(destroy_state.count, 1u);
49 EXPECT_EQ(destroy_state.last_region.size(), kArbitraryBufferSize);
50 EXPECT_EQ(destroy_state.last_region.data(), data_area.data());
51 }
52
53 } // namespace
54 } // namespace pw::multibuf
55