using System.Runtime.InteropServices;
using Brutal.Attributes;
namespace Brutal.Pointers.Extensions;
///
/// Extensions for Span and ReadOnlySpan as pointers
///
public static class PointerExtensions
{
///
/// Return the underlying pointer of span. Note this may be unsafe if the span refers to memory not allocated on the
/// native memory, as they may be relocated at any time due to generational Garbage Collections. Please review usage
/// to ensure only fixed native memory pointers are returned.
///
/// Span of native memory
/// Unsafe pointer to block of memory
public static unsafe T* AsPointer(this Span span)
where T : unmanaged
{
return (T*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span));
}
///
/// Return the underlying pointer of span. Note this may be unsafe if the span refers to memory not allocated on the
/// native memory, as they may be relocated at any time due to generational Garbage Collections. Please review usage
/// to ensure only fixed native memory pointers are returned.
///
/// ReadOnlySpan of native memory
/// Unsafe pointer to block of memory
public static unsafe T* AsPointer(this ReadOnlySpan span)
where T : unmanaged
{
return (T*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span));
}
///
/// Return the underlying pointer of span. Note this may be unsafe if the span refers to memory not allocated on the
/// native memory, as they may be relocated at any time due to generational Garbage Collections. Please review usage
/// to ensure only fixed native memory pointers are returned.
///
/// Span of native memory
/// Unsafe pointer to block of memory
public static unsafe Ptr AsPtr(this Span span)
where T : unmanaged
{
return (T*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span));
}
///
/// Return the underlying pointer of span. Note this may be unsafe if the span refers to memory not allocated on the
/// native memory, as they may be relocated at any time due to generational Garbage Collections. Please review usage
/// to ensure only fixed native memory pointers are returned.
///
/// ReadOnlySpan of native memory
/// Unsafe pointer to block of memory
public static unsafe Ptr AsPtr([Fixed] this ReadOnlySpan span)
where T : unmanaged
{
return (T*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span));
}
}