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