Skip to content

Commit 932da77

Browse files
Remove unsafe modifier from Memory<T>.Span (#106085)
* Remove `unsafe` modifier from `Memory<T>.Span` * Make `desiredStartIndex` an `int` * Use `nuint` and add comment * fixup!b6b93d972b5b16b345e53c8c07c074cdc85cad9a --------- Co-authored-by: Stephen Toub <[email protected]>
1 parent e3b3aaa commit 932da77

File tree

2 files changed

+8
-4
lines changed

2 files changed

+8
-4
lines changed

src/libraries/System.Private.CoreLib/src/System/Memory.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ public Memory<T> Slice(int start, int length)
263263
/// <summary>
264264
/// Returns a span from the memory.
265265
/// </summary>
266-
public unsafe Span<T> Span
266+
public Span<T> Span
267267
{
268268
[MethodImpl(MethodImplOptions.AggressiveInlining)]
269269
get
@@ -327,7 +327,9 @@ public unsafe Span<T> Span
327327
// least to be in-bounds when compared with the original Memory<T> instance, so using the span won't
328328
// AV the process.
329329

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

333335
#if TARGET_64BIT
@@ -343,7 +345,7 @@ public unsafe Span<T> Span
343345
}
344346
#endif
345347

346-
refToReturn = ref Unsafe.Add(ref refToReturn, (IntPtr)(void*)desiredStartIndex);
348+
refToReturn = ref Unsafe.Add(ref refToReturn, desiredStartIndex);
347349
lengthOfUnderlyingSpan = desiredLength;
348350
}
349351

src/libraries/System.Private.CoreLib/src/System/ReadOnlyMemory.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ public ReadOnlyMemory<T> Slice(int start, int length)
192192
/// <summary>
193193
/// Returns a span from the memory.
194194
/// </summary>
195-
public unsafe ReadOnlySpan<T> Span
195+
public ReadOnlySpan<T> Span
196196
{
197197
[MethodImpl(MethodImplOptions.AggressiveInlining)]
198198
get
@@ -249,7 +249,9 @@ public unsafe ReadOnlySpan<T> Span
249249
// least to be in-bounds when compared with the original Memory<T> instance, so using the span won't
250250
// AV the process.
251251

252+
// We use 'nuint' because it gives us a free early zero-extension to 64 bits when running on a 64-bit platform.
252253
nuint desiredStartIndex = (uint)_index & (uint)RemoveFlagsBitMask;
254+
253255
int desiredLength = _length;
254256

255257
#if TARGET_64BIT
@@ -265,7 +267,7 @@ public unsafe ReadOnlySpan<T> Span
265267
}
266268
#endif
267269

268-
refToReturn = ref Unsafe.Add(ref refToReturn, (IntPtr)(void*)desiredStartIndex);
270+
refToReturn = ref Unsafe.Add(ref refToReturn, desiredStartIndex);
269271
lengthOfUnderlyingSpan = desiredLength;
270272
}
271273

0 commit comments

Comments
 (0)