Skip to content

Commit

Permalink
Common: Add aligned_unique_ptr
Browse files Browse the repository at this point in the history
  • Loading branch information
stenzek committed Sep 1, 2024
1 parent 81c9bde commit 14ab642
Showing 1 changed file with 45 additions and 1 deletion.
46 changes: 45 additions & 1 deletion src/common/align.h
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
// SPDX-FileCopyrightText: 2019-2022 Connor McLaughlin <[email protected]>
// SPDX-FileCopyrightText: 2019-2024 Connor McLaughlin <[email protected]>
// SPDX-License-Identifier: (GPL-3.0 OR CC-BY-NC-ND-4.0)

#pragma once

#include "types.h"

#include <cstdlib>
#include <memory>
#include <type_traits>

#ifdef _MSC_VER
#include <malloc.h>
Expand Down Expand Up @@ -109,4 +111,46 @@ ALWAYS_INLINE static void AlignedFree(void* ptr)
#endif
}

namespace detail {
template<class T>
struct unique_aligned_ptr_deleter
{
ALWAYS_INLINE void operator()(T* ptr) { Common::AlignedFree(ptr); }
};

template<class>
constexpr bool is_unbounded_array_v = false;
template<class T>
constexpr bool is_unbounded_array_v<T[]> = true;

template<class>
constexpr bool is_bounded_array_v = false;
template<class T, std::size_t N>
constexpr bool is_bounded_array_v<T[N]> = true;
} // namespace detail

template<class T>
using unique_aligned_ptr = std::unique_ptr<T, detail::unique_aligned_ptr_deleter<std::remove_extent_t<T>>>;

template<class T, class... Args>
requires(std::is_unbounded_array_v<T>, std::is_trivially_default_constructible_v<std::remove_extent_t<T>>,
std::is_trivially_destructible_v<std::remove_extent_t<T>>)
unique_aligned_ptr<T> make_unique_aligned(size_t alignment, size_t n)
{
unique_aligned_ptr<T> ptr(
static_cast<std::remove_extent_t<T>*>(AlignedMalloc(sizeof(std::remove_extent_t<T>) * n, alignment)));
if (ptr)
new (ptr.get()) std::remove_extent_t<T>[ n ]();
return ptr;
}

template<class T, class... Args>
requires(std::is_unbounded_array_v<T>, std::is_trivially_default_constructible_v<std::remove_extent_t<T>>,
std::is_trivially_destructible_v<std::remove_extent_t<T>>)
unique_aligned_ptr<T> make_unique_aligned_for_overwrite(size_t alignment, size_t n)
{
return unique_aligned_ptr<T>(
static_cast<std::remove_extent_t<T>*>(AlignedMalloc(sizeof(std::remove_extent_t<T>) * n, alignment)));
}

} // namespace Common

0 comments on commit 14ab642

Please sign in to comment.