using CommunityToolkit.HighPerformance;
namespace Brutal.Numerics;
///
/// Packing utilities for converting between matrix types
///
public static class MatrixPack
{
///
/// Convert a span of matrices of one type to another using a per-element delegate converter function
///
/// Source span of matrices
/// Destination span of matrices
/// Delegate for converting between source and destination elements
/// Source element type
/// Destination element type
/// Source matrix type
/// Destination matrix type
///
/// Source and destination matrix types have different element counts, or are different
/// length spans
///
public static void Pack(
ReadOnlySpan source,
Span destination,
Func elementConverter
)
where TSourceMatrix : unmanaged, IMatrix
where TDestinationMatrix : unmanaged, IMatrix
where TSourceType : unmanaged
where TDestinationElement : unmanaged
{
if (destination.Length < source.Length)
throw new ArgumentException("Destination span is not long enough to hold the converted matrices");
if (
TSourceMatrix.RowCount != TDestinationMatrix.RowCount
|| TSourceMatrix.ColumnCount != TDestinationMatrix.ColumnCount
)
throw new ArgumentException("Source and destination matrix 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 matrix (cast as a span of elements) to a destination matrix (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 matrix
/// Destination matrix, created from a span of elements
/// Per-element conversion delegate
/// Element type of input span
/// Element type of output matrix
/// Type of input matrix
/// Type of output matrix
public static void Pack(
in TSourceMatrix source,
out TDestinationMatrix destination,
Func elementConverter
)
where TSourceType : unmanaged
where TDestinationType : unmanaged
where TSourceMatrix : unmanaged, IMatrix
where TDestinationMatrix : unmanaged, IMatrix
{
if (
TSourceMatrix.RowCount != TDestinationMatrix.RowCount
|| TSourceMatrix.ColumnCount != TDestinationMatrix.ColumnCount
)
throw new ArgumentException("Source and destination matrix types have different element counts");
var src = source.AsSpan();
Span dst =
stackalloc TDestinationType[TDestinationMatrix.RowCount * TDestinationMatrix.ColumnCount];
for (var i = 0; i < src.Length; i++)
dst[i] = elementConverter(src[i]);
destination = TDestinationMatrix.Create(dst);
}
}