Skip to content

Commit 86803d8

Browse files
Merge branch 'master' into wrapPanel.verticalAlignment
2 parents 792bc93 + 9087194 commit 86803d8

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

Microsoft.Toolkit.HighPerformance/Streams/MemoryStream.Validate.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,14 @@ namespace Microsoft.Toolkit.HighPerformance.Streams
1313
internal static partial class MemoryStream
1414
{
1515
/// <summary>
16-
/// Validates the <see cref="Stream.Position"/> argument.
16+
/// Validates the <see cref="Stream.Position"/> argument (it needs to be in the [0, length]) range.
1717
/// </summary>
1818
/// <param name="position">The new <see cref="Stream.Position"/> value being set.</param>
1919
/// <param name="length">The maximum length of the target <see cref="Stream"/>.</param>
2020
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2121
public static void ValidatePosition(long position, int length)
2222
{
23-
if ((ulong)position >= (ulong)length)
23+
if ((ulong)position > (ulong)length)
2424
{
2525
ThrowArgumentOutOfRangeExceptionForPosition();
2626
}

UnitTests/UnitTests.HighPerformance.Shared/Streams/Test_MemoryStream.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,42 @@ public void Test_MemoryStream_Seek()
7878
Assert.AreEqual(stream.Position, 32);
7979
}
8080

81+
// See https://github.com/windows-toolkit/WindowsCommunityToolkit/issues/3536
82+
[TestCategory("MemoryStream")]
83+
[TestMethod]
84+
public void Test_MemoryStream_WriteToEndAndRefreshPosition()
85+
{
86+
byte[]
87+
array = new byte[10],
88+
temp = new byte[1];
89+
ReadOnlyMemory<byte> memory = array;
90+
91+
using var stream = memory.AsStream();
92+
93+
for (int i = 0; i < array.Length; i++)
94+
{
95+
int read = stream.Read(temp, 0, 1);
96+
97+
Assert.AreEqual(read, 1);
98+
Assert.AreEqual(stream.Position, i + 1);
99+
}
100+
101+
Assert.AreEqual(stream.Position, array.Length);
102+
103+
// These should not throw, seeking to the end is valid
104+
stream.Position = stream.Position;
105+
Assert.AreEqual(stream.Position, array.Length);
106+
107+
stream.Seek(array.Length, SeekOrigin.Begin);
108+
Assert.AreEqual(stream.Position, array.Length);
109+
110+
stream.Seek(0, SeekOrigin.Current);
111+
Assert.AreEqual(stream.Position, array.Length);
112+
113+
stream.Seek(0, SeekOrigin.End);
114+
Assert.AreEqual(stream.Position, array.Length);
115+
}
116+
81117
[TestCategory("MemoryStream")]
82118
[TestMethod]
83119
public void Test_MemoryStream_ReadWrite_Array()

0 commit comments

Comments
 (0)