using CommunityToolkit.HighPerformance;
namespace Brutal.Numerics;
///
/// Packing utilities for converting between vector types
///
public static class VectorPack
{
///
/// Convert a span of vectors of one type to another using a per-element delegate converter function
///
/// Source span of vectors
/// Destination span of vectors
/// Delegate for converting between source and destination elements
/// Source element type
/// Destination element type
/// Source vector type
/// Destination vector type
///
/// Source and destination vector types have different element counts, or are different
/// length spans
///
public static void Pack(
ReadOnlySpan source,
Span destination,
Func elementConverter
)
where TSourceVector : unmanaged, IVector
where TDestinationVector : unmanaged, IVector
where TSourceType : unmanaged
where TDestinationElement : unmanaged
{
if (destination.Length < source.Length)
throw new ArgumentException("Destination span is not long enough to hold the converted vectors");
if (TSourceVector.ComponentCount != TDestinationVector.ComponentCount)
throw new ArgumentException("Source and destination vector types have different element counts");
var src = source.Cast();
var dst = destination.Cast();
for (var i = 0; i < src.Length; i++)
dst[i] = elementConverter(src[i]);
}
///
/// Convert a source vector (cast as a span of elements) to a destination vector (created from a span of elements)
/// using a per-element delegate converter function
/// This slightly quirky signature is a workaround to avoid generics hell where you have to explicitly write each type
///
/// Source vector
/// Destination vector, created from a span of elements
/// Per-element conversion delegate
/// Element type of input span
/// Element type of output vector
/// Type of input vector
/// Type of output vector
public static void Pack(
in TSourceVector source,
out TDestinationVector destination,
Func elementConverter
)
where TSourceType : unmanaged
where TDestinationType : unmanaged
where TSourceVector : unmanaged, IVector
where TDestinationVector : unmanaged, IVector
{
if (TDestinationVector.ComponentCount < TSourceVector.ComponentCount)
throw new ArgumentException("Destination vector type has fewer elements than source vector type");
var src = source.AsSpan();
Span dst = stackalloc TDestinationType[TDestinationVector.ComponentCount];
for (var i = 0; i < src.Length; i++)
dst[i] = elementConverter(src[i]);
destination = TDestinationVector.Create(dst);
}
}