allocator.h 2.5 KB

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