Skip to content

Commit c23e1cc

Browse files
authored
Merge pull request #997 from CommunityToolkit/dev/indexof-ref-readonly
Use 'ref readonly' in 'IndexOf<T>' APIs
2 parents 5009433 + 77f1f33 commit c23e1cc

File tree

3 files changed

+12
-4
lines changed

3 files changed

+12
-4
lines changed

src/CommunityToolkit.HighPerformance/Enumerables/SpanTokenizer{T}.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,10 @@ public bool MoveNext()
7373
{
7474
this.start = newEnd;
7575

76-
int index = this.span.Slice(newEnd).IndexOf(this.separator);
76+
// Here we're inside the 'CommunityToolkit.HighPerformance.Enumerables' namespace, so the
77+
// 'MemoryExtensions' type from the .NET Community Toolkit would be bound instead. Because
78+
// want the one from the BCL (to search by value), we can use its fully qualified name.
79+
int index = System.MemoryExtensions.IndexOf(this.span.Slice(newEnd), this.separator);
7780

7881
// Extract the current subsequence
7982
if (index >= 0)

src/CommunityToolkit.HighPerformance/Extensions/ReadOnlySpanExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ public static ReadOnlySpan2D<T> AsSpan2D<T>(this ReadOnlySpan<T> span, int offse
210210
/// <param name="value">The reference to the target item to get the index for.</param>
211211
/// <returns>The index of <paramref name="value"/> within <paramref name="span"/>, or <c>-1</c>.</returns>
212212
[MethodImpl(MethodImplOptions.AggressiveInlining)]
213-
public static unsafe int IndexOf<T>(this ReadOnlySpan<T> span, in T value)
213+
public static unsafe int IndexOf<T>(this ReadOnlySpan<T> span, ref readonly T value)
214214
{
215215
ref T r0 = ref MemoryMarshal.GetReference(span);
216216
ref T r1 = ref Unsafe.AsRef(in value);

src/CommunityToolkit.HighPerformance/Extensions/SpanExtensions.cs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,10 +148,15 @@ public static Span<TTo> Cast<TFrom, TTo>(this Span<TFrom> span)
148148
/// <param name="value">The reference to the target item to get the index for.</param>
149149
/// <returns>The index of <paramref name="value"/> within <paramref name="span"/>, or <c>-1</c>.</returns>
150150
[MethodImpl(MethodImplOptions.AggressiveInlining)]
151-
public static unsafe int IndexOf<T>(this Span<T> span, ref T value)
151+
public static unsafe int IndexOf<T>(this Span<T> span, ref readonly T value)
152152
{
153153
ref T r0 = ref MemoryMarshal.GetReference(span);
154-
IntPtr byteOffset = Unsafe.ByteOffset(ref r0, ref value);
154+
IntPtr byteOffset =
155+
#if NET8_0_OR_GREATER
156+
Unsafe.ByteOffset(ref r0, in value);
157+
#else
158+
Unsafe.ByteOffset(ref r0, ref Unsafe.AsRef(in value));
159+
#endif
155160

156161
nint elementOffset = byteOffset / (nint)(uint)sizeof(T);
157162

0 commit comments

Comments
 (0)