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/allocator.h"
16
17 #include <algorithm>
18 #include <cstring>
19
20 namespace pw {
21
22 using ::pw::allocator::Layout;
23
DoReallocate(void * ptr,Layout new_layout)24 void* Allocator::DoReallocate(void* ptr, Layout new_layout) {
25 if (Resize(ptr, new_layout.size())) {
26 return ptr;
27 }
28 Result<Layout> old_layout = GetUsableLayout(ptr);
29 if (!old_layout.ok()) {
30 return nullptr;
31 }
32 void* new_ptr = Allocate(new_layout);
33 if (new_ptr == nullptr) {
34 return nullptr;
35 }
36 if (ptr != nullptr) {
37 std::memcpy(new_ptr, ptr, std::min(new_layout.size(), old_layout->size()));
38 Deallocate(ptr);
39 }
40 return new_ptr;
41 }
42
DoReallocate(void * ptr,Layout old_layout,size_t new_size)43 void* Allocator::DoReallocate(void* ptr, Layout old_layout, size_t new_size) {
44 return Reallocate(ptr, Layout(new_size, old_layout.alignment()));
45 }
46
47 } // namespace pw
48