LibCore: Add Stream::Handle
This essentially wraps a `NonnullOwnPtr` or a reference, allowing us to either have a stream own a dependent stream that it uses or to just hold a reference if a stream is already owned by somebody else and we just want to use it temporarily.
This commit is contained in:
parent
6c83bd8fd4
commit
8b5df161af
Notes:
sideshowbarker
2024-07-17 03:21:43 +09:00
Author: https://github.com/timschumi Commit: https://github.com/SerenityOS/serenity/commit/8b5df161af Pull-request: https://github.com/SerenityOS/serenity/pull/16355 Reviewed-by: https://github.com/linusg Reviewed-by: https://github.com/sin-ack ✅
1 changed files with 42 additions and 0 deletions
|
@ -24,6 +24,48 @@
|
|||
|
||||
namespace Core::Stream {
|
||||
|
||||
template<DerivedFrom<Core::Stream::Stream> T>
|
||||
class Handle {
|
||||
public:
|
||||
template<DerivedFrom<T> U>
|
||||
Handle(NonnullOwnPtr<U> handle)
|
||||
: m_handle(adopt_own<T>(*handle.leak_ptr()))
|
||||
{
|
||||
}
|
||||
|
||||
// This is made `explicit` to not accidentally create a non-owning Handle,
|
||||
// which may not always be intended.
|
||||
explicit Handle(T& handle)
|
||||
: m_handle(&handle)
|
||||
{
|
||||
}
|
||||
|
||||
T* ptr()
|
||||
{
|
||||
if (m_handle.template has<T*>())
|
||||
return m_handle.template get<T*>();
|
||||
else
|
||||
return m_handle.template get<NonnullOwnPtr<T>>();
|
||||
}
|
||||
|
||||
T const* ptr() const
|
||||
{
|
||||
if (m_handle.template has<T*>())
|
||||
return m_handle.template get<T*>();
|
||||
else
|
||||
return m_handle.template get<NonnullOwnPtr<T>>();
|
||||
}
|
||||
|
||||
T* operator->() { return ptr(); }
|
||||
T const* operator->() const { return ptr(); }
|
||||
|
||||
T& operator*() { return *ptr(); }
|
||||
T const& operator*() const { return *ptr(); }
|
||||
|
||||
private:
|
||||
Variant<NonnullOwnPtr<T>, T*> m_handle;
|
||||
};
|
||||
|
||||
/// The base, abstract class for stream operations. This class defines the
|
||||
/// operations one can perform on every stream in LibCore.
|
||||
class Stream {
|
||||
|
|
Loading…
Add table
Reference in a new issue