Skip to content

Commit

Permalink
Merge pull request #6533 from YohDeadfall/faster-type-utils
Browse files Browse the repository at this point in the history
Compiler intrinsic based type nullability check
  • Loading branch information
Dan Walmsley committed Sep 7, 2021
2 parents d2347bf + e3961ec commit 982dbcb
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/Avalonia.Base/Data/Converters/FuncValueConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public FuncValueConverter(Func<TIn, TOut> convert)
/// <inheritdoc/>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is TIn || (value == null && TypeUtilities.AcceptsNull(typeof(TIn))))
if (TypeUtilities.CanCast<TIn>(value))
{
return _convert((TIn)value);
}
Expand Down
14 changes: 13 additions & 1 deletion src/Avalonia.Base/Utilities/TypeUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace Avalonia.Utilities
{
Expand Down Expand Up @@ -93,6 +94,17 @@ public static bool AcceptsNull(Type type)
return !type.IsValueType || IsNullableType(type);
}

/// <summary>
/// Returns a value indicating whether null can be assigned to the specified type.
/// </summary>
/// <typeparam name="T">The type</typeparam>
/// <returns>True if the type accepts null values; otherwise false.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool AcceptsNull<T>()
{
return default(T) is null;
}

/// <summary>
/// Returns a value indicating whether value can be casted to the specified type.
/// If value is null, checks if instances of that type can be null.
Expand All @@ -102,7 +114,7 @@ public static bool AcceptsNull(Type type)
/// <returns>True if the cast is possible, otherwise false.</returns>
public static bool CanCast<T>(object value)
{
return value is T || (value is null && AcceptsNull(typeof(T)));
return value is T || (value is null && AcceptsNull<T>());
}

/// <summary>
Expand Down

0 comments on commit 982dbcb

Please sign in to comment.