Skip to content

Commit

Permalink
Use explicit AsSpan
Browse files Browse the repository at this point in the history
  • Loading branch information
am11 committed Dec 3, 2024
1 parent 1012c0d commit 3a7a63b
Show file tree
Hide file tree
Showing 23 changed files with 57 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public ReachabilityInstrumentationFilter(string profileDataFileName, ILProvider
int numTokens = reader.ReadInt32();

bool[] tokenStates = new bool[numTokens];
if (reader.Read(MemoryMarshal.Cast<bool, byte>(tokenStates)) != numTokens)
if (reader.Read(MemoryMarshal.Cast<bool, byte>(tokenStates.AsSpan())) != numTokens)
throw new IOException("Unexpected end of file");

_reachabilityInfo.Add(new Guid(guidBytes), tokenStates);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1915,7 +1915,7 @@ public virtual async Task ReadWrite_MessagesSmallerThanReadBuffer_Success(ReadWr
}

Assert.Equal(writerBytes.Length, n);
AssertExtensions.SequenceEqual(writerBytes, readerBytes.AsSpan(0, writerBytes.Length));
AssertExtensions.SequenceEqual(writerBytes.AsSpan(), readerBytes.AsSpan(0, writerBytes.Length));

await writes;
}
Expand Down Expand Up @@ -3069,7 +3069,7 @@ public virtual async Task ZeroByteRead_PerformsZeroByteReadOnUnderlyingStreamWhe

if (FlushGuaranteesAllDataWritten)
{
AssertExtensions.SequenceEqual(data, buffer.AsSpan(0, bytesRead));
AssertExtensions.SequenceEqual(data.AsSpan(), buffer.AsSpan(0, bytesRead));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ internal static IReadOnlyList<T> DecodePrimitiveTypes(BinaryReader reader, int c
{
if (typeof(T) == typeof(short) || typeof(T) == typeof(ushort))
{
Span<short> span = MemoryMarshal.Cast<T, short>(result);
Span<short> span = MemoryMarshal.Cast<T, short>(result.AsSpan());
#if NET
BinaryPrimitives.ReverseEndianness(span, span);
#else
Expand All @@ -173,7 +173,7 @@ internal static IReadOnlyList<T> DecodePrimitiveTypes(BinaryReader reader, int c
}
else if (typeof(T) == typeof(int) || typeof(T) == typeof(uint) || typeof(T) == typeof(float))
{
Span<int> span = MemoryMarshal.Cast<T, int>(result);
Span<int> span = MemoryMarshal.Cast<T, int>(result.AsSpan());
#if NET
BinaryPrimitives.ReverseEndianness(span, span);
#else
Expand All @@ -185,7 +185,7 @@ internal static IReadOnlyList<T> DecodePrimitiveTypes(BinaryReader reader, int c
}
else if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong) || typeof(T) == typeof(double))
{
Span<long> span = MemoryMarshal.Cast<T, long>(result);
Span<long> span = MemoryMarshal.Cast<T, long>(result.AsSpan());
#if NET
BinaryPrimitives.ReverseEndianness(span, span);
#else
Expand All @@ -201,7 +201,7 @@ internal static IReadOnlyList<T> DecodePrimitiveTypes(BinaryReader reader, int c
{
// See DontCastBytesToBooleans test to see what could go wrong.
bool[] booleans = (bool[])(object)result;
Span<byte> resultAsBytes = MemoryMarshal.AsBytes<T>(result);
Span<byte> resultAsBytes = MemoryMarshal.AsBytes<T>(result.AsSpan());
for (int i = 0; i < booleans.Length; i++)
{
// We don't use the bool array to get the value, as an optimizing compiler or JIT could elide this.
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Linq/tests/RangeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ static void Validate(IEnumerable<int> e, int[] expected)
list.CopyTo(actual, 1);
Assert.Equal(0, actual[0]);
Assert.Equal(0, actual[^1]);
AssertExtensions.SequenceEqual(expected, actual.AsSpan(1, expected.Length));
AssertExtensions.SequenceEqual(expected.AsSpan(), actual.AsSpan(1, expected.Length));
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Linq/tests/RepeatTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ static void Validate(IEnumerable<int> e, int[] expected)
list.CopyTo(actual, 1);
Assert.Equal(0, actual[0]);
Assert.Equal(0, actual[^1]);
AssertExtensions.SequenceEqual(expected, actual.AsSpan(1, expected.Length));
AssertExtensions.SequenceEqual(expected.AsSpan(), actual.AsSpan(1, expected.Length));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ public static void Base64_AllMethodsRoundtripConsistently()
Span<byte> decodedBytes = new byte[original.Length];
int decoded = Base64Url.DecodeFromChars(encodedArray, decodedBytes);
Assert.Equal(original.Length, decoded);
AssertExtensions.SequenceEqual(original, decodedBytes);
AssertExtensions.SequenceEqual(original.AsSpan(), decodedBytes);

byte[] actualBytes = new byte[original.Length];
Assert.True(Base64Url.TryDecodeFromChars(encodedSpan, actualBytes, out int bytesWritten));
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Memory/tests/Span/SearchValues.cs
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ static SearchValuesTestHelper()
s_randomLatin1Chars[i] = (char)rng.Next(0, 256);
}

rng.NextBytes(MemoryMarshal.Cast<char, byte>(s_randomChars));
rng.NextBytes(MemoryMarshal.Cast<char, byte>(s_randomChars.AsSpan()));

s_randomAsciiBytes = Encoding.ASCII.GetBytes(s_randomAsciiChars);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,7 @@ public StringSearchValuesTestHelper(IndexOfAnySearchDelegate expected, SearchVal
}));
}

rng.NextBytes(MemoryMarshal.Cast<char, byte>(_randomChars));
rng.NextBytes(MemoryMarshal.Cast<char, byte>(_randomChars.AsSpan()));
}

public void StressRandomInputs(TimeSpan duration)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -728,7 +728,7 @@ public void AcceptAsync_WithReceiveBuffer_Success()

Assert.Equal(acceptBufferDataSize, acceptArgs.BytesTransferred);

AssertExtensions.SequenceEqual(sendBuffer, acceptArgs.Buffer.AsSpan(0, acceptArgs.BytesTransferred));
AssertExtensions.SequenceEqual(sendBuffer.AsSpan(), acceptArgs.Buffer.AsSpan(0, acceptArgs.BytesTransferred));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -527,32 +527,32 @@ public void ListSetCount()
CollectionsMarshal.SetCount(list, 3);
Assert.Equal(3, list.Count);
Assert.Throws<ArgumentOutOfRangeException>(() => list[3]);
AssertExtensions.SequenceEqual(CollectionsMarshal.AsSpan(list), new int[] { 1, 2, 3 });
AssertExtensions.SequenceEqual(CollectionsMarshal.AsSpan(list), new int[] { 1, 2, 3 }.AsSpan());
Assert.True(Unsafe.AreSame(ref intRef, ref MemoryMarshal.GetReference(CollectionsMarshal.AsSpan(list))));

// make sure that size increase preserves content and doesn't clear
CollectionsMarshal.SetCount(list, 5);
AssertExtensions.SequenceEqual(CollectionsMarshal.AsSpan(list), new int[] { 1, 2, 3, 4, 5 });
AssertExtensions.SequenceEqual(CollectionsMarshal.AsSpan(list), new int[] { 1, 2, 3, 4, 5 }.AsSpan());
Assert.True(Unsafe.AreSame(ref intRef, ref MemoryMarshal.GetReference(CollectionsMarshal.AsSpan(list))));

// make sure that reallocations preserve content
int newCount = list.Capacity * 2;
CollectionsMarshal.SetCount(list, newCount);
Assert.Equal(newCount, list.Count);
AssertExtensions.SequenceEqual(CollectionsMarshal.AsSpan(list)[..3], new int[] { 1, 2, 3 });
AssertExtensions.SequenceEqual(CollectionsMarshal.AsSpan(list)[..3], new int[] { 1, 2, 3 }.AsSpan());
Assert.True(!Unsafe.AreSame(ref intRef, ref MemoryMarshal.GetReference(CollectionsMarshal.AsSpan(list))));

List<string> listReference = new() { "a", "b", "c", "d", "e" };
ref string stringRef = ref MemoryMarshal.GetReference(CollectionsMarshal.AsSpan(listReference));
CollectionsMarshal.SetCount(listReference, 3);

// verify that reference types aren't cleared
AssertExtensions.SequenceEqual(CollectionsMarshal.AsSpan(listReference), new string[] { "a", "b", "c" });
AssertExtensions.SequenceEqual(CollectionsMarshal.AsSpan(listReference), new string[] { "a", "b", "c" }.AsSpan());
Assert.True(Unsafe.AreSame(ref stringRef, ref MemoryMarshal.GetReference(CollectionsMarshal.AsSpan(listReference))));
CollectionsMarshal.SetCount(listReference, 5);

// verify that removed reference types are cleared
AssertExtensions.SequenceEqual(CollectionsMarshal.AsSpan(listReference), new string[] { "a", "b", "c", null, null });
AssertExtensions.SequenceEqual(CollectionsMarshal.AsSpan(listReference), new string[] { "a", "b", "c", null, null }.AsSpan());
Assert.True(Unsafe.AreSame(ref stringRef, ref MemoryMarshal.GetReference(CollectionsMarshal.AsSpan(listReference))));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ public BigInteger(ReadOnlySpan<byte> value, bool isUnsigned = false, bool isBigE
// The bytes parameter is in little-endian byte order.
// We can just copy the bytes directly into the uint array.

value.Slice(0, wholeUInt32Count * 4).CopyTo(MemoryMarshal.AsBytes<uint>(val));
value.Slice(0, wholeUInt32Count * 4).CopyTo(MemoryMarshal.AsBytes<uint>(val.AsSpan()));
}

// In both of the above cases on big-endian architecture, we need to perform
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public async Task IncompleteReadCantSetPositionBeyondEndOfFile(FileShare fileSha
await Task.WhenAll(reads);
// but when they are finished, the first buffer should contain valid data:
Assert.Equal(fileSize, reads.First().Result);
AssertExtensions.SequenceEqual(content, buffers.First().AsSpan(0, fileSize));
AssertExtensions.SequenceEqual(content.AsSpan(), buffers.First().AsSpan(0, fileSize));
// and other reads should return 0:
Assert.All(reads.Skip(1), read => Assert.Equal(0, read.Result));
// and the Position must be correct:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ private static void TestSequence(byte[] expected, string actual)
Assert.Equal(OperationStatus.Done, Convert.FromHexString(actual, tryResult, out int consumed, out int written));
Assert.Equal(fromResult.Length, written);
Assert.Equal(actual.Length, consumed);
AssertExtensions.SequenceEqual(expected, tryResult);
AssertExtensions.SequenceEqual(expected.AsSpan(), tryResult);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -713,9 +713,9 @@ public static void Shuffle_Array_Seeded(bool emptyShuffle)
Random random = new Random(0x70636A61);
int[] items = new int[] { 1, 2, 3, 4 };
random.Shuffle(items);
AssertExtensions.SequenceEqual(stackalloc int[] { 4, 2, 1, 3 }, items);
AssertExtensions.SequenceEqual(stackalloc int[] { 4, 2, 1, 3 }, items.AsSpan());
random.Shuffle(items);
AssertExtensions.SequenceEqual(stackalloc int[] { 2, 3, 4, 1 }, items);
AssertExtensions.SequenceEqual(stackalloc int[] { 2, 3, 4, 1 }, items.AsSpan());

if (emptyShuffle)
{
Expand All @@ -724,7 +724,7 @@ public static void Shuffle_Array_Seeded(bool emptyShuffle)
}

random.Shuffle(items);
AssertExtensions.SequenceEqual(stackalloc int[] { 1, 4, 3, 2 }, items);
AssertExtensions.SequenceEqual(stackalloc int[] { 1, 4, 3, 2 }, items.AsSpan());
}

[Fact]
Expand Down Expand Up @@ -831,13 +831,13 @@ public static void GetItems_Buffer_Seeded_NonPower2()

Span<byte> buffer = stackalloc byte[7];
random.GetItems(items, buffer);
AssertExtensions.SequenceEqual(new byte[] { 3, 1, 3, 2, 3, 3, 3 }, buffer);
AssertExtensions.SequenceEqual(new byte[] { 3, 1, 3, 2, 3, 3, 3 }.AsSpan(), buffer);

random.GetItems(items, buffer);
AssertExtensions.SequenceEqual(new byte[] { 2, 1, 2, 1, 2, 3, 1 }, buffer);
AssertExtensions.SequenceEqual(new byte[] { 2, 1, 2, 1, 2, 3, 1 }.AsSpan(), buffer);

random.GetItems(items, buffer);
AssertExtensions.SequenceEqual(new byte[] { 1, 1, 3, 1, 3, 2, 2 }, buffer);
AssertExtensions.SequenceEqual(new byte[] { 1, 1, 3, 1, 3, 2, 2 }.AsSpan(), buffer);
}

[Fact]
Expand Down Expand Up @@ -880,13 +880,13 @@ public static void GetItems_Buffer_Seeded_Power2()

Span<byte> buffer = stackalloc byte[7];
random.GetItems(items, buffer);
AssertExtensions.SequenceEqual(new byte[] { 4, 1, 4, 2, 4, 4, 4 }, buffer);
AssertExtensions.SequenceEqual(new byte[] { 4, 1, 4, 2, 4, 4, 4 }.AsSpan(), buffer);

random.GetItems(items, buffer);
AssertExtensions.SequenceEqual(new byte[] { 2, 2, 3, 1, 3, 3, 1 }, buffer);
AssertExtensions.SequenceEqual(new byte[] { 2, 2, 3, 1, 3, 3, 1 }.AsSpan(), buffer);

random.GetItems(items, buffer);
AssertExtensions.SequenceEqual(new byte[] { 2, 1, 4, 2, 4, 2, 2 }, buffer);
AssertExtensions.SequenceEqual(new byte[] { 2, 1, 4, 2, 4, 2, 2 }.AsSpan(), buffer);
}

[Theory]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,20 @@ public static void OverlappingBuffers_Throws()
Assert.Throws<InvalidOperationException>(() => Ascii.ToUpper(byteBuffer, byteBuffer, out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToUpper(byteBuffer.AsSpan(1, 3), byteBuffer.AsSpan(3, 5), out _));
// byte -> char
Assert.Throws<InvalidOperationException>(() => Ascii.ToLower(byteBuffer, MemoryMarshal.Cast<byte, char>(byteBuffer), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToLower(byteBuffer, MemoryMarshal.Cast<byte, char>(byteBuffer).Slice(1, 3), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToUpper(byteBuffer, MemoryMarshal.Cast<byte, char>(byteBuffer), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToUpper(byteBuffer, MemoryMarshal.Cast<byte, char>(byteBuffer).Slice(1, 3), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToLower(byteBuffer, MemoryMarshal.Cast<byte, char>(byteBuffer.AsSpan()), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToLower(byteBuffer, MemoryMarshal.Cast<byte, char>(byteBuffer.AsSpan()).Slice(1, 3), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToUpper(byteBuffer, MemoryMarshal.Cast<byte, char>(byteBuffer.AsSpan()), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToUpper(byteBuffer, MemoryMarshal.Cast<byte, char>(byteBuffer.AsSpan()).Slice(1, 3), out _));
// char -> char
Assert.Throws<InvalidOperationException>(() => Ascii.ToLower(charBuffer, charBuffer, out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToLower(charBuffer.AsSpan(1, 3), charBuffer.AsSpan(3, 5), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToUpper(charBuffer, charBuffer, out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToUpper(charBuffer.AsSpan(1, 3), charBuffer.AsSpan(3, 5), out _));
// char -> byte
Assert.Throws<InvalidOperationException>(() => Ascii.ToLower(charBuffer, MemoryMarshal.Cast<char, byte>(charBuffer), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToLower(charBuffer, MemoryMarshal.Cast<char, byte>(charBuffer).Slice(1, 3), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToUpper(charBuffer, MemoryMarshal.Cast<char, byte>(charBuffer), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToUpper(charBuffer, MemoryMarshal.Cast<char, byte>(charBuffer).Slice(1, 3), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToLower(charBuffer, MemoryMarshal.Cast<char, byte>(charBuffer.AsSpan()), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToLower(charBuffer, MemoryMarshal.Cast<char, byte>(charBuffer.AsSpan()).Slice(1, 3), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToUpper(charBuffer, MemoryMarshal.Cast<char, byte>(charBuffer.AsSpan()), out _));
Assert.Throws<InvalidOperationException>(() => Ascii.ToUpper(charBuffer, MemoryMarshal.Cast<char, byte>(charBuffer.AsSpan()).Slice(1, 3), out _));
}

private static void VerifySingleChar<T>(OperationStatus status, int value, T expected, T actual, int written)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public void GetValueAsBytesSucceeds(ContentTestCase @case)
Span<byte> buffer = new byte[content.Length];
int length = headerValue.GetValueAsBytes(buffer);
Assert.Equal(content.Length, length);
AssertExtensions.SequenceEqual(content, buffer);
AssertExtensions.SequenceEqual(content.AsSpan(), buffer);
}

[Theory]
Expand Down Expand Up @@ -138,7 +138,7 @@ void Verify(int repetitions)

for (int i = 0; i < expectedLength; i+= content.Length)
{
AssertExtensions.SequenceEqual(content, buffer.Slice(i, content.Length));
AssertExtensions.SequenceEqual(content.AsSpan(), buffer.Slice(i, content.Length));
}
}
}
Expand Down Expand Up @@ -244,7 +244,7 @@ public void FromBytesSucceeds(ContentTestCase @case)

Span<byte> buffer = new byte[content.Length];
int length = headerValue.GetValueAsBytes(buffer);
AssertExtensions.SequenceEqual(content, buffer);
AssertExtensions.SequenceEqual(content.AsSpan(), buffer);
Assert.Equal(content.Length, length);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public void ZeroBufferThrows()
public void NearCorrectSizeBufferTests(int delta, bool success)
{
byte[] buffer = new byte[DefaultProtectedBufferSize];
int original = ProtectedData.Protect([1, 2, 3], DataProtectionScope.CurrentUser, buffer);
int original = ProtectedData.Protect([1, 2, 3], DataProtectionScope.CurrentUser, buffer.AsSpan());

if (success)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ private void VerifyOneShotStream(Stream input, string output)
Span<byte> buffer = stackalloc byte[512 / 8];

int written = HashData(input, buffer);
AssertExtensions.SequenceEqual(expected, buffer.Slice(0, written));
AssertExtensions.SequenceEqual(expected.AsSpan(), buffer.Slice(0, written));
}

private async Task VerifyOneShotStreamAsync(Stream input, string output)
Expand All @@ -75,7 +75,7 @@ private async Task VerifyOneShotStreamAsync(Stream input, string output)
Memory<byte> buffer = new byte[512 / 8];

int written = await HashDataAsync(input, buffer, cancellationToken: default);
AssertExtensions.SequenceEqual(expected, buffer.Slice(0, written).Span);
AssertExtensions.SequenceEqual(expected.AsSpan(), buffer.Slice(0, written).Span);
}

private void VerifyOneShotAllocatingStream(Stream input, string output)
Expand All @@ -100,7 +100,7 @@ private void VerifyOneShotStream_CryptographicOperations(Stream input, string ou
Span<byte> buffer = stackalloc byte[512 / 8];

int written = CryptographicOperations.HashData(HashAlgorithm, input, buffer);
AssertExtensions.SequenceEqual(expected, buffer.Slice(0, written));
AssertExtensions.SequenceEqual(expected.AsSpan(), buffer.Slice(0, written));
}

private async Task VerifyOneShotStreamAsync_CryptographicOperations(Stream input, string output)
Expand All @@ -114,7 +114,7 @@ private async Task VerifyOneShotStreamAsync_CryptographicOperations(Stream input
buffer,
cancellationToken: default);

AssertExtensions.SequenceEqual(expected, buffer.Slice(0, written).Span);
AssertExtensions.SequenceEqual(expected.AsSpan(), buffer.Slice(0, written).Span);
}

private void VerifyOneShotAllocatingStream_CryptographicOperations(Stream input, string output)
Expand Down
Loading

0 comments on commit 3a7a63b

Please sign in to comment.