| 1 | /* |
| 2 | * This file is part of the DXX-Rebirth project <https://www.dxx-rebirth.com/>. |
| 3 | * It is copyright by its individual contributors, as recorded in the |
| 4 | * project's Git history. See COPYING.txt at the top level for license |
| 5 | * terms and a link to the Git history. |
| 6 | */ |
| 7 | |
| 8 | #pragma once |
| 9 | #include <memory> |
| 10 | #include <span> |
| 11 | |
| 12 | namespace dcx { |
| 13 | |
| 14 | /* `unique_span` wraps `unique_ptr<T[]>`, but also remembers the extent of the |
| 15 | * array `T[]`. The method `span()` returns a |
| 16 | * `std::span<T, std::dynamic_extent>` that covers the memory region managed by |
| 17 | * `unique_span`. There is no support for a `std::span<T, static_length>`, |
| 18 | * because that could be more simply handled by |
| 19 | * `std::unique_ptr<std::array<T, static_length>>`, which would avoid |
| 20 | * storing the extent in the `unique_span`. |
| 21 | */ |
| 22 | /* Set a default deleter from the underlying unique_ptr, but allow it to be |
| 23 | * overridden if the caller needs special handling. |
| 24 | */ |
| 25 | template <typename T, typename Deleter = typename std::unique_ptr<T[]>::deleter_type> |
| 26 | class unique_span : std::unique_ptr<T[], Deleter> |
| 27 | { |
| 28 | using base_type = std::unique_ptr<T[], Deleter>; |
| 29 | std::size_t extent{}; |
| 30 | public: |
| 31 | constexpr unique_span() = default; |
| 32 | constexpr unique_span(base_type &&b, const std::size_t e) : |
| 33 | base_type{std::move(b)}, |
| 34 | extent{e} |
| 35 | { |
| 36 | } |
| 37 | unique_span(const std::size_t e) : |
| 38 | base_type{new T[e]()}, |
| 39 | extent{e} |
| 40 | { |
| 41 | } |
| 42 | unique_span(unique_span &&) = default; |
| 43 | unique_span &operator=(unique_span &&) = default; |
| 44 | using base_type::get; |
| 45 | /* Require an lvalue input, since the returned pointer is borrowed from |
| 46 | * this object. If the method is called on an rvalue input, then the |
| 47 | * unique_ptr would be destroyed and free the memory before the returned |
| 48 | * span was destroyed, which would leave the span dangling. |
| 49 | */ |
| 50 | [[nodiscard]] |
| 51 | std::span<T> span() & |
| 52 | { |
| 53 | return {get(), extent}; |
| 54 | } |
| 55 | [[nodiscard]] |
| 56 | std::span<const T> span() const & |
| 57 | { |
| 58 | return {get(), extent}; |
| 59 | } |
| 60 | std::span<const T> span() const && = delete; |
| 61 | auto release() |
| 62 | { |
| 63 | extent = 0; |
| 64 | return this->base_type::release(); |
| 65 | } |
| 66 | std::size_t size() const |
| 67 | { |
| 68 | return extent; |
| 69 | } |
| 70 | /* Inherit the zero-argument form of reset(), for clearing an allocation. |
| 71 | * Override and delete the one-argument form, so that the object cannot be |
| 72 | * given new contents, with a potentially different length, using |
| 73 | * `reset(other_pointer);` |
| 74 | */ |
| 75 | using base_type::reset; |
| 76 | void reset(auto) = delete; |
| 77 | }; |
| 78 | |
| 79 | } |