Skip to content

Commit

Permalink
Remove unsafe modifier from Memory<T>.Span (#106085)
Browse files Browse the repository at this point in the history
* Remove `unsafe` modifier from `Memory<T>.Span`

* Make `desiredStartIndex` an `int`

* Use `nuint` and add comment

* fixup!b6b93d972b5b16b345e53c8c07c074cdc85cad9a

---------

Co-authored-by: Stephen Toub <stoub@microsoft.com>
  • Loading branch information
xtqqczze and stephentoub authored Nov 19, 2024
1 parent e3b3aaa commit 932da77
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
6 changes: 4 additions & 2 deletions src/libraries/System.Private.CoreLib/src/System/Memory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ public Memory<T> Slice(int start, int length)
/// <summary>
/// Returns a span from the memory.
/// </summary>
public unsafe Span<T> Span
public Span<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
Expand Down Expand Up @@ -327,7 +327,9 @@ public unsafe Span<T> Span
// least to be in-bounds when compared with the original Memory<T> instance, so using the span won't
// AV the process.

// We use 'nuint' because it gives us a free early zero-extension to 64 bits when running on a 64-bit platform.
nuint desiredStartIndex = (uint)_index & (uint)ReadOnlyMemory<T>.RemoveFlagsBitMask;

int desiredLength = _length;

#if TARGET_64BIT
Expand All @@ -343,7 +345,7 @@ public unsafe Span<T> Span
}
#endif

refToReturn = ref Unsafe.Add(ref refToReturn, (IntPtr)(void*)desiredStartIndex);
refToReturn = ref Unsafe.Add(ref refToReturn, desiredStartIndex);
lengthOfUnderlyingSpan = desiredLength;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ public ReadOnlyMemory<T> Slice(int start, int length)
/// <summary>
/// Returns a span from the memory.
/// </summary>
public unsafe ReadOnlySpan<T> Span
public ReadOnlySpan<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
Expand Down Expand Up @@ -249,7 +249,9 @@ public unsafe ReadOnlySpan<T> Span
// least to be in-bounds when compared with the original Memory<T> instance, so using the span won't
// AV the process.

// We use 'nuint' because it gives us a free early zero-extension to 64 bits when running on a 64-bit platform.
nuint desiredStartIndex = (uint)_index & (uint)RemoveFlagsBitMask;

int desiredLength = _length;

#if TARGET_64BIT
Expand All @@ -265,7 +267,7 @@ public unsafe ReadOnlySpan<T> Span
}
#endif

refToReturn = ref Unsafe.Add(ref refToReturn, (IntPtr)(void*)desiredStartIndex);
refToReturn = ref Unsafe.Add(ref refToReturn, desiredStartIndex);
lengthOfUnderlyingSpan = desiredLength;
}

Expand Down

0 comments on commit 932da77

Please sign in to comment.