Skip to content

Commit d45e129

Browse files
committed
More efficient RgbConverter.Convert
1 parent d57e346 commit d45e129

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

AssetRipper.TextureDecoder/Rgb/RgbConverter.cs

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -517,9 +517,34 @@ public static void Convert<TSourceColor, TSourceChannel, TDestinationColor, TDes
517517
where TDestinationChannel : unmanaged
518518
where TDestinationColor : unmanaged, IColor<TDestinationChannel>
519519
{
520-
for (int i = 0; i < sourceSpan.Length; i++)
520+
if (sourceSpan.Length is 0)
521521
{
522-
destinationSpan[i] = sourceSpan[i].Convert<TSourceColor, TSourceChannel, TDestinationColor, TDestinationChannel>();
522+
// Do nothing if the source span is empty
523+
}
524+
else if (destinationSpan.Length < sourceSpan.Length)
525+
{
526+
ThrowDestinationSpanNotLargeEnough();
527+
}
528+
else if (typeof(TSourceColor) != typeof(TDestinationColor))
529+
{
530+
for (int i = 0; i < sourceSpan.Length; i++)
531+
{
532+
destinationSpan[i] = sourceSpan[i].Convert<TSourceColor, TSourceChannel, TDestinationColor, TDestinationChannel>();
533+
}
534+
}
535+
else if (Unsafe.AreSame(in sourceSpan[0], ref Unsafe.As<TDestinationColor, TSourceColor>(ref destinationSpan[0])))
536+
{
537+
// Do nothing because the source and destination point to the same memory
538+
}
539+
else
540+
{
541+
// Note: This assumes that the source and destination will never overlap.
542+
sourceSpan.CopyTo(MemoryMarshal.Cast<TDestinationColor, TSourceColor>(destinationSpan));
543+
}
544+
545+
static void ThrowDestinationSpanNotLargeEnough()
546+
{
547+
throw new ArgumentException("Destination span is not large enough to hold the converted data.", nameof(destinationSpan));
523548
}
524549
}
525550

0 commit comments

Comments
 (0)