using Brutal.Attributes;
using Brutal.Memory;
using Brutal.Pointers;
using Brutal.Pointers.Extensions;
namespace Brutal.Collections;
///
/// An untyped span to unsafe memory, however with a stride.
///
public readonly ref struct NativeStrideSpan(Ptr inData, ElementCount inLength, ByteSize inStride) : ISpanLike
{
///
/// The pointer to the first element of the span.
///
public Ptr Ptr => inData;
///
/// The length of the span.
///
public ElementCount Length => inLength;
///
/// The stride of each element.
///
public ByteSize Stride => inStride;
public bool IsEmpty => Length == 0;
///
/// The total size of the span in bytes.
///
public ByteSize ByteSize => Length * Stride;
///
/// Slice the span into a new raw span.
///
public NativeStrideSpan Slice(int start, int length)
{
return new NativeStrideSpan(Ptr.Offset(start * Stride), length, Stride);
}
///
/// Create a new raw span with a different stride.
///
///
public NativeStrideSpan WithStride(ByteSize stride)
{
if (stride <= 0)
throw new ArgumentOutOfRangeException(nameof(stride));
var prevSize = ByteSize;
return new NativeStrideSpan(Ptr, prevSize.ToElementCount(stride), stride);
}
///
public bool IsNull() => Ptr.IsNull();
///
/// Create a new raw span from a managed span.
///
public static unsafe NativeStrideSpan FromSpan([Fixed] ReadOnlySpan span)
where T : unmanaged
{
return new NativeStrideSpan(span.AsPointer(), span.Length, ByteSize.Of());
}
///
/// Create a new raw span from a managed span.
///
public static unsafe NativeStrideSpan FromSpan([Fixed] Span span)
where T : unmanaged
{
return new NativeStrideSpan(span.AsPointer(), span.Length, ByteSize.Of());
}
///
/// Slice the span into a new raw span.
///
public NativeStrideSpan this[int start, int end] => Slice(start, end - start);
[return: Fixed]
public unsafe Span AsSpan()
where T : unmanaged
{
if (typeof(T) == typeof(byte))
return new Span(Ptr.Cast(), ElementCount.Of(Length * Stride));
var size = ByteSize.Of();
if (size != Stride)
throw new InvalidOperationException("Stride must be equal to the size of the type, or type must be byte.");
return new Span(Ptr.Cast(), Length);
}
public NativeStrideSpan this[Range start] => Slice(start.Start.Value, start.End.Value - start.Start.Value);
}