OGLplus  (0.59.0) a C++ wrapper for rendering APIs

fallback_alloc.hpp
Go to the documentation of this file.
1 
9 #ifndef EAGINE_MEMORY_FALLBACK_ALLOC_HPP
10 #define EAGINE_MEMORY_FALLBACK_ALLOC_HPP
11 
12 #include "../assert.hpp"
13 #include "default_alloc.hpp"
14 #include "shared_alloc.hpp"
15 
16 namespace eagine::memory {
17 
18 template <typename Policy = default_byte_allocator_policy>
19 class byte_allocator_with_fallback
20  : public byte_allocator_impl<Policy, byte_allocator_with_fallback> {
21 private:
22  span_size_t _fbk_size;
23  span_size_t _fbk_max;
24  shared_byte_allocator _dft;
25  shared_byte_allocator _fbk;
26 
27 public:
28  byte_allocator_with_fallback(
29  shared_byte_allocator&& dft,
30  shared_byte_allocator&& fbk = default_byte_allocator())
31  : _fbk_size(0)
32  , _fbk_max(0)
33  , _dft(std::move(dft))
34  , _fbk(std::move(fbk)) {}
35 
36  using size_type = span_size_t;
37 
38  auto equal(byte_allocator* a) const noexcept -> bool override {
39  auto* pa = dynamic_cast<byte_allocator_with_fallback*>(a);
40 
41  if(a != nullptr) {
42  return (_dft == pa->_dft) && (_fbk == pa->_fbk);
43  }
44  return false;
45  }
46 
47  auto max_size(span_size_t a) noexcept -> size_type override {
48  size_type mdft = _dft.max_size(a);
49  size_type mfbk = _fbk.max_size(a);
50 
51  return (mfbk > mdft) ? mfbk : mdft;
52  }
53 
54  auto has_allocated(const owned_block& b, span_size_t a) noexcept
55  -> tribool override {
56  return _dft.has_allocated(b, a) || _fbk.has_allocated(b, a);
57  }
58 
59  auto allocate(size_type n, size_type a) noexcept -> owned_block override {
60  if(n <= _dft.max_size(a)) {
61  if(owned_block b = _dft.allocate(n, a)) {
62  return b;
63  }
64  }
65 
66  _fbk_size += n;
67  if(_fbk_max < _fbk_size) {
68  _fbk_max = _fbk_size;
69  }
70  return _fbk.allocate(n, a);
71  }
72 
73  void deallocate(owned_block&& b, size_type a) noexcept override {
74  if(_dft.has_allocated(b, a)) {
75  _dft.deallocate(std::move(b), a);
76  } else if(!!_fbk.has_allocated(b, a)) {
77  _fbk_size -= b.size();
78  _fbk.deallocate(std::move(b), a);
79  } else {
80  EAGINE_ABORT("Pointer not allocated by this allocator!");
81  }
82  }
83 };
84 
85 } // namespace eagine::memory
86 
87 #endif // EAGINE_MEMORY_FALLBACK_ALLOC_HPP
std::ptrdiff_t span_size_t
Signed span size type used by eagine.
Definition: types.hpp:36

Copyright © 2015-2021 Matúš Chochlík.
<chochlik -at -gmail.com>
Documentation generated on Tue Apr 13 2021 by Doxygen (version 1.8.17).