From 6b0154b183f9539097f13af9b5da78ca24da6df2 Mon Sep 17 00:00:00 2001 From: Lee Bousfield Date: Tue, 4 Mar 2025 15:26:24 -0600 Subject: [PATCH] memory: Add shared pointer reinterpretPointerCast function (#47) * memory: Add force reinterpret constructor to shared pointer * memory: Change constructor to reinterpretPointerCast function * memory: Add reinterpretPointerCast test --- include/hyprutils/memory/SharedPtr.hpp | 9 +++++++-- tests/memory.cpp | 12 +++++++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/include/hyprutils/memory/SharedPtr.hpp b/include/hyprutils/memory/SharedPtr.hpp index d2c5995..f2003a2 100644 --- a/include/hyprutils/memory/SharedPtr.hpp +++ b/include/hyprutils/memory/SharedPtr.hpp @@ -144,7 +144,7 @@ namespace Hyprutils { Impl_::impl_base* impl_ = nullptr; private: - /* + /* no-op if there is no impl_ may delete the stored object if ref == 0 may delete and reset impl_ if ref == 0 and weak == 0 @@ -167,7 +167,7 @@ namespace Hyprutils { impl_->inc(); } - /* destroy the pointed-to object + /* destroy the pointed-to object if able, will also destroy impl */ void destroyImpl() { // destroy the impl contents @@ -185,6 +185,11 @@ namespace Hyprutils { static CSharedPointer makeShared(Args&&... args) { return CSharedPointer(new U(std::forward(args)...)); } + + template + CSharedPointer reinterpretPointerCast(const CSharedPointer& ref) { + return CSharedPointer(ref.impl_); + } } } diff --git a/tests/memory.cpp b/tests/memory.cpp index 2c43303..118e8c8 100644 --- a/tests/memory.cpp +++ b/tests/memory.cpp @@ -11,7 +11,7 @@ using namespace Hyprutils::Memory; int main(int argc, char** argv, char** envp) { SP intPtr = makeShared(10); - SP intPtr2 = makeShared(1337); + SP intPtr2 = makeShared(-1337); UP intUnique = makeUnique(420); int ret = 0; @@ -52,5 +52,15 @@ int main(int argc, char** argv, char** envp) { EXPECT(weak.expired(), true); EXPECT(weakUnique.expired(), true); + auto intPtr2AsUint = reinterpretPointerCast(intPtr2); + EXPECT(intPtr2.strongRef(), 4); + EXPECT(intPtr2AsUint.strongRef(), 4); + + EXPECT(*intPtr2AsUint > 0, true); + EXPECT(*intPtr2AsUint, (unsigned int)(int)-1337); + *intPtr2AsUint = 10; + EXPECT(*intPtr2AsUint, 10); + EXPECT(*intPtr2, 10); + return ret; } \ No newline at end of file