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> allocated = GetAllocatedLayout(ptr);
29 if (!allocated.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(), allocated->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 if (Resize(ptr, old_layout, new_size)) {
45 return ptr;
46 }
47 Result<Layout> allocated = GetAllocatedLayout(ptr);
48 if (!allocated.ok()) {
49 return nullptr;
50 }
51 void* new_ptr = Allocate(Layout(new_size, old_layout.alignment()));
52 if (new_ptr == nullptr) {
53 return nullptr;
54 }
55 if (ptr != nullptr) {
56 std::memcpy(new_ptr, ptr, std::min(new_size, allocated->size()));
57 Deallocate(ptr, *allocated);
58 }
59 return new_ptr;
60 }
61
62 } // namespace pw
63