From 6d69512c6ff58ee8a7c1266257db5bf94cc91886 Mon Sep 17 00:00:00 2001 From: Steven Le Rouzic Date: Tue, 17 Dec 2024 23:30:44 +0100 Subject: Refactor a bunch of memory utilities --- asl/memory.hpp | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) (limited to 'asl/memory.hpp') diff --git a/asl/memory.hpp b/asl/memory.hpp index 23aa392..7601a7f 100644 --- a/asl/memory.hpp +++ b/asl/memory.hpp @@ -1,6 +1,9 @@ #pragma once #include "asl/integers.hpp" +#include "asl/meta.hpp" +#include "asl/layout.hpp" +#include "asl/utility.hpp" constexpr void* operator new(size_t, void* ptr) { @@ -25,5 +28,53 @@ constexpr isize_t strlen(const char* s) return static_cast(__builtin_strlen(s)); } +template +constexpr T* construct_at(void* ptr, Args&&... args) + requires constructible_from +{ + return new (ptr) T{ ASL_FWD(args)... }; +} + +template +constexpr void destruct(T* data) +{ + if constexpr (!trivially_destructible) + { + data->~T(); + } +} + +template +constexpr void destruct_n(T* data, isize_t n) +{ + if constexpr (!trivially_destructible) + { + for (isize_t i = 0; i < n; ++i) + { + destruct(data + i); + } + } +} + +template +constexpr void relocate_uninit_n(T* to, T* from, isize_t n) +{ + if constexpr (trivially_copyable) + { + memcpy(to, from, size_of * n); + } + else + { + static_assert(move_constructible); + for (isize_t i = 0; i < n; ++i) + { + // NOLINTNEXTLINE(*-pointer-arithmetic) + construct_at(to + i, ASL_MOVE(from[i])); + } + } + + destruct_n(from, n); +} + } // namespace asl -- cgit