using Brutal.Attributes;
using Brutal.Pointers;
using Brutal.Pointers.Extensions;
namespace Brutal.Memory;
///
/// A variant of Ptr that owns the memory and frees it automatically when disposed or finalized
///
/// The struct type we want to create unmanaged memory pointing to
public class PtrOwner : IDisposable, INullable
where TValueType : unmanaged
{
///
/// The owned pointer.
///
public Ptr Ptr { get; private set; }
///
/// Get the value of the pointer as a reference
///
public ref TValueType Value => ref Ptr.Value;
public PtrOwner(TValueType value)
{
Ptr = Mem.AllocAndCopy(value);
}
public PtrOwner(Ptr ptr)
{
Ptr = ptr;
}
///
/// Dispose resources, freeing the memory and preventing further use.
///
///
/// ONLY call this if you are sure you don't need the PtrOwner anymore.
///
public void Dispose()
{
Mem.Free(Ptr);
Ptr = null;
GC.SuppressFinalize(this);
}
///
/// A finalizer that frees the memory, in case the object was not disposed.
///
~PtrOwner()
{
Mem.Free(Ptr);
}
///
public bool IsNull()
{
return Ptr.IsNull();
}
///
/// Returns a new that points to the same memory as this one, but with an offset in elements of .
///
public Ptr Offset(int count)
{
return Ptr.Offset(count);
}
///
/// Convert the pointer to a span of type TValueType with the given length.
///
[return: Fixed]
public Span AsSpan(int length)
{
return Ptr.AsSpan(length);
}
///
/// Gets a reference to the element at the specified index.
///
public ref TValueType this[int index] => ref Ptr[index];
///
/// Swap the pointer with another one.
///
///
///
public Ptr Swap(Ptr newPointer)
{
var oldPointer = Ptr;
Ptr = newPointer;
return oldPointer;
}
///
/// Release the pointer and return it to the caller.
///
///
/// If you don't need the PtrOwner anymore, call Dispose() instead.
///
public Ptr Release()
{
return Swap(null);
}
///
/// Frees any existing pointer and resets it to the given value.
///
///
/// This PtrOwner will now own the memory of the given value.
///
public void Reset(Ptr newValue = default)
{
Release();
Swap(newValue);
}
///
/// Implicit cast to .
///
public static implicit operator Ptr(PtrOwner? inPtrOwner)
{
return inPtrOwner?.Ptr ?? null;
}
///
/// Implicit cast to *.
///
public static unsafe implicit operator TValueType*(PtrOwner? inPtrOwner)
{
return inPtrOwner?.Ptr ?? null;
}
///
/// Explicit cast to nint.
///
public static explicit operator nint(PtrOwner ptr)
{
return (nint)ptr.Ptr;
}
}