Skip to content

Commit 77f203f

Browse files
committed
Added validation for Pin methods
1 parent caca3b1 commit 77f203f

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

Microsoft.Toolkit.HighPerformance/Buffers/Internals/ArrayMemoryManager{TFrom,TTo}.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,11 @@ public override Span<TTo> GetSpan()
6868
/// <inheritdoc/>
6969
public override unsafe MemoryHandle Pin(int elementIndex = 0)
7070
{
71+
if ((uint)elementIndex >= (uint)(this.length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>()))
72+
{
73+
ThrowArgumentExceptionForInvalidIndex();
74+
}
75+
7176
int
7277
bytePrefix = this.offset + Unsafe.SizeOf<TFrom>(),
7378
byteSuffix = elementIndex * Unsafe.SizeOf<TTo>(),
@@ -99,5 +104,13 @@ public MemoryManager<T> Cast<T>(int offset, int length)
99104
{
100105
return new ArrayMemoryManager<TFrom, T>(this.array, this.offset + offset, length);
101106
}
107+
108+
/// <summary>
109+
/// Throws an <see cref="ArgumentOutOfRangeException"/> when the target index for <see cref="Pin"/> is invalid.
110+
/// </summary>
111+
private static void ThrowArgumentExceptionForInvalidIndex()
112+
{
113+
throw new ArgumentOutOfRangeException("elementIndex", "The input index is not in the valid range");
114+
}
102115
}
103116
}

Microsoft.Toolkit.HighPerformance/Buffers/Internals/ProxyMemoryManager{TFrom,TTo}.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,11 @@ public override Span<TTo> GetSpan()
5858
/// <inheritdoc/>
5959
public override MemoryHandle Pin(int elementIndex = 0)
6060
{
61+
if ((uint)elementIndex >= (uint)(this.length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>()))
62+
{
63+
ThrowArgumentExceptionForInvalidIndex();
64+
}
65+
6166
int byteOffset = elementIndex * Unsafe.SizeOf<TTo>();
6267

6368
#if NETSTANDARD1_4
@@ -95,6 +100,14 @@ public MemoryManager<T> Cast<T>(int offset, int length)
95100
return new ProxyMemoryManager<TFrom, T>(this.memoryManager, this.offset + offset, length);
96101
}
97102

103+
/// <summary>
104+
/// Throws an <see cref="ArgumentOutOfRangeException"/> when the target index for <see cref="Pin"/> is invalid.
105+
/// </summary>
106+
private static void ThrowArgumentExceptionForInvalidIndex()
107+
{
108+
throw new ArgumentOutOfRangeException("elementIndex", "The input index is not in the valid range");
109+
}
110+
98111
/// <summary>
99112
/// Throws an <see cref="ArgumentOutOfRangeException"/> when <see cref="Pin"/> receives an invalid target index.
100113
/// </summary>

0 commit comments

Comments
 (0)