Skip to content

Commit

Permalink
Avoid Unsafe.As<char, ushort> reinterpret casts by introducing string…
Browse files Browse the repository at this point in the history
….GetRawStringDataAsUshort() internal method
  • Loading branch information
gfoidl committed Jul 20, 2022
1 parent ed83650 commit 5d92816
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1006,8 +1006,8 @@ public string Replace(char oldChar, char newChar)
}

// Copy the remaining characters, doing the replacement as we go.
ref ushort pSrc = ref Unsafe.Add(ref Unsafe.As<char, ushort>(ref _firstChar), (nint)(uint)copyLength);
ref ushort pDst = ref Unsafe.Add(ref Unsafe.As<char, ushort>(ref result._firstChar), (nint)(uint)copyLength);
ref ushort pSrc = ref Unsafe.Add(ref GetRawStringDataAsUshort(), (nint)(uint)copyLength);
ref ushort pDst = ref Unsafe.Add(ref result.GetRawStringDataAsUshort(), (nint)(uint)copyLength);
nint i = 0;

if (Vector.IsHardwareAccelerated && Length >= Vector<ushort>.Count)
Expand Down Expand Up @@ -1044,10 +1044,10 @@ public string Replace(char oldChar, char newChar)
// additional check which would introduce a branch here.

i = (nint)(uint)Length - Vector<ushort>.Count;
original = Vector.LoadUnsafe(ref Unsafe.As<char, ushort>(ref _firstChar), i);
original = Vector.LoadUnsafe(ref GetRawStringDataAsUshort(), i);
equals = Vector.Equals(original, oldChars);
results = Vector.ConditionalSelect(equals, newChars, original);
results.StoreUnsafe(ref Unsafe.As<char, ushort>(ref result._firstChar), i);
results.StoreUnsafe(ref result.GetRawStringDataAsUshort(), i);
}
else
{
Expand Down
1 change: 1 addition & 0 deletions src/libraries/System.Private.CoreLib/src/System/String.cs
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,7 @@ public static bool IsNullOrWhiteSpace([NotNullWhen(false)] string? value)
public ref readonly char GetPinnableReference() => ref _firstChar;

internal ref char GetRawStringData() => ref _firstChar;
internal ref ushort GetRawStringDataAsUshort() => ref Unsafe.As<char, ushort>(ref _firstChar);

// Helper for encodings so they can talk to our buffer directly
// stringLength must be the exact size we'll expect
Expand Down

0 comments on commit 5d92816

Please sign in to comment.