Skip to content
64 changes: 64 additions & 0 deletions Source/ReactiveProperty.Core/Internals/PropertyPathAccessor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace Reactive.Bindings.Internals;

internal static class PropertyPathAccessor
{
private static readonly ConditionalWeakTable<Delegate, Func<object, object?>> s_getters = new();
private static readonly ConditionalWeakTable<Delegate, Action<object, object?>> s_setters = new();

public static Func<object, object?> Get(Delegate accessor) => s_getters.GetValue(accessor, CreateGetter);

public static Action<object, object?> Set(Delegate accessor) => s_setters.GetValue(accessor, CreateSetter);

private static Func<object, object?> CreateGetter(Delegate accessor)
{
var typeArguments = accessor.GetType().GetGenericArguments();
var source = Expression.Parameter(typeof(object), "source");
var invoke = Expression.Invoke(Expression.Constant(accessor), Expression.Convert(source, typeArguments[0]));
var fallback = Expression.Call(
Expression.Constant(accessor),
nameof(Delegate.DynamicInvoke),
Type.EmptyTypes,
Expression.NewArrayInit(typeof(object), source));
var body = Expression.Condition(
Expression.TypeIs(source, typeArguments[0]),
Expression.Convert(WrapTargetExceptions(invoke), typeof(object)),
fallback);
return Expression.Lambda<Func<object, object?>>(body, source).Compile();
}

private static Action<object, object?> CreateSetter(Delegate accessor)
{
var typeArguments = accessor.GetType().GetGenericArguments();
var source = Expression.Parameter(typeof(object), "source");
var value = Expression.Parameter(typeof(object), "value");
var invoke = Expression.Invoke(
Expression.Constant(accessor),
Expression.Convert(source, typeArguments[0]),
Expression.Convert(value, typeArguments[1]));
var fallback = Expression.Call(
Expression.Constant(accessor),
nameof(Delegate.DynamicInvoke),
Type.EmptyTypes,
Expression.NewArrayInit(typeof(object), source, value));
var body = Expression.IfThenElse(
Expression.AndAlso(Expression.TypeIs(source, typeArguments[0]), Expression.TypeIs(value, typeArguments[1])),
WrapTargetExceptions(invoke),
Expression.Block(fallback, Expression.Empty()));
return Expression.Lambda<Action<object, object?>>(body, source, value).Compile();
}

private static Expression WrapTargetExceptions(Expression invoke)
{
var exception = Expression.Parameter(typeof(Exception), "exception");
var constructor = typeof(TargetInvocationException).GetConstructor(new[] { typeof(Exception) })!;
// DynamicInvoke wraps exceptions thrown by the target delegate.
return Expression.TryCatch(
invoke,
Expression.Catch(exception, Expression.Throw(Expression.New(constructor, exception), invoke.Type)));
}
}
12 changes: 6 additions & 6 deletions Source/ReactiveProperty.Core/Internals/PropertyPathNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ internal class PropertyPathNode : IDisposable
{
private bool _isDisposed = false;
private Action? _callback;
private Delegate? _getAccessor;
private Delegate? _setAccessor;
private Func<object, object?>? _getAccessor;
private Action<object, object?>? _setAccessor;

public event EventHandler? PropertyChanged;

Expand Down Expand Up @@ -69,8 +69,8 @@ private void StartObservePropertyChanged()
{
EnsureDispose();
if (Source == null) return null;
return (_getAccessor ?? (_getAccessor = AccessorCache.LookupGet(Source.GetType(), PropertyName)))
.DynamicInvoke(Source);
return (_getAccessor ?? (_getAccessor = PropertyPathAccessor.Get(AccessorCache.LookupGet(Source.GetType(), PropertyName))))
.Invoke(Source);
}

public object? GetPropertyPathValue()
Expand Down Expand Up @@ -101,8 +101,8 @@ public bool SetPropertyPathValue(object? value)
}
else
{
var setter = _setAccessor ?? (_setAccessor = AccessorCache.LookupSet(Source.GetType(), PropertyName));
setter.DynamicInvoke(Source, value);
var setter = _setAccessor ?? (_setAccessor = PropertyPathAccessor.Set(AccessorCache.LookupSet(Source.GetType(), PropertyName)));
setter(Source, value);
return true;
}
}
Expand Down
14 changes: 11 additions & 3 deletions Source/ReactiveProperty.Core/ValidatableReactiveProperty.cs
Original file line number Diff line number Diff line change
Expand Up @@ -337,9 +337,17 @@ private void Validate(T value, ValidationKind validationKind = ValidationKind.De
_latestValue = value;
if (needValidation)
{
_errorMessages.Value = _validators.Select(x => x(value))
.Where(x => x is not null)
.ToArray()!;
List<string>? errors = null;
foreach (var validator in _validators)
{
var error = validator(value);
if (error is not null)
{
(errors ??= []).Add(error);
}
}

_errorMessages.Value = errors?.ToArray() ?? [];
}

if (isNotEquals || IsDistinctUntilChanged is false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ internal class PropertyPathNodeLegacy : IDisposable
{
private bool _isDisposed = false;
private Action? _callback;
private Delegate? _getAccessor;
private Delegate? _setAccessor;
private Func<object, object?>? _getAccessor;
private Action<object, object?>? _setAccessor;

public event EventHandler? PropertyChanged;

Expand Down Expand Up @@ -70,8 +70,8 @@ private void StartObservePropertyChanged()
{
EnsureDispose();
if (Source == null) return null;
return (_getAccessor ?? (_getAccessor = AccessorCache.LookupGet(Source.GetType(), PropertyName)))
.DynamicInvoke(Source);
return (_getAccessor ?? (_getAccessor = PropertyPathAccessor.Get(AccessorCache.LookupGet(Source.GetType(), PropertyName))))
.Invoke(Source);
}

public object? GetPropertyPathValue()
Expand Down Expand Up @@ -102,8 +102,8 @@ public bool SetPropertyPathValue(object? value)
}
else
{
var setter = _setAccessor ?? (_setAccessor = AccessorCache.LookupSet(Source.GetType(), PropertyName));
setter.DynamicInvoke(Source, value);
var setter = _setAccessor ?? (_setAccessor = PropertyPathAccessor.Set(AccessorCache.LookupSet(Source.GetType(), PropertyName)));
setter(Source, value);
return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ internal sealed class FilteredReadOnlyObservableCollection<TCollection, TElement
where TCollection : INotifyCollectionChanged, IList<TElement>
where TElement : class, INotifyPropertyChanged
{
private static readonly PropertyChangedEventArgs s_countPropertyChangedEventArgs = new(nameof(Count));
private static readonly PropertyChangedEventArgs s_indexerPropertyChangedEventArgs = new("Item[]");

private readonly object _syncRoot = new();
private readonly List<TElement> _innerCollection = new();
private readonly List<int?> _indexList = new();
Expand Down Expand Up @@ -178,7 +181,7 @@ private void SourceCollectionChanged(object? sender, NotifyCollectionChangedEven
{
var sourceIndex = e.OldStartingIndex;
var filteredIndex = _indexList[sourceIndex];
var item = e.OldItems.Cast<TElement>().ElementAt(i);
var item = (TElement)e.OldItems[i]!;
if (filteredIndex.HasValue)
{
DisappearItem(sourceIndex);
Expand Down Expand Up @@ -312,8 +315,8 @@ private void RaiseChangedCore(NotifyCollectionChangedEventArgs? args)
return;
}

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
PropertyChanged?.Invoke(this, s_countPropertyChangedEventArgs);
PropertyChanged?.Invoke(this, s_indexerPropertyChangedEventArgs);
CollectionChanged?.Invoke(this, args);
}
}
Expand Down
7 changes: 5 additions & 2 deletions Source/ReactiveProperty.R3/ReadOnlyReactiveCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ namespace Reactive.Bindings.R3;
/// <typeparam name="T">Element type.</typeparam>
public sealed class ReadOnlyReactiveCollection<T> : ReadOnlyObservableCollection<T>, IDisposable
{
private static readonly PropertyChangedEventArgs s_countPropertyChangedEventArgs = new(nameof(Count));
private static readonly PropertyChangedEventArgs s_indexerPropertyChangedEventArgs = new("Item[]");

private readonly object _syncRoot = new();
private readonly ObservableCollection<T> _source;
private readonly bool _disposeElement;
Expand Down Expand Up @@ -145,8 +148,8 @@ private void ApplyCollectionChangedCore(CollectionChanged<T> collectionChanged)
}
}

OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count)));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnPropertyChanged(s_countPropertyChangedEventArgs);
OnPropertyChanged(s_indexerPropertyChangedEventArgs);
OnCollectionChanged(eventArgs);
}

Expand Down
48 changes: 41 additions & 7 deletions Source/ReactiveProperty.R3/ValidatableReactiveProperty.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,17 @@ namespace Reactive.Bindings.R3;
/// <typeparam name="T">Value type.</typeparam>
public sealed class ValidatableReactiveProperty<T> : Observable<T>, INotifyPropertyChanged, INotifyDataErrorInfo, IDisposable
{
private static readonly PropertyChangedEventArgs s_valuePropertyChangedEventArgs = new(nameof(Value));
private static readonly PropertyChangedEventArgs s_errorMessagePropertyChangedEventArgs = new(nameof(ErrorMessage));
private static readonly PropertyChangedEventArgs s_hasErrorsPropertyChangedEventArgs = new(nameof(HasErrors));

private readonly ReactiveProperty<T> _property;
private readonly IEqualityComparer<T> _equalityComparer;
private readonly object _validationSyncRoot = new();
private readonly ReactiveProperty<IReadOnlyList<string>> _errors = new(Array.Empty<string>());
private readonly ReactiveProperty<bool> _hasErrors = new(false);
private readonly Subject<T> _validationTrigger = new();
private readonly List<(int Slot, Func<T, IEnumerable<string>?> Validate)> _validators = new();
private (int Slot, Func<T, IEnumerable<string>?> Validate)[] _validators = [];
private readonly List<string[]> _validationErrors = new();
private readonly List<IDisposable> _subscriptions = new();
private readonly bool _ignoreInitialValidationError;
Expand Down Expand Up @@ -60,7 +64,7 @@ public T Value
_hasChangedValue = true;
_property.Value = value;
ValidateAndNotify(value);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
PropertyChanged?.Invoke(this, s_valuePropertyChangedEventArgs);
}
}

Expand Down Expand Up @@ -134,7 +138,11 @@ public ValidatableReactiveProperty<T> SetValidateNotifyError(Func<T, IEnumerable
lock (_validationSyncRoot)
{
var slot = AddValidationSlot();
_validators.Add((slot, validate));
var validators = _validators;
var nextValidators = new (int Slot, Func<T, IEnumerable<string>?> Validate)[validators.Length + 1];
Array.Copy(validators, nextValidators, validators.Length);
nextValidators[validators.Length] = (slot, validate);
_validators = nextValidators;
}

ValidateAfterRegistration();
Expand Down Expand Up @@ -285,7 +293,7 @@ private void Validate(T value)
(int Slot, Func<T, IEnumerable<string>?> Validate)[] validators;
lock (_validationSyncRoot)
{
validators = [.. _validators];
validators = _validators;
}

if (validators.Length == 0)
Expand All @@ -309,7 +317,13 @@ private void SetErrors(int slot, IEnumerable<string> errors)
{
lock (_validationSyncRoot)
{
_validationErrors[slot] = [.. errors];
string[] nextErrors = [.. errors];
if (_validationErrors[slot].SequenceEqual(nextErrors) && ErrorsMatchSlots())
{
return;
}

_validationErrors[slot] = nextErrors;
string[] next = [.. _validationErrors.SelectMany(static x => x)];
var previousHasErrors = _hasErrors.Value;
if (_errors.Value.SequenceEqual(next))
Expand All @@ -320,12 +334,32 @@ private void SetErrors(int slot, IEnumerable<string> errors)
_errors.Value = next;
_hasErrors.Value = next.Length != 0;
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Value)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ErrorMessage)));
PropertyChanged?.Invoke(this, s_errorMessagePropertyChangedEventArgs);
if (previousHasErrors != _hasErrors.Value)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HasErrors)));
PropertyChanged?.Invoke(this, s_hasErrorsPropertyChangedEventArgs);
}
}
}

private bool ErrorsMatchSlots()
{
var current = _errors.Value;
var index = 0;
foreach (var errors in _validationErrors)
{
foreach (var error in errors)
{
if (index >= current.Count || !EqualityComparer<string>.Default.Equals(error, current[index]))
{
return false;
}

index++;
}
}

return index == current.Count;
}

private static string[] ToErrorMessages(IEnumerable? errors)
Expand Down
Loading
Loading