From 79092cdda08b5b89dd874ffb7de161efcd65af16 Mon Sep 17 00:00:00 2001 From: Techjar Date: Wed, 18 Dec 2019 23:36:56 -0500 Subject: [PATCH] Common/BitUtils: Implement BitCast(To|From)Array --- Source/Core/Common/BitUtils.h | 48 +++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/Source/Core/Common/BitUtils.h b/Source/Core/Common/BitUtils.h index 8b64a92508..79c1a7799e 100644 --- a/Source/Core/Common/BitUtils.h +++ b/Source/Core/Common/BitUtils.h @@ -4,6 +4,7 @@ #pragma once +#include #include #include #include @@ -240,6 +241,53 @@ inline auto BitCastPtr(PtrType* ptr) noexcept -> BitCastPtrType return BitCastPtrType{ptr}; } +// Similar to BitCastPtr, but specifically for aliasing structs to arrays. +template > +inline auto BitCastToArray(const T& obj) noexcept -> Container +{ + static_assert(sizeof(T) % sizeof(ArrayType) == 0, + "Size of array type must be a factor of size of source type."); + static_assert(std::is_trivially_copyable(), + "BitCastToArray source type must be trivially copyable."); + static_assert(std::is_trivially_copyable(), + "BitCastToArray array type must be trivially copyable."); + + Container result; + std::memcpy(result.data(), &obj, sizeof(T)); + return result; +} + +template > +inline void BitCastFromArray(const Container& array, T& obj) noexcept +{ + static_assert(sizeof(T) % sizeof(ArrayType) == 0, + "Size of array type must be a factor of size of destination type."); + static_assert(std::is_trivially_copyable(), + "BitCastFromArray array type must be trivially copyable."); + static_assert(std::is_trivially_copyable(), + "BitCastFromArray destination type must be trivially copyable."); + + std::memcpy(&obj, array.data(), sizeof(T)); +} + +template > +inline auto BitCastFromArray(const Container& array) noexcept -> T +{ + static_assert(sizeof(T) % sizeof(ArrayType) == 0, + "Size of array type must be a factor of size of destination type."); + static_assert(std::is_trivially_copyable(), + "BitCastFromArray array type must be trivially copyable."); + static_assert(std::is_trivially_copyable(), + "BitCastFromArray destination type must be trivially copyable."); + + T obj; + std::memcpy(&obj, array.data(), sizeof(T)); + return obj; +} + template void SetBit(T& value, size_t bit_number, bool bit_value) {