Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public abstract class CasterHelper<TFrom, TTo>
- #if NET9_0_OR_GREATER
- where TFrom : allows ref struct
- where TTo : allows ref struct
- #endif
- {
- #if NET9_0_OR_GREATER
- private static readonly CasterHelper<TFrom, TTo>? Impl = (typeof(TFrom).IsByRefLike || typeof(TTo).IsByRefLike || (typeof(TFrom).IsValueType && typeof(TTo) == typeof(TFrom)))
- ? null
- : (CasterHelper<TFrom, TTo>?)Activator.CreateInstance(typeof(CastHelperImplementation<,>).MakeGenericType(new Type[] { typeof(TFrom), typeof(TTo) }));
- #endif
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- [return: NotNullIfNotNull(nameof(from))]
- public static TTo Cast(scoped in TFrom from)
- {
- if (typeof(TFrom).IsValueType && typeof(TFrom) == typeof(TTo))
- {
- #if NET9_0_OR_GREATER
- return Unsafe.BitCast<TFrom, TTo>(from);
- #else
- return Unsafe.As<TFrom, TTo>(ref Unsafe.AsRef(in from));
- #endif
- }
- #if NET9_0_OR_GREATER
- if (typeof(TFrom).IsByRefLike || typeof(TTo).IsByRefLike)
- Helper.ThrowInvalidCastException();
- #endif
- #if NET9_0_OR_GREATER
- return Impl!.Cast_(from);
- #else
- return (TTo)(object)from;
- #endif
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static bool TryCast(scoped in TFrom from, out TTo? to)
- {
- if (typeof(TFrom).IsValueType && typeof(TFrom) == typeof(TTo))
- {
- #if NET9_0_OR_GREATER
- to = Unsafe.BitCast<TFrom, TTo>(from);
- #else
- to = Unsafe.As<TFrom, TTo>(ref Unsafe.AsRef(in from));
- #endif
- return true;
- }
- #if NET9_0_OR_GREATER
- if (typeof(TFrom).IsByRefLike || typeof(TTo).IsByRefLike)
- {
- to = default;
- return false;
- }
- #endif
- #if NET9_0_OR_GREATER
- return Impl!.TryCast_(from, out to);
- #else
- if (from is TTo v)
- {
- to = v;
- return true;
- }
- to = default;
- return !typeof(TTo).IsValueType && from is null;
- #endif
- }
- #if NET9_0_OR_GREATER
- [return: NotNullIfNotNull(nameof(from))]
- protected abstract TTo Cast_(scoped in TFrom from);
- protected abstract bool TryCast_(scoped in TFrom from, out TTo to);
- #endif
- }
- #if NET9_0_OR_GREATER
- internal sealed class CastHelperImplementation<TFrom, TTo> : CasterHelper<TFrom, TTo>
- {
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- protected override TTo Cast_(scoped in TFrom from) => (TTo)(object)from;
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- protected override bool TryCast_(scoped in TFrom from, out TTo to)
- {
- if (from is TTo v)
- {
- to = v;
- return true;
- }
- to = default;
- return !typeof(TTo).IsValueType && from is null;
- }
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement