xref: /aosp_15_r20/external/pigweed/pw_allocator/libc_allocator_test.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2023 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_allocator/libc_allocator.h"
16 
17 #include <cstring>
18 
19 #include "pw_unit_test/framework.h"
20 
21 namespace {
22 
23 using ::pw::allocator::GetLibCAllocator;
24 using ::pw::allocator::Layout;
25 
TEST(LibCAllocatorTest,AllocateDeallocate)26 TEST(LibCAllocatorTest, AllocateDeallocate) {
27   pw::Allocator& allocator = GetLibCAllocator();
28   constexpr Layout layout = Layout::Of<std::byte[64]>();
29   void* ptr = allocator.Allocate(layout);
30   ASSERT_NE(ptr, nullptr);
31   // Check that the pointer can be dereferenced.
32   memset(ptr, 0xAB, layout.size());
33   allocator.Deallocate(ptr);
34 }
35 
TEST(LibCAllocatorTest,AllocatorHasGlobalLifetime)36 TEST(LibCAllocatorTest, AllocatorHasGlobalLifetime) {
37   void* ptr = nullptr;
38   constexpr Layout layout = Layout::Of<std::byte[64]>();
39   {
40     ptr = GetLibCAllocator().Allocate(layout);
41     ASSERT_NE(ptr, nullptr);
42   }
43   // Check that the pointer can be dereferenced.
44   {
45     memset(ptr, 0xAB, layout.size());
46     GetLibCAllocator().Deallocate(ptr);
47   }
48 }
49 
TEST(LibCAllocatorTest,AllocateLargeAlignment)50 TEST(LibCAllocatorTest, AllocateLargeAlignment) {
51   pw::Allocator& allocator = GetLibCAllocator();
52   /// TODO: b/301930507 - `aligned_alloc` is not portable. As a result, this
53   /// allocator has a maximum alignment of `std::align_max_t`.
54   size_t size = 16;
55   size_t alignment = alignof(std::max_align_t) * 2;
56   void* ptr = allocator.Allocate(Layout(size, alignment));
57   EXPECT_EQ(ptr, nullptr);
58 }
59 
TEST(LibCAllocatorTest,Reallocate)60 TEST(LibCAllocatorTest, Reallocate) {
61   pw::Allocator& allocator = GetLibCAllocator();
62   constexpr Layout old_layout = Layout::Of<uint32_t[4]>();
63   void* ptr = allocator.Allocate(old_layout);
64   ASSERT_NE(ptr, nullptr);
65   constexpr Layout new_layout(sizeof(uint32_t[3]), old_layout.alignment());
66   void* new_ptr = allocator.Reallocate(ptr, new_layout);
67   ASSERT_NE(new_ptr, nullptr);
68   allocator.Deallocate(new_ptr);
69 }
70 
71 }  // namespace
72