Coverage Report

Created: 2023-09-25 06:29

/src/flatbuffers/include/flatbuffers/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_ALLOCATOR_H_
18
#define FLATBUFFERS_ALLOCATOR_H_
19
20
#include "flatbuffers/base.h"
21
22
namespace flatbuffers {
23
24
// Allocator interface. This is flatbuffers-specific and meant only for
25
// `vector_downward` usage.
26
class Allocator {
27
 public:
28
245k
  virtual ~Allocator() {}
29
30
  // Allocate `size` bytes of memory.
31
  virtual uint8_t *allocate(size_t size) = 0;
32
33
  // Deallocate `size` bytes of memory at `p` allocated by this allocator.
34
  virtual void deallocate(uint8_t *p, size_t size) = 0;
35
36
  // Reallocate `new_size` bytes of memory, replacing the old region of size
37
  // `old_size` at `p`. In contrast to a normal realloc, this grows downwards,
38
  // and is intended specifcally for `vector_downward` use.
39
  // `in_use_back` and `in_use_front` indicate how much of `old_size` is
40
  // actually in use at each end, and needs to be copied.
41
  virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size,
42
                                       size_t new_size, size_t in_use_back,
43
5.18k
                                       size_t in_use_front) {
44
5.18k
    FLATBUFFERS_ASSERT(new_size > old_size);  // vector_downward only grows
45
0
    uint8_t *new_p = allocate(new_size);
46
5.18k
    memcpy_downward(old_p, old_size, new_p, new_size, in_use_back,
47
5.18k
                    in_use_front);
48
5.18k
    deallocate(old_p, old_size);
49
5.18k
    return new_p;
50
5.18k
  }
51
52
 protected:
53
  // Called by `reallocate_downward` to copy memory from `old_p` of `old_size`
54
  // to `new_p` of `new_size`. Only memory of size `in_use_front` and
55
  // `in_use_back` will be copied from the front and back of the old memory
56
  // allocation.
57
  void memcpy_downward(uint8_t *old_p, size_t old_size, uint8_t *new_p,
58
                       size_t new_size, size_t in_use_back,
59
5.18k
                       size_t in_use_front) {
60
5.18k
    memcpy(new_p + new_size - in_use_back, old_p + old_size - in_use_back,
61
5.18k
           in_use_back);
62
5.18k
    memcpy(new_p, old_p, in_use_front);
63
5.18k
  }
64
};
65
66
}  // namespace flatbuffers
67
68
#endif  // FLATBUFFERS_ALLOCATOR_H_