/src/flatbuffers/include/flatbuffers/default_allocator.h
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * Copyright 2021 Google Inc. All rights reserved. |
3 | | * |
4 | | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | | * you may not use this file except in compliance with the License. |
6 | | * You may obtain a copy of the License at |
7 | | * |
8 | | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | | * |
10 | | * Unless required by applicable law or agreed to in writing, software |
11 | | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | | * See the License for the specific language governing permissions and |
14 | | * limitations under the License. |
15 | | */ |
16 | | |
17 | | #ifndef FLATBUFFERS_DEFAULT_ALLOCATOR_H_ |
18 | | #define FLATBUFFERS_DEFAULT_ALLOCATOR_H_ |
19 | | |
20 | | #include "flatbuffers/allocator.h" |
21 | | #include "flatbuffers/base.h" |
22 | | |
23 | | namespace flatbuffers { |
24 | | |
25 | | // DefaultAllocator uses new/delete to allocate memory regions |
26 | | class DefaultAllocator : public Allocator { |
27 | | public: |
28 | 116k | uint8_t *allocate(size_t size) FLATBUFFERS_OVERRIDE { |
29 | 116k | return new uint8_t[size]; |
30 | 116k | } |
31 | | |
32 | 115k | void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE { delete[] p; } |
33 | | |
34 | 0 | static void dealloc(void *p, size_t) { delete[] static_cast<uint8_t *>(p); } |
35 | | }; |
36 | | |
37 | | // These functions allow for a null allocator to mean use the default allocator, |
38 | | // as used by DetachedBuffer and vector_downward below. |
39 | | // This is to avoid having a statically or dynamically allocated default |
40 | | // allocator, or having to move it between the classes that may own it. |
41 | 110k | inline uint8_t *Allocate(Allocator *allocator, size_t size) { |
42 | 110k | return allocator ? allocator->allocate(size) |
43 | 110k | : DefaultAllocator().allocate(size); |
44 | 110k | } |
45 | | |
46 | 110k | inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) { |
47 | 110k | if (allocator) |
48 | 0 | allocator->deallocate(p, size); |
49 | 110k | else |
50 | 110k | DefaultAllocator().deallocate(p, size); |
51 | 110k | } |
52 | | |
53 | | inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p, |
54 | | size_t old_size, size_t new_size, |
55 | 5.44k | size_t in_use_back, size_t in_use_front) { |
56 | 5.44k | return allocator ? allocator->reallocate_downward(old_p, old_size, new_size, |
57 | 0 | in_use_back, in_use_front) |
58 | 5.44k | : DefaultAllocator().reallocate_downward( |
59 | 5.44k | old_p, old_size, new_size, in_use_back, in_use_front); |
60 | 5.44k | } |
61 | | |
62 | | } // namespace flatbuffers |
63 | | |
64 | | #endif // FLATBUFFERS_DEFAULT_ALLOCATOR_H_ |