Skip to content

Commit

Permalink
Use BitCast in MemoryMarshal.Cast fast-path
Browse files Browse the repository at this point in the history
Alternative to dotnet#109136
  • Loading branch information
MichalPetryka authored Dec 23, 2024
1 parent 9c1bae3 commit 90be007
Showing 1 changed file with 10 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,12 @@ public static unsafe Span<TTo> Cast<TFrom, TTo>(Span<TFrom> span)
int toLength;
if (fromSize == toSize)
{
// Special case for same size types - `(ulong)fromLength * (ulong)fromSize / (ulong)toSize`
// should be optimized to just `length` but the JIT doesn't do that today.
toLength = (int)fromLength;
// Special case for same size types
// should be optimized without this but the JIT doesn't do that today.
return Unsafe.BitCast<Span<TFrom>, Span<TTo>>(span);
}
else if (fromSize == 1)

if (fromSize == 1)
{
// Special case for byte sized TFrom - `(ulong)fromLength * (ulong)fromSize / (ulong)toSize`
// becomes `(ulong)fromLength / (ulong)toSize` but the JIT can't narrow it down to `int`
Expand Down Expand Up @@ -183,11 +184,12 @@ public static unsafe ReadOnlySpan<TTo> Cast<TFrom, TTo>(ReadOnlySpan<TFrom> span
int toLength;
if (fromSize == toSize)
{
// Special case for same size types - `(ulong)fromLength * (ulong)fromSize / (ulong)toSize`
// should be optimized to just `length` but the JIT doesn't do that today.
toLength = (int)fromLength;
// Special case for same size types
// should be optimized without this but the JIT doesn't do that today.
return Unsafe.BitCast<ReadOnlySpan<TFrom>, ReadOnlySpan<TTo>>(span);
}
else if (fromSize == 1)

if (fromSize == 1)
{
// Special case for byte sized TFrom - `(ulong)fromLength * (ulong)fromSize / (ulong)toSize`
// becomes `(ulong)fromLength / (ulong)toSize` but the JIT can't narrow it down to `int`
Expand Down

0 comments on commit 90be007

Please sign in to comment.