Lumiera  0.pre.03
»edit your freedom«
allocator-handle.hpp
Go to the documentation of this file.
1 /*
2  ALLOCATOR-HANDLE.hpp - front-end handle for custom allocation schemes
3 
4  Copyright (C) Lumiera.org
5  2023, Hermann Vosseler <Ichthyostega@web.de>
6 
7  This program is free software; you can redistribute it and/or
8  modify it under the terms of the GNU General Public License as
9  published by the Free Software Foundation; either version 2 of
10  the License, or (at your option) any later version.
11 
12  This program is distributed in the hope that it will be useful,
13  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  GNU General Public License for more details.
16 
17  You should have received a copy of the GNU General Public License
18  along with this program; if not, write to the Free Software
19  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 
21 */
22 
55 #ifndef LIB_ALLOCATOR_HANDLE_H
56 #define LIB_ALLOCATOR_HANDLE_H
57 
58 #include "lib/error.hpp"
59 
60 #include <cstddef>
61 #include <utility>
62 #include <list>
63 
64 
65 
66 namespace lib {
67 
68 
80  template<typename TY>
82  {
83  struct Allocation
84  {
85  alignas(TY)
86  std::byte buf_[sizeof(TY)];
87 
88  template<typename...ARGS>
89  TY&
90  create (ARGS&& ...args)
91  {
92  return *new(&buf_) TY {std::forward<ARGS> (args)...};
93  }
94 
95  TY&
96  access()
97  {
98  return * std::launder (reinterpret_cast<TY*> (&buf_));
99  }
100  void
102  {
103  access().~TY();
104  }
105  };
106 
107  std::list<Allocation> storage_;
108 
109  public:
110  template<typename...ARGS>
111  TY&
112  operator() (ARGS&& ...args)
113  { // EX_STRONG
114  auto pos = storage_.emplace (storage_.end());
115  try {
116  return pos->create (std::forward<ARGS> (args)...);
117  }
118  catch(...)
119  {
120  storage_.erase (pos); // EX_FREE
121 
122  const char* errID = lumiera_error();
123  ERROR (memory, "Allocation failed with unknown exception. "
124  "Lumiera errorID=%s", errID?errID:"??");
125  throw;
126  }
127  }
128 
133  try {
134  for (auto& alloc : storage_)
135  alloc.discard();
136  }
137  ERROR_LOG_AND_IGNORE (memory, "clean-up of custom AllocatorHandle")
138  };
139 
140 
141 
142 } // namespace lib
143 #endif /*LIB_ALLOCATOR_HANDLE_H*/
#define ERROR_LOG_AND_IGNORE(_FLAG_, _OP_DESCR_)
convenience shortcut for a sequence of catch blocks just logging and consuming an error...
Definition: error.hpp:275
Implementation namespace for support and library code.
Placeholder implementation for a custom allocator.
lumiera_err lumiera_error(void)
Get and clear current error state.
Definition: error-state.c:124
Lumiera error handling (C++ interface).