xref: /aosp_15_r20/external/pigweed/pw_allocator/pmr_allocator.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 "pw_allocator/pmr_allocator.h"
16 
17 #include "pw_assert/check.h"
18 
19 namespace pw::allocator::internal {
20 
do_allocate(size_t bytes,size_t alignment)21 void* MemoryResource::do_allocate(size_t bytes, size_t alignment) {
22   void* ptr = nullptr;
23   if (bytes != 0) {
24     ptr = allocator_->Allocate(Layout(bytes, alignment));
25   }
26 
27   // The standard library expects the memory resource to throw an
28   // exception if storage of the requested size and alignment cannot be
29   // obtained. As a result, the uses-allocator types are not required to check
30   // for allocation failure. In lieu of using exceptions, this type asserts that
31   // an allocation must succeed.
32   PW_CHECK_NOTNULL(
33       ptr, "failed to allocate %zu bytes for PMR container", bytes);
34   return ptr;
35 }
36 
do_deallocate(void * p,size_t,size_t)37 void MemoryResource::do_deallocate(void* p, size_t, size_t) {
38   allocator_->Deallocate(p);
39 }
40 
do_is_equal(const pw::pmr::memory_resource & other) const41 bool MemoryResource::do_is_equal(
42     const pw::pmr::memory_resource& other) const noexcept {
43   if (this == &other) {
44     return true;
45   }
46   // If `other` is not the same object as this one, it is only equal if
47   // the other object is a `MemoryResource` with the same allocator. That checks
48   // requires runtime type identification. Without RTTI, two `MemoryResource`s
49   // with the same allocator will be treated as unequal, and moving objects
50   // between them may lead to an extra allocation, copy, and deallocation.
51 #if defined(__cpp_rtti) && __cpp_rtti
52   if (typeid(*this) == typeid(other)) {
53     return allocator_ == static_cast<const MemoryResource&>(other).allocator_;
54   }
55 #endif  // defined(__cpp_rtti) && __cpp_rtti
56   return false;
57 }
58 
59 }  // namespace pw::allocator::internal
60