using System;
namespace Ryujinx.Common.Memory
{
///
/// A struct that can represent both a Span and Array.
/// This is useful to keep the Array representation when possible to avoid copies.
///
/// Element Type
public readonly ref struct SpanOrArray where T : unmanaged
{
public readonly T[] Array;
public readonly ReadOnlySpan Span;
///
/// Create a new SpanOrArray from an array.
///
/// Array to store
public SpanOrArray(T[] array)
{
Array = array;
Span = ReadOnlySpan.Empty;
}
///
/// Create a new SpanOrArray from a readonly span.
///
/// Span to store
public SpanOrArray(ReadOnlySpan span)
{
Array = null;
Span = span;
}
///
/// Return the contained array, or convert the span if necessary.
///
/// An array containing the data
public T[] ToArray()
{
return Array ?? Span.ToArray();
}
///
/// Return a ReadOnlySpan from either the array or ReadOnlySpan.
///
/// A ReadOnlySpan containing the data
public ReadOnlySpan AsSpan()
{
return Array ?? Span;
}
///
/// Cast an array to a SpanOrArray.
///
/// Source array
public static implicit operator SpanOrArray(T[] array)
{
return new SpanOrArray(array);
}
///
/// Cast a ReadOnlySpan to a SpanOrArray.
///
/// Source ReadOnlySpan
public static implicit operator SpanOrArray(ReadOnlySpan span)
{
return new SpanOrArray(span);
}
///
/// Cast a Span to a SpanOrArray.
///
/// Source Span
public static implicit operator SpanOrArray(Span span)
{
return new SpanOrArray(span);
}
///
/// Cast a SpanOrArray to a ReadOnlySpan
///
/// Source SpanOrArray
public static implicit operator ReadOnlySpan(SpanOrArray spanOrArray)
{
return spanOrArray.AsSpan();
}
}
}