From d9c11bd34a0487668f469067af06d4ee415e6416 Mon Sep 17 00:00:00 2001 From: David Hall Date: Tue, 21 Jan 2025 08:32:51 -0700 Subject: [PATCH] Added SafeAllocatedMemoryHandleBase.CopyTo methods to copy memory segments to pointers and other SafeAllocatedMemoryHandleBase instances --- Core/InteropServices/SafeMemoryHandle.cs | 37 ++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/Core/InteropServices/SafeMemoryHandle.cs b/Core/InteropServices/SafeMemoryHandle.cs index 47c185751..68f6efc47 100644 --- a/Core/InteropServices/SafeMemoryHandle.cs +++ b/Core/InteropServices/SafeMemoryHandle.cs @@ -371,6 +371,43 @@ public virtual int CompareTo(IReadOnlyList? other) return ret; } + /// Copies memory from this allocation to an allocated memory pointer. + /// A pointer to allocated memory that must be at least bytes. + /// The number of bytes to copy. + public void CopyTo(IntPtr dest, SizeT length) => CallLocked(p => p.CopyTo(dest, length)); + + /// Copies memory from this allocation to an allocated memory handle. + /// A safe handle to allocated memory. + /// The offset within at which to start copying. + /// dest + /// destOffset + public void CopyTo(SafeAllocatedMemoryHandleBase dest, SizeT destOffset = default) + { + if (dest is null) throw new ArgumentNullException(nameof(dest)); + if (dest.Size < destOffset + Size) throw new ArgumentOutOfRangeException(nameof(destOffset), "The destination buffer is not large enough."); + CallLocked(p => p.CopyTo(dest.handle, Size)); + } + + /// Copies memory from this allocation to an allocated memory pointer. + /// The starting offset within this allocation at which to start copying. + /// A pointer to allocated memory that must be at least bytes. + /// The number of bytes to copy. + public void CopyTo(SizeT start, IntPtr dest, SizeT length) => CallLocked(p => p.CopyTo(start, dest, length)); + + /// Copies memory from this allocation to an allocated memory handle. + /// The starting offset within this allocation at which to start copying. + /// The number of bytes to copy. + /// A safe handle to allocated memory. + /// The offset within at which to start copying. + /// dest + /// destOffset - The destination buffer is not large enough. + public void CopyTo(SizeT start, SizeT length, SafeAllocatedMemoryHandleBase dest, SizeT destOffset = default) + { + if (dest is null) throw new ArgumentNullException(nameof(dest)); + if (dest.Size < destOffset + length - start) throw new ArgumentOutOfRangeException(nameof(destOffset), "The destination buffer is not large enough."); + CallLocked(p => p.CopyTo(start, dest.handle.Offset(destOffset), length)); + } + /// public bool Equals(SafeAllocatedMemoryHandleBase? other) => CompareTo(other) == 0;