From 5b5c0130da32cd740fc8b4773745d55dacc69572 Mon Sep 17 00:00:00 2001 From: Merry Date: Sun, 10 Jul 2022 10:00:42 +0100 Subject: [PATCH] memory: Add overaligned_unique_ptr --- include/mcl/memory/overaligned_unique_ptr.hpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 include/mcl/memory/overaligned_unique_ptr.hpp diff --git a/include/mcl/memory/overaligned_unique_ptr.hpp b/include/mcl/memory/overaligned_unique_ptr.hpp new file mode 100644 index 0000000..1e645ef --- /dev/null +++ b/include/mcl/memory/overaligned_unique_ptr.hpp @@ -0,0 +1,46 @@ +// This file is part of the mcl project. +// Copyright (c) 2022 merryhime +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#ifdef _MSC_VER +# include +#else +# include +#endif + +namespace mcl { + +namespace detail { +struct aligned_alloc_deleter { + template + void operator()(T* p) const + { +#ifdef _MSC_VER + _aligned_free(const_cast*>(p)); +#else + std::free(const_cast*>(p)); +#endif + } +}; +} // namespace detail + +template +using overaligned_unique_ptr = std::unique_ptr; + +template +auto make_overaligned_unique_ptr_array(size_t element_count) +{ + const size_t min_size = element_count * sizeof(T); + const size_t alloc_size = (min_size + alignment - 1) / alignment * alignment; +#ifdef _MSC_VER + return overaligned_unique_ptr{static_cast(_aligned_malloc(alloc_size, alignment))}; +#else + return overaligned_unique_ptr{static_cast(std::aligned_alloc(alignment, alloc_size))}; +#endif +} + +} // namespace mcl