Create a RefCounted type and use it for Thread.

This should prevent me from actually creating 2 shared ptrs of
a single kernel object with their separate ref counts.
This commit is contained in:
Drew Galbraith 2023-06-06 19:05:03 -07:00
parent d9b17d96d7
commit 2e1357255c
8 changed files with 146 additions and 22 deletions

41
zion/lib/ref_counted.h Normal file
View file

@ -0,0 +1,41 @@
#pragma once
#include <stdint.h>
#include "debug/debug.h"
template <typename T>
class RefCounted {
public:
RefCounted() {}
~RefCounted() { dbgln("RefCounted object destroyed"); }
void Adopt() {
if (ref_count_ != -1) {
panic("Adopting owned ptr");
} else {
ref_count_ = 1;
}
}
void Acquire() {
if (ref_count_ == -1) {
panic("Acquiring unowned ptr");
}
ref_count_++;
}
bool Release() {
if (ref_count_ == -1 || ref_count_ == 0) {
panic("Releasing unowned ptr");
}
return (--ref_count_) == 0;
}
private:
// FIXME: This should be an atomic type.
uint64_t ref_count_ = -1;
// Disallow copy and move.
RefCounted(RefCounted&) = delete;
RefCounted(RefCounted&&) = delete;
RefCounted& operator=(RefCounted&) = delete;
RefCounted& operator=(RefCounted&&) = delete;
};

76
zion/lib/ref_ptr.h Normal file
View file

@ -0,0 +1,76 @@
#pragma once
template <typename T>
class RefPtr;
template <typename T>
RefPtr<T> AdoptPtr(T* ptr);
template <typename T>
class RefPtr {
public:
RefPtr() : ptr_(nullptr) {}
RefPtr(decltype(nullptr)) : ptr_(nullptr) {}
RefPtr(const RefPtr& other) : ptr_(other.ptr_) {
if (ptr_) {
ptr_->Acquire();
}
}
RefPtr& operator=(const RefPtr& other) {
T* old = ptr_;
ptr_ = other.ptr_;
if (ptr_) {
ptr_->Acquire();
}
if (old && old->Release()) {
delete old;
}
return *this;
}
RefPtr(RefPtr&& other) : ptr_(other.ptr_) { other.ptr_ = nullptr; }
RefPtr& operator=(RefPtr&& other) {
// Swap
T* ptr = ptr_;
ptr_ = other.ptr_;
other.ptr_ = ptr;
return *this;
}
T* get() const { return ptr_; };
T& operator*() const { return *ptr_; }
T* operator->() const { return ptr_; }
operator bool() const { return ptr_ != nullptr; }
bool operator==(decltype(nullptr)) const { return (ptr_ == nullptr); }
bool operator!=(decltype(nullptr)) const { return (ptr_ != nullptr); }
bool operator==(const RefPtr<T>& other) const { return (ptr_ == other.ptr_); }
bool operator!=(const RefPtr<T>& other) const { return (ptr_ != other.ptr_); }
private:
T* ptr_;
friend RefPtr<T> AdoptPtr<T>(T* ptr);
RefPtr(T* ptr) : ptr_(ptr) { ptr->Adopt(); }
};
template <typename T>
class MakeRefCountedFriend final {
public:
template <typename... Args>
static RefPtr<T> Make(Args&&... args) {
return AdoptPtr(new T(args...));
}
};
template <typename T, typename... Args>
RefPtr<T> MakeRefCounted(Args&&... args) {
return MakeRefCountedFriend<T>::Make(args...);
}
template <typename T>
RefPtr<T> AdoptPtr(T* ptr) {
return RefPtr(ptr);
}