using System;
using System.Runtime.CompilerServices;
namespace ComputeSharp.Graphics.Helpers
{
///
/// A with some helper methods to copy data between memory areas.
///
internal static class MemoryHelper
{
///
/// Copies the content of a to the area pointed by an input pointer.
///
/// The type of values in the input .
/// The source to read.
/// The pointer for the destination memory area.
/// The destination offset to start writing data to.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void Copy(ReadOnlySpan source, void* destination, int destinationOffset)
where T : unmanaged
{
source.CopyTo(new Span((T*)destination + destinationOffset, source.Length));
}
///
/// Copies a memory area pointed by a pointer to a target .
///
/// The type of values to read.
/// The pointer that indicates the memory area to read from.
/// The source offset to start reading data from.
/// The destination to write.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void Copy(void* source, int sourceOffset, Span destination)
where T : unmanaged
{
new Span((T*)source + sourceOffset, destination.Length).CopyTo(destination);
}
///
/// Copies the content of a to the 2D area pointed by an input pointer.
///
/// The type of values to read.
/// The destination to read from.
/// The pointer that indicates the 2D memory area to write to.
/// The width of the 2D memory area to read.
/// The height of the 2D memory area to read.
/// The width of the memory area in bytes.
/// The pitch (padded width) of the memory area in bytes.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void Copy(
ReadOnlySpan source,
void* destination,
int width,
int height,
ulong widthInBytes,
ulong pitchInBytes)
where T : unmanaged
{
if (widthInBytes == pitchInBytes)
{
source.CopyTo(new Span(destination, width * height));
}
else
{
for (int i = 0; i < height; i++)
{
ReadOnlySpan sourceRow = source.Slice(i * width, width);
Span destinationRow = new((byte*)destination + (uint)i * pitchInBytes, width);
sourceRow.CopyTo(destinationRow);
}
}
}
///
/// Copies a 2D memory area pointed by a pointer value to a target .
///
/// The type of values to read.
/// The pointer that indicates the memory area to read from.
/// The width of the 2D memory area to read.
/// The height of the 2D memory area to read.
/// The width of the memory area in bytes.
/// The pitch (padded width) of the memory area in bytes.
/// The destination to write.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void Copy(
void* source,
int width,
int height,
ulong widthInBytes,
ulong pitchInBytes,
Span destination)
where T : unmanaged
{
if (widthInBytes == pitchInBytes)
{
new Span(source, width * height).CopyTo(destination);
}
else
{
for (int i = 0; i < height; i++)
{
ReadOnlySpan sourceRow = new((byte*)source + (uint)i * pitchInBytes, width);
Span destinationRow = destination.Slice(i * width, width);
sourceRow.CopyTo(destinationRow);
}
}
}
}
}