xref: /aosp_15_r20/external/pigweed/pw_libcxx/operator_new_test.cc (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 
15 #include <new>
16 
17 #include "pw_unit_test/framework.h"
18 
19 namespace pw {
20 namespace {
21 
CheckNonNull(void * ptr)22 void CheckNonNull(void* ptr) {
23   EXPECT_NE(ptr, nullptr);
24   ::operator delete(ptr);
25 }
26 
CheckNonNullArray(void * ptr)27 void CheckNonNullArray(void* ptr) {
28   EXPECT_NE(ptr, nullptr);
29   ::operator delete[](ptr);
30 }
31 
CheckNonNullWithAlignment(void * ptr,std::align_val_t alignment)32 void CheckNonNullWithAlignment(void* ptr, std::align_val_t alignment) {
33   EXPECT_NE(ptr, nullptr);
34   EXPECT_EQ(reinterpret_cast<uintptr_t>(ptr) % static_cast<size_t>(alignment),
35             size_t{0});
36   ::operator delete(ptr, alignment);
37 }
38 
CheckNonNullArrayWithAlignment(void * ptr,std::align_val_t alignment)39 void CheckNonNullArrayWithAlignment(void* ptr, std::align_val_t alignment) {
40   EXPECT_NE(ptr, nullptr);
41   EXPECT_EQ(reinterpret_cast<uintptr_t>(ptr) % static_cast<size_t>(alignment),
42             size_t{0});
43   ::operator delete[](ptr, alignment);
44 }
45 
TEST(OperatorNew,CallAllNews)46 TEST(OperatorNew, CallAllNews) {
47   constexpr std::align_val_t kAlignment{16};
48   constexpr size_t kSize{16};
49   char kBuff[kSize];
50 
51   // Replaceable allocation functions
52   CheckNonNull(::operator new(kSize));
53   CheckNonNullArray(::operator new[](kSize));
54   CheckNonNullWithAlignment(::operator new(kSize, kAlignment), kAlignment);
55   CheckNonNullArrayWithAlignment(::operator new[](kSize, kAlignment),
56                                  kAlignment);
57 
58   // Replaceable non-throwing allocation functions
59   CheckNonNull(::operator new(kSize, std::nothrow));
60   CheckNonNullArray(::operator new[](kSize, std::nothrow));
61   CheckNonNullWithAlignment(::operator new(kSize, kAlignment, std::nothrow),
62                             kAlignment);
63   CheckNonNullArrayWithAlignment(
64       ::operator new[](kSize, kAlignment, std::nothrow), kAlignment);
65 
66   // Non-allocating placement allocation functions
67   EXPECT_EQ(::operator new(kSize, kBuff), kBuff);
68   EXPECT_EQ(::operator new[](kSize, kBuff), kBuff);
69 }
70 
71 }  // namespace
72 }  // namespace pw
73