C++ Essence Library 0.1.0
A Utility Library for Modern C++ Programming
Loading...
Searching...
No Matches
memory.hpp
1/*
2 * Copyright (c) 2024 The RefValue Project
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 * THE SOFTWARE.
21 */
22
23#pragma once
24
25#include <cstddef>
26#include <functional>
27#include <memory>
28#include <new>
29#include <span>
30
31namespace essence {
32 template <typename T>
33 using unique_array = std::unique_ptr<std::span<T>, std::function<void(std::span<T>*)>>;
34
41 template <typename T>
42 auto make_unique_array(std::size_t size) {
43 auto buffer = std::make_unique_for_overwrite<std::byte[]>(sizeof(std::span<T>) + size * sizeof(T));
44 auto span = new (buffer.get()) std::span{new (buffer.get() + sizeof(std::span<T>)) T[size]{}, size};
45 auto deleter = [size](std::span<T>* inner) {
46 auto data = std::launder(reinterpret_cast<T*>(reinterpret_cast<std::byte*>(inner) + sizeof(std::span<T>)));
47
48 inner->~span();
49 std::ranges::destroy(data, data + size);
50 std::default_delete<std::byte[]>{}(reinterpret_cast<std::byte*>(inner));
51 };
52
53 buffer.release();
54
55 return unique_array<T>{span, deleter};
56 }
57} // namespace essence