feat(handle): add handle functions

This commit is contained in:
fallenoak 2023-01-01 20:59:41 -06:00 committed by GitHub
parent 57a1dae84c
commit 90246804d0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 90 additions and 0 deletions

36
common/Handle.cpp Normal file
View file

@ -0,0 +1,36 @@
#include "common/Handle.hpp"
#include "common/handle/CHandleObject.hpp"
#include <storm/Error.hpp>
HOBJECT HandleCreate(CHandleObject* ptr) {
STORM_ASSERT(ptr);
STORM_VALIDATE(ptr, ERROR_INVALID_PARAMETER, nullptr);
ptr->m_refcount++;
return reinterpret_cast<HOBJECT>(ptr);
}
void HandleClose(HOBJECT handle) {
CHandleObject* ptr = HandleDereference(handle);
STORM_ASSERT(ptr->m_refcount > 0);
ptr->m_refcount--;
if (ptr->m_refcount == 0) {
delete ptr;
}
}
CHandleObject* HandleDereference(HOBJECT handle) {
return reinterpret_cast<CHandleObject*>(handle);
}
HOBJECT HandleDuplicate(HOBJECT handle) {
if (!handle) {
return nullptr;
}
HandleDereference(handle)->m_refcount++;
return handle;
}

24
common/Handle.hpp Normal file
View file

@ -0,0 +1,24 @@
#ifndef COMMON_HANDLE_HPP
#define COMMON_HANDLE_HPP
#include "common/handle/CHandleObject.hpp"
#include <cstddef>
#include <cstdint>
typedef void* HANDLE;
#define DECLARE_HANDLE(name) \
struct name##__; \
typedef struct name##__* name
DECLARE_HANDLE(HOBJECT);
HOBJECT HandleCreate(CHandleObject* ptr);
void HandleClose(HOBJECT handle);
CHandleObject* HandleDereference(HOBJECT handle);
HOBJECT HandleDuplicate(HOBJECT handle);
#endif

View file

@ -0,0 +1,15 @@
#ifndef COMMON_HANDLE_C_HANDLE_OBJECT_HPP
#define COMMON_HANDLE_C_HANDLE_OBJECT_HPP
#include <cstdint>
class CHandleObject {
public:
// Member variables
int32_t m_refcount = 0;
// Virtual member functions
virtual ~CHandleObject() = default;
};
#endif

15
test/Handle.cpp Normal file
View file

@ -0,0 +1,15 @@
#include "common/Handle.hpp"
#include "test/Test.hpp"
class TestHandleObject : public CHandleObject {};
TEST_CASE("HandleCreate", "[handle]") {
SECTION("returns handle for subclass of CHandleObject") {
auto testObject = new TestHandleObject();
auto handle = HandleCreate(testObject);
CHECK(handle);
HandleClose(handle);
}
}