util: add class for storing extensions strings
[platform/core/uifw/vulkan-wsi-tizen.git] / util / custom_allocator.hpp
1 /*
2  * Copyright (c) 2020-2021 Arm Limited.
3  *
4  * SPDX-License-Identifier: MIT
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24
25 #include <new>
26 #include <vector>
27 #include <string>
28 #include <cassert>
29
30 #include <vulkan/vulkan.h>
31
32 #pragma once
33
34 namespace util
35 {
36
37 /**
38  * @brief Minimalistic wrapper of VkAllocationCallbacks.
39  */
40 class allocator
41 {
42 public:
43    /**
44     * @brief Get an allocator that can be used if VkAllocationCallbacks are not provided.
45     */
46    static const allocator& get_generic();
47
48    /**
49     * @brief Construct a new wrapper for the given VK callbacks and scope.
50     * @param callbacks Pointer to allocation callbacks. If this is @c nullptr, then default
51     *   allocation callbacks are used. These can be accessed through #m_callbacks.
52     * @param scope The scope to use for this allocator.
53     */
54    allocator(const VkAllocationCallbacks *callbacks, VkSystemAllocationScope scope);
55
56    /**
57     * @brief Copy the given allocator, but change the allocation scope.
58     */
59    allocator(const allocator& other, VkSystemAllocationScope new_scope);
60
61    /**
62     * @brief Get a pointer to the allocation callbacks provided while constructing this object.
63     * @return a copy of the #VkAllocationCallback argument provided in the allocator constructor
64     *   or @c nullptr if this argument was provided as @c nullptr.
65     * @note The #m_callbacks member is always populated with callable pointers for pfnAllocation,
66     *   pfnReallocation and pfnFree.
67     */
68    const VkAllocationCallbacks *get_original_callbacks() const;
69
70    /**
71     * @brief Helper method to allocate and construct objects with a custom allocator.
72     * @param num_objects Number of objects to create.
73     * @return Pointer to the newly created objects or @c nullptr if allocation failed.
74     */
75    template <typename T, typename... arg_types>
76    T *create(size_t num_objects, arg_types &&... args) const noexcept;
77
78    /**
79     * @brief Helper method to destroy and deallocate objects constructed with allocator::create().
80     * @param num_objects Number of objects to destroy.
81     */
82    template <typename T>
83    void destroy(size_t num_objects, T *obj) const noexcept;
84
85    VkAllocationCallbacks m_callbacks;
86    VkSystemAllocationScope m_scope;
87 };
88
89 /**
90  * @brief Implementation of an allocator that can be used with STL containers.
91  */
92 template <typename T>
93 class custom_allocator
94 {
95 public:
96    using value_type = T;
97    using pointer = T *;
98
99    custom_allocator(const allocator &alloc)
100       : m_alloc(alloc)
101    {
102    }
103
104    template <typename U>
105    custom_allocator(const custom_allocator<U> &other)
106       : m_alloc(other.get_data())
107    {
108    }
109
110    const allocator &get_data() const
111    {
112       return m_alloc;
113    }
114
115    pointer allocate(size_t n) const
116    {
117       size_t size = n * sizeof(T);
118       auto &cb = m_alloc.m_callbacks;
119       void *ret = cb.pfnAllocation(cb.pUserData, size, alignof(T), m_alloc.m_scope);
120       if (ret == nullptr)
121          throw std::bad_alloc();
122       return reinterpret_cast<pointer>(ret);
123    }
124
125    pointer allocate(size_t n, void *ptr) const
126    {
127       size_t size = n * sizeof(T);
128       auto &cb = m_alloc.m_callbacks;
129       void *ret = cb.pfnReallocation(cb.pUserData, ptr, size, alignof(T), m_alloc.m_scope);
130       if (ret == nullptr)
131          throw std::bad_alloc();
132       return reinterpret_cast<pointer>(ret);
133    }
134
135    void deallocate(void *ptr, size_t) const noexcept
136    {
137       m_alloc.m_callbacks.pfnFree(m_alloc.m_callbacks.pUserData, ptr);
138    }
139
140 private:
141    const allocator m_alloc;
142 };
143
144 template <typename T, typename U>
145 bool operator==(const custom_allocator<T> &, const custom_allocator<U> &)
146 {
147    return true;
148 }
149
150 template <typename T, typename U>
151 bool operator!=(const custom_allocator<T> &, const custom_allocator<U> &)
152 {
153    return false;
154 }
155
156 template <typename T, typename... arg_types>
157 T *allocator::create(size_t num_objects, arg_types &&... args) const noexcept
158 {
159    if (num_objects < 1)
160    {
161       return nullptr;
162    }
163
164    custom_allocator<T> allocator(*this);
165    T *ptr;
166    try
167    {
168       ptr = allocator.allocate(num_objects);
169    }
170    catch (...)
171    {
172       return nullptr;
173    }
174
175    size_t objects_constructed = 0;
176    try
177    {
178       while (objects_constructed < num_objects)
179       {
180          T *next_object = &ptr[objects_constructed];
181          new (next_object) T(std::forward<arg_types>(args)...);
182          objects_constructed++;
183       }
184    }
185    catch (...)
186    {
187       /* We catch all exceptions thrown while constructing the object, not just
188        * std::bad_alloc.
189        */
190       while (objects_constructed > 0)
191       {
192          objects_constructed--;
193          ptr[objects_constructed].~T();
194       }
195       allocator.deallocate(ptr, num_objects);
196       return nullptr;
197    }
198    return ptr;
199 }
200
201 template <typename T>
202 void allocator::destroy(size_t num_objects, T *objects) const noexcept
203 {
204    assert((objects == nullptr) == (num_objects == 0));
205    if (num_objects == 0)
206    {
207       return;
208    }
209
210    custom_allocator<T> allocator(*this);
211    for (size_t i = 0; i < num_objects; i++)
212    {
213       objects[i].~T();
214    }
215    allocator.deallocate(objects, num_objects);
216 }
217
218 template <typename T>
219 void destroy_custom(T *obj)
220 {
221    T::destroy(obj);
222 }
223
224 /**
225  * @brief Vector using a Vulkan custom allocator to allocate its elements.
226  * @note The vector must be passed a custom_allocator during construction and it takes a copy
227  *   of it, meaning that the user is free to destroy the custom_allocator after constructing the
228  *   vector.
229  */
230 template <typename T>
231 class vector : public std::vector<T, custom_allocator<T>>
232 {
233 public:
234    using base = std::vector<T, custom_allocator<T>>;
235    using base::base;
236
237    /* Delete all methods that can cause allocation failure, i.e. can throw std::bad_alloc.
238     *
239     * Rationale: we want to force users to use our corresponding try_... method instead:
240     * this makes the API slightly more annoying to use, but hopefully safer as it encourages
241     * users to check for allocation failures, which is important for Vulkan.
242     *
243     * Note: deleting each of these methods (below) deletes all its overloads from the base class,
244     *   to be precise: the deleted method covers the methods (all overloads) in the base class.
245     * Note: clear() is already noexcept since C++11.
246     */
247    void insert() = delete;
248    void emplace() = delete;
249    void emplace_back() = delete;
250    void push_back() = delete;
251    void resize() = delete;
252    void reserve() = delete;
253
254    /* Note pop_back(), erase(), clear() do not throw std::bad_alloc exceptions. */
255
256    /* @brief Like std::vector::push_back, but non throwing.
257     * @return @c false iff the operation could not be performed due to an allocation failure.
258     */
259    template <typename... arg_types>
260    bool try_push_back(arg_types &&... args) noexcept
261    {
262       try
263       {
264          base::push_back(std::forward<arg_types>(args)...);
265          return true;
266       }
267       catch (const std::bad_alloc &e)
268       {
269          return false;
270       }
271    }
272
273    /* @brief push back multiple elements at once
274     * @return @c false iff the operation could not be performed due to an allocation failure.
275     */
276    bool try_push_back_many(const T *begin, const T *end) noexcept
277    {
278       for (const T *it = begin; it != end; ++it)
279       {
280          if (!try_push_back(*it))
281          {
282             return false;
283          }
284       }
285       return true;
286    }
287
288    /* @brief Like std::vector::resize, but non throwing.
289     * @return @c false iff the operation could not be performed due to an allocation failure.
290     */
291    template <typename... arg_types>
292    bool try_resize(arg_types &&... args) noexcept
293    {
294       try
295       {
296          base::resize(std::forward<arg_types>(args)...);
297          return true;
298       }
299       catch (const std::bad_alloc &e)
300       {
301          return false;
302       }
303    }
304 };
305
306 } /* namespace util */