using Brutal.Attributes;
using Brutal.Pointers.Extensions;
namespace Brutal.Pointers;
///
/// A wrapper for a typed pointer.
///
public readonly unsafe struct Ptr(TValueType* pointer) : INullable
where TValueType : unmanaged
{
///
/// The raw pointer of type .
///
public TValueType* Pointer => pointer;
///
/// A reference to the first value at the pointer address.
///
public ref TValueType Value => ref *Pointer;
///
/// Returns a new , offset by the given byte count.
///
///
///
public Ptr Offset(ElementCount count)
{
return new Ptr(Pointer + count);
}
///
/// Converts the pointer to a of the given length.
///
[return: Fixed]
public Span AsSpan(ElementCount length)
{
return new Span(Pointer, length);
}
///
/// Converts the pointer to an untyped .
///
public Ptr AsPtr()
{
return new Ptr(Pointer);
}
///
/// Cast this pointer to a different type.
///
///
///
public Ptr Cast()
where TCastType : unmanaged
{
return new Ptr((TCastType*)Pointer);
}
///
public bool IsNull()
{
return Pointer == null;
}
///
/// Gets a reference to the value at the given index.
///
public ref TValueType this[int index] => ref Pointer[index];
///
/// Implicit conversion from a to an untyped .
///
public static implicit operator Ptr(Ptr ptr)
{
return ptr.AsPtr();
}
///
/// Implicit conversion from a typed pointer to a .
///
public static implicit operator Ptr(TValueType* pointer)
{
return new Ptr(pointer);
}
///
/// Implicit conversion from a to *.
///
///
///
public static implicit operator TValueType*(Ptr ptr)
{
return ptr.Pointer;
}
///
/// Implicit conversion from a to void pointer.
///
public static implicit operator void*(Ptr ptr)
{
return ptr.Pointer;
}
public static implicit operator Ptr([Fixed] ReadOnlySpan span)
{
return span.AsPtr();
}
public static implicit operator Ptr([Fixed] Span span)
{
return span.AsPtr();
}
///
/// Explicit cast from nint to Ptr.
///
public static explicit operator Ptr(nint ptr)
{
return new Ptr((TValueType*)ptr);
}
///
/// Explicit cast to nint.
///
public static explicit operator nint(Ptr ptr)
{
return (nint)ptr.Pointer;
}
}