From 290ac63c4adf7e99a563569cdde0dc8212f90ddf Mon Sep 17 00:00:00 2001
From: Glenn Watson <5834289+glennawatson@users.noreply.github.com>
Date: Tue, 1 Dec 2026 20:44:36 +1100
Subject: [PATCH 001/144] fix(views): rebuild list views on retained
notifications
- add CsCheck fuzz harness and filtered, sorted, grouped and dynamic fuzz tests
- ViewChangeBuffer retains raw notifications with version coverage and head verification
- filtered view tracks membership so inserts, moves and updates keep source order
- sorted view uses binary search and stable rebuild, grouped view re-keys items
- ViewDispatcher dispatches zero throttle directly and coalesces windows
---
src/Directory.Packages.props | 1 +
.../Internal/BatchObservableCollection.cs | 83 ++++
.../Internal/FilteredViewBufferState.cs | 88 ----
.../Internal/FilteredViewEngine.cs | 318 ++++++++++++++
.../Internal/FilteredViewReconciler.cs | 241 -----------
src/ReactiveList/Internal/GroupSlot.cs | 18 +
.../Internal/GroupedViewEngine.cs | 298 +++++++++++++
src/ReactiveList/Internal/IViewMirrorSink.cs | 48 +++
.../Internal/PendingNotification.cs | 15 +
src/ReactiveList/Internal/ProjectionRules.cs | 19 +
.../Internal/ReactiveListScheduler.cs | 9 +
src/ReactiveList/Internal/SortedViewEngine.cs | 208 +++++++++
src/ReactiveList/Internal/SourceSnapshot.cs | 15 +
src/ReactiveList/Internal/StableMergeSort.cs | 118 ++++++
src/ReactiveList/Internal/ViewDispatcher.cs | 109 +++++
src/ReactiveList/Internal/ViewMirrorPump.cs | 197 +++++++++
.../Views/DynamicFilteredReactiveView.cs | 168 ++------
.../Views/FilteredReactiveView.cs | 138 +-----
src/ReactiveList/Views/GroupedReactiveView.cs | 334 +--------------
src/ReactiveList/Views/SortedReactiveView.cs | 247 +----------
src/ReactiveList/Views/ViewChangeBuffer.cs | 393 ++++++++++++++----
.../ReactiveList.Reactive.Tests.csproj | 13 +
.../DynamicViewFuzzTests.cs | 88 ++++
.../GroupedReactiveViewFuzzTests.cs | 79 ++++
.../InternalDeduplicationHelpersTests.cs | 68 +--
.../ReactiveList.Tests.csproj | 4 +
.../ReactiveViewFuzzTests.cs | 98 +++++
.../ReactiveList.Tests/RecordingMirrorSink.cs | 42 ++
.../SortedReactiveViewFuzzTests.cs | 78 ++++
.../ViewChangeBufferTests.cs | 97 +++--
.../ReactiveList.Tests/ViewCoverageTests.cs | 8 +-
src/tests/ReactiveList.Tests/ViewFuzzKind.cs | 54 +++
src/tests/ReactiveList.Tests/ViewFuzzOp.cs | 12 +
.../ReactiveList.Tests/ViewFuzzSupport.cs | 295 +++++++++++++
34 files changed, 2705 insertions(+), 1296 deletions(-)
create mode 100644 src/ReactiveList/Internal/BatchObservableCollection.cs
delete mode 100644 src/ReactiveList/Internal/FilteredViewBufferState.cs
create mode 100644 src/ReactiveList/Internal/FilteredViewEngine.cs
delete mode 100644 src/ReactiveList/Internal/FilteredViewReconciler.cs
create mode 100644 src/ReactiveList/Internal/GroupSlot.cs
create mode 100644 src/ReactiveList/Internal/GroupedViewEngine.cs
create mode 100644 src/ReactiveList/Internal/IViewMirrorSink.cs
create mode 100644 src/ReactiveList/Internal/PendingNotification.cs
create mode 100644 src/ReactiveList/Internal/ProjectionRules.cs
create mode 100644 src/ReactiveList/Internal/SortedViewEngine.cs
create mode 100644 src/ReactiveList/Internal/SourceSnapshot.cs
create mode 100644 src/ReactiveList/Internal/StableMergeSort.cs
create mode 100644 src/ReactiveList/Internal/ViewDispatcher.cs
create mode 100644 src/ReactiveList/Internal/ViewMirrorPump.cs
create mode 100644 src/tests/ReactiveList.Tests/DynamicViewFuzzTests.cs
create mode 100644 src/tests/ReactiveList.Tests/GroupedReactiveViewFuzzTests.cs
create mode 100644 src/tests/ReactiveList.Tests/ReactiveViewFuzzTests.cs
create mode 100644 src/tests/ReactiveList.Tests/RecordingMirrorSink.cs
create mode 100644 src/tests/ReactiveList.Tests/SortedReactiveViewFuzzTests.cs
create mode 100644 src/tests/ReactiveList.Tests/ViewFuzzKind.cs
create mode 100644 src/tests/ReactiveList.Tests/ViewFuzzOp.cs
create mode 100644 src/tests/ReactiveList.Tests/ViewFuzzSupport.cs
diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props
index 32e4ab02..6945c583 100644
--- a/src/Directory.Packages.props
+++ b/src/Directory.Packages.props
@@ -13,6 +13,7 @@
+
diff --git a/src/ReactiveList/Internal/BatchObservableCollection.cs b/src/ReactiveList/Internal/BatchObservableCollection.cs
new file mode 100644
index 00000000..9e09dc1e
--- /dev/null
+++ b/src/ReactiveList/Internal/BatchObservableCollection.cs
@@ -0,0 +1,83 @@
+// Copyright (c) ReactiveUI and Contributors. All rights reserved.
+// ReactiveUI and Contributors licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for full license information.
+
+#if REACTIVELIST_REACTIVE
+namespace ReactiveList.Reactive.Internal;
+#else
+namespace ReactiveList.Internal;
+#endif
+
+/// An observable collection that can replace its contents with a single reset notification.
+/// The element type.
+internal sealed class BatchObservableCollection : ObservableCollection
+ where T : notnull
+{
+ /// The number of changed positions above which the contents are replaced with one reset notification.
+ internal const int ResetThreshold = 32;
+
+ /// The cached count change notification.
+ private static readonly PropertyChangedEventArgs CountChangedArgs = new(nameof(Count));
+
+ /// The cached indexer change notification.
+ private static readonly PropertyChangedEventArgs IndexerChangedArgs = new("Item[]");
+
+ /// The cached reset notification.
+ private static readonly NotifyCollectionChangedEventArgs ResetArgs = new(NotifyCollectionChangedAction.Reset);
+
+ /// Edits the collection until it holds the target sequence, replacing it outright when many positions differ.
+ /// The desired contents.
+ internal void ReconcileTo(List target)
+ {
+ var differences = 0;
+ var limit = Math.Min(target.Count, Count);
+ for (var i = 0; i < limit; i++)
+ {
+ if (!ViewChangeBuffer.SameItem(this[i], target[i]))
+ {
+ differences++;
+ }
+ }
+
+ differences += Math.Abs(target.Count - Count);
+ if (differences > ResetThreshold)
+ {
+ ReplaceAll(target);
+ return;
+ }
+
+ for (var i = 0; i < limit; i++)
+ {
+ if (!ViewChangeBuffer.SameItem(this[i], target[i]))
+ {
+ this[i] = target[i];
+ }
+ }
+
+ for (var i = limit; i < target.Count; i++)
+ {
+ Add(target[i]);
+ }
+
+ while (Count > target.Count)
+ {
+ RemoveAt(Count - 1);
+ }
+ }
+
+ /// Replaces every element with the supplied items and raises one reset notification.
+ /// The replacement items.
+ internal void ReplaceAll(List items)
+ {
+ CheckReentrancy();
+ Items.Clear();
+ for (var i = 0; i < items.Count; i++)
+ {
+ Items.Add(items[i]);
+ }
+
+ OnPropertyChanged(CountChangedArgs);
+ OnPropertyChanged(IndexerChangedArgs);
+ OnCollectionChanged(ResetArgs);
+ }
+}
diff --git a/src/ReactiveList/Internal/FilteredViewBufferState.cs b/src/ReactiveList/Internal/FilteredViewBufferState.cs
deleted file mode 100644
index 585d343d..00000000
--- a/src/ReactiveList/Internal/FilteredViewBufferState.cs
+++ /dev/null
@@ -1,88 +0,0 @@
-// Copyright (c) ReactiveUI and Contributors. All rights reserved.
-// ReactiveUI and Contributors licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for full license information.
-
-#if REACTIVELIST_REACTIVE
-namespace ReactiveList.Reactive.Internal;
-#else
-namespace ReactiveList.Internal;
-#endif
-
-/// Holds the buffered change queue, target collection, and reentrancy flags for a filtered reactive view.
-/// The non-nullable element type stored in the view.
-/// The reactive source list feeding the view.
-/// The mutable observable collection backing the public read-only view.
-/// The retained structural delta buffer synchronized with .
-internal sealed record FilteredViewBufferState(
- IReactiveList Source,
- ObservableCollection FilteredItems,
- ViewChangeBuffer Changes)
- where T : notnull
-{
- /// Tracks whether an update pass is currently delivering collection notifications.
- private int _rebuilding;
-
- /// Tracks whether a full snapshot reconciliation is pending.
- private bool _rebuildRequested;
-
- /// Tracks whether the change buffer must reset from the live source before reconciling.
- private bool _refreshFromSource;
-
- /// Gets a value indicating whether a full snapshot reconciliation is pending.
- internal bool RebuildRequested => _rebuildRequested;
-
- /// Gets a value indicating whether a live-source reset is pending.
- internal bool RefreshFromSource => _refreshFromSource;
-
- /// Gets a value indicating whether a rebuild pass is currently active.
- internal bool IsRebuilding => Volatile.Read(ref _rebuilding) != 0;
-
- /// Marks a snapshot rebuild as pending.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal void MarkRebuildRequested() => _rebuildRequested = true;
-
- /// Marks both a live-source reset and snapshot rebuild as pending.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal void MarkRefreshFromSource()
- {
- _refreshFromSource = true;
- _rebuildRequested = true;
- }
-
- /// Consumes and clears the pending live-source refresh flag.
- /// when a live-source reset was pending; otherwise, .
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal bool ConsumeRefreshFromSource()
- {
- if (!_refreshFromSource)
- {
- return false;
- }
-
- _refreshFromSource = false;
- return true;
- }
-
- /// Consumes and clears the pending snapshot rebuild flag.
- /// when a snapshot rebuild was pending; otherwise, .
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal bool ConsumeRebuildRequested()
- {
- if (!_rebuildRequested)
- {
- return false;
- }
-
- _rebuildRequested = false;
- return true;
- }
-
- /// Attempts to enter the single-reconciler section.
- /// when the caller acquired rebuild ownership; otherwise, .
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal bool TryBeginRebuild() => Interlocked.Exchange(ref _rebuilding, 1) == 0;
-
- /// Exits the single-reconciler section.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal void EndRebuild() => Volatile.Write(ref _rebuilding, 0);
-}
diff --git a/src/ReactiveList/Internal/FilteredViewEngine.cs b/src/ReactiveList/Internal/FilteredViewEngine.cs
new file mode 100644
index 00000000..cfca5008
--- /dev/null
+++ b/src/ReactiveList/Internal/FilteredViewEngine.cs
@@ -0,0 +1,318 @@
+// Copyright (c) ReactiveUI and Contributors. All rights reserved.
+// ReactiveUI and Contributors licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for full license information.
+
+#if REACTIVELIST_REACTIVE
+namespace ReactiveList.Reactive.Internal;
+#else
+namespace ReactiveList.Internal;
+#endif
+
+/// Maintains an ordered, filtered projection of a reactive list from its retained notifications.
+/// The non-nullable element type.
+internal sealed class FilteredViewEngine : IViewMirrorSink, IDisposable
+ where T : notnull
+{
+ /// Drains retained source notifications into this engine.
+ private readonly ViewMirrorPump _pump;
+
+ /// Whether each mirror item is currently part of the projection.
+ private readonly List _flags = [];
+
+ /// The active filter.
+ private Func _filter;
+
+ /// The filter waiting to be applied by the next drain.
+ private Func? _pendingFilter;
+
+ /// Initializes a new instance of the class.
+ /// The source to project.
+ /// The initial filter.
+ internal FilteredViewEngine(IReactiveSource source, Func filter)
+ {
+ ThrowHelper.ThrowIfNull(filter);
+
+ _filter = filter;
+ _pump = new(source);
+ Filtered = [];
+ Items = new(Filtered);
+ CollectionChanges = FacadeNotificationHelper.ObserveCollectionChanges(Filtered);
+ MirrorReset();
+ }
+
+ /// Gets the observable stream of collection-change notifications.
+ internal IObservable CollectionChanges { get; }
+
+ /// Gets the observable stream of property-change notifications.
+ internal IObservable PropertyChanges => _pump.PropertyChanges;
+
+ /// Gets the read-only projection.
+ internal ReadOnlyObservableCollection Items { get; }
+
+ /// Gets the mutable projection.
+ internal BatchObservableCollection Filtered { get; }
+
+ /// Gets the retained notifications and ordered source mirror.
+ private ViewChangeBuffer Buffer => _pump.Buffer;
+
+ /// Stops observing and releases retained notifications.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void Dispose() => _pump.Dispose();
+
+ ///
+ public void ItemsInserted(int index, int count)
+ {
+ _flags.InsertRange(index, new bool[count]);
+ for (var i = index; i < index + count; i++)
+ {
+ var item = Buffer.Items[i];
+ if (!_filter(item))
+ {
+ continue;
+ }
+
+ var position = IncludedBefore(i);
+ _flags[i] = true;
+ Filtered.Insert(position, item);
+ }
+ }
+
+ ///
+ public void ItemRemoved(int index, T item)
+ {
+ if (_flags[index])
+ {
+ Filtered.RemoveAt(IncludedBefore(index));
+ }
+
+ _flags.RemoveAt(index);
+ }
+
+ ///
+ public void ItemReplaced(int index, T previous, T current)
+ {
+ var included = false;
+ try
+ {
+ included = _filter(current);
+ }
+ finally
+ {
+ SetMembership(index, current, included);
+ }
+ }
+
+ ///
+ public void ItemMoved(int oldIndex, int newIndex, T item)
+ {
+ var included = _flags[oldIndex];
+ var oldPosition = included ? IncludedBefore(oldIndex) : -1;
+ _flags.RemoveAt(oldIndex);
+ _flags.Insert(newIndex, included);
+ if (!included)
+ {
+ return;
+ }
+
+ var newPosition = IncludedBefore(newIndex);
+ if (newPosition != oldPosition)
+ {
+ Filtered.Move(oldPosition, newPosition);
+ }
+ }
+
+ ///
+ public void ItemRefreshed(int index, T item)
+ {
+ var included = false;
+ try
+ {
+ included = _filter(item);
+ }
+ finally
+ {
+ SetMembership(index, item, included);
+ }
+ }
+
+ ///
+ public void MirrorCleared()
+ {
+ _flags.Clear();
+ Filtered.Clear();
+ }
+
+ ///
+ public void MirrorReset()
+ {
+ var items = Buffer.Items;
+ _flags.Clear();
+ for (var i = 0; i < items.Count; i++)
+ {
+ _flags.Add(false);
+ }
+
+ for (var i = 0; i < items.Count; i++)
+ {
+ _flags[i] = _filter(items[i]);
+ }
+
+ Filtered.ReconcileTo(Project());
+ }
+
+ /// Queues a filter replacement.
+ /// The new filter.
+ internal void SetFilter(Func filter)
+ {
+ Volatile.Write(ref _pendingFilter, filter);
+ _pump.RequestDrain();
+ }
+
+ /// Starts observing the source.
+ /// The coalescing window.
+ /// The scheduler that applies changes.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal void Start(TimeSpan throttle, ISequencer scheduler) =>
+ _pump.Start(this, throttle, scheduler, ApplyQueuedChanges, HasQueuedChanges);
+
+ /// Rebuilds the projection from the live source on the calling thread.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal void Refresh() => _pump.Refresh();
+
+ /// Applies a queued filter replacement.
+ /// when the projection changed.
+ private bool ApplyQueuedChanges()
+ {
+ if (Interlocked.Exchange(ref _pendingFilter, null) is not { } filter)
+ {
+ return false;
+ }
+
+ _filter = filter;
+ ApplyFilterToMirror();
+ return true;
+ }
+
+ /// Gets whether a filter replacement is queued.
+ /// when a filter is waiting.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private bool HasQueuedChanges() => Volatile.Read(ref _pendingFilter) is not null;
+
+ /// Counts the projected items that precede a mirror index.
+ /// The mirror index.
+ /// The projection position of the first included item at or after the index.
+ private int IncludedBefore(int index)
+ {
+ var count = _flags.Count;
+ var result = 0;
+ if (index <= count >> 1)
+ {
+ for (var i = 0; i < index; i++)
+ {
+ if (_flags[i])
+ {
+ result++;
+ }
+ }
+
+ return result;
+ }
+
+ var after = 0;
+ for (var i = index; i < count; i++)
+ {
+ if (_flags[i])
+ {
+ after++;
+ }
+ }
+
+ return Filtered.Count - after;
+ }
+
+ /// Updates one mirror item's membership and the projection to match.
+ /// The mirror index.
+ /// The current item.
+ /// Whether the item should be projected.
+ private void SetMembership(int index, T item, bool included)
+ {
+ var was = _flags[index];
+ if (was && included)
+ {
+ Filtered[IncludedBefore(index)] = item;
+ }
+ else if (was)
+ {
+ Filtered.RemoveAt(IncludedBefore(index));
+ _flags[index] = false;
+ }
+ else if (included)
+ {
+ var position = IncludedBefore(index);
+ _flags[index] = true;
+ Filtered.Insert(position, item);
+ }
+ }
+
+ /// Re-evaluates the filter for every mirror item and edits the projection in place.
+ private void ApplyFilterToMirror()
+ {
+ var items = Buffer.Items;
+ var newFlags = new bool[items.Count];
+ var flips = 0;
+ for (var i = 0; i < items.Count; i++)
+ {
+ newFlags[i] = _filter(items[i]);
+ if (newFlags[i] != _flags[i])
+ {
+ flips++;
+ }
+ }
+
+ if (flips > BatchObservableCollection.ResetThreshold)
+ {
+ _flags.Clear();
+ _flags.AddRange(newFlags);
+ Filtered.ReplaceAll(Project());
+ return;
+ }
+
+ var position = 0;
+ for (var i = 0; i < items.Count; i++)
+ {
+ var was = _flags[i];
+ if (was && newFlags[i])
+ {
+ position++;
+ }
+ else if (was)
+ {
+ Filtered.RemoveAt(position);
+ }
+ else if (newFlags[i])
+ {
+ Filtered.Insert(position, items[i]);
+ position++;
+ }
+
+ _flags[i] = newFlags[i];
+ }
+ }
+
+ /// Builds the projected sequence from the mirror and flags.
+ /// The included items in source order.
+ private List Project()
+ {
+ var items = Buffer.Items;
+ var result = new List(Filtered.Count);
+ for (var i = 0; i < items.Count; i++)
+ {
+ if (_flags[i])
+ {
+ result.Add(items[i]);
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/src/ReactiveList/Internal/FilteredViewReconciler.cs b/src/ReactiveList/Internal/FilteredViewReconciler.cs
deleted file mode 100644
index 36d03e2c..00000000
--- a/src/ReactiveList/Internal/FilteredViewReconciler.cs
+++ /dev/null
@@ -1,241 +0,0 @@
-// Copyright (c) ReactiveUI and Contributors. All rights reserved.
-// ReactiveUI and Contributors licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for full license information.
-
-#if REACTIVELIST_REACTIVE
-namespace ReactiveList.Reactive.Internal;
-#else
-namespace ReactiveList.Internal;
-#endif
-
-/// Reconciles buffered source deltas and snapshots into filtered reactive view collections.
-internal static class FilteredViewReconciler
-{
- /// Subscribes a filtered view buffer to source change sets with optional throttling.
- /// The non-nullable element type stored in the view.
- /// The filtered view buffer state.
- /// The debounce window before dispatching retained changes, or .
- /// The sequencer on which view updates execute.
- /// Invoked on when retained deltas are ready.
- /// The active stream subscription.
- internal static IDisposable SubscribeChanges(
- FilteredViewBufferState state,
- TimeSpan throttle,
- ISequencer scheduler,
- Action onSourceChanged)
- where T : notnull
- {
- ThrowHelper.ThrowIfNull(state);
- ThrowHelper.ThrowIfNull(scheduler);
- ThrowHelper.ThrowIfNull(onSourceChanged);
-
- var updates = state.Source.Stream
- .ToChangeSets()
- .Map(changes => state.Changes.Capture(changes, state.Source.Version));
- if (throttle > TimeSpan.Zero)
- {
- updates = updates.Throttle(throttle);
- }
-
- return updates
- .ObserveOn(scheduler)
- .Subscribe(_ => onSourceChanged());
- }
-
- /// Marks a snapshot rebuild as pending and drains buffered updates under the specified predicate.
- /// The non-nullable element type stored in the view.
- /// The filtered view buffer state.
- /// The active filter predicate.
- internal static void RequestRebuild(FilteredViewBufferState state, Func filter)
- where T : notnull
- {
- ThrowHelper.ThrowIfNull(state);
- ThrowHelper.ThrowIfNull(filter);
-
- state.MarkRebuildRequested();
- ApplyUpdates(state, filter);
- }
-
- /// Marks both a live-source reset and snapshot rebuild as pending, then drains buffered updates.
- /// The non-nullable element type stored in the view.
- /// The filtered view buffer state.
- /// The active filter predicate.
- internal static void RefreshFromSource(FilteredViewBufferState state, Func filter)
- where T : notnull
- {
- ThrowHelper.ThrowIfNull(state);
- ThrowHelper.ThrowIfNull(filter);
-
- state.MarkRefreshFromSource();
- ApplyUpdates(state, filter);
- }
-
- /// Drains retained source deltas and deferred rebuild requests while preventing reentrant corruption.
- /// The non-nullable element type stored in the view.
- /// The filtered view buffer state.
- /// The active filter predicate.
- internal static void ApplyUpdates(FilteredViewBufferState state, Func filter)
- where T : notnull
- {
- ThrowHelper.ThrowIfNull(state);
- ThrowHelper.ThrowIfNull(filter);
-
- if (!state.TryBeginRebuild())
- {
- return;
- }
-
- try
- {
- do
- {
- if (state.ConsumeRefreshFromSource())
- {
- state.Changes.Reset(state.Source);
- }
-
- while (state.Changes.TryTake(out var changes))
- {
- for (var i = 0; i < changes.Count; i++)
- {
- var change = changes[i];
- state.Changes.Apply(change);
- ProcessChange(state, change, filter);
- }
- }
-
- if (state.ConsumeRebuildRequested())
- {
- ReconcileSnapshot(state.FilteredItems, state.Changes.Items, filter);
- }
- }
- while (state.RebuildRequested || state.RefreshFromSource || state.Changes.HasPending);
- }
- finally
- {
- state.EndRebuild();
- }
- }
-
- /// Applies a single structural delta to the filtered items collection.
- /// The non-nullable element type stored in the view.
- /// The filtered view buffer state.
- /// The delta to process.
- /// The active filter predicate.
- internal static void ProcessChange(
- FilteredViewBufferState state,
- Change change,
- Func filter)
- where T : notnull
- {
- ThrowHelper.ThrowIfNull(state);
- ThrowHelper.ThrowIfNull(filter);
-
- if (change.Reason is ChangeReason.Add)
- {
- if (filter(change.Current))
- {
- state.FilteredItems.Add(change.Current);
- }
- }
- else if (change.Reason is ChangeReason.Remove)
- {
- var index = ViewChangeBuffer.FindIndex(state.FilteredItems, change.Current);
- if (index >= 0)
- {
- state.FilteredItems.RemoveAt(index);
- }
- }
- else if (change.Reason is ChangeReason.Update)
- {
- UpdateItem(state.FilteredItems, change, filter);
- }
- else if (change.Reason is ChangeReason.Clear)
- {
- state.FilteredItems.Clear();
- }
- else if (change.Reason is ChangeReason.Move or ChangeReason.Refresh)
- {
- ReconcileSnapshot(state.FilteredItems, state.Changes.Items, filter);
- }
- }
-
- /// Updates an item in place, inserts it, or removes it while preserving existing filtered order.
- /// The non-nullable element type stored in the view.
- /// The mutable filtered items collection.
- /// The update delta.
- /// The active filter predicate.
- internal static void UpdateItem(
- ObservableCollection filteredItems,
- Change change,
- Func filter)
- where T : notnull
- {
- ThrowHelper.ThrowIfNull(filteredItems);
- ThrowHelper.ThrowIfNull(filter);
-
- var index = change.Previous is null ? -1 : ViewChangeBuffer.FindIndex(filteredItems, change.Previous);
- var included = filter(change.Current);
- if (index < 0)
- {
- if (included)
- {
- filteredItems.Add(change.Current);
- }
-
- return;
- }
-
- if (!included)
- {
- filteredItems.RemoveAt(index);
- return;
- }
-
- filteredItems[index] = change.Current;
- }
-
- /// Reconciles to match filtered by .
- /// The non-nullable element type stored in the view.
- /// The mutable filtered items collection.
- /// The ordered source snapshot.
- /// The active filter predicate.
- internal static void ReconcileSnapshot(
- ObservableCollection filteredItems,
- List sourceItems,
- Func filter)
- where T : notnull
- {
- ThrowHelper.ThrowIfNull(filteredItems);
- ThrowHelper.ThrowIfNull(sourceItems);
- ThrowHelper.ThrowIfNull(filter);
-
- var index = 0;
- for (var i = 0; i < sourceItems.Count; i++)
- {
- var item = sourceItems[i];
- if (!filter(item))
- {
- continue;
- }
-
- if (index == filteredItems.Count)
- {
- filteredItems.Add(item);
- }
- else if (typeof(T).IsValueType
- ? !EqualityComparer.Default.Equals(filteredItems[index], item)
- : !ReferenceEquals(filteredItems[index], item))
- {
- filteredItems[index] = item;
- }
-
- index++;
- }
-
- while (filteredItems.Count > index)
- {
- filteredItems.RemoveAt(filteredItems.Count - 1);
- }
- }
-}
diff --git a/src/ReactiveList/Internal/GroupSlot.cs b/src/ReactiveList/Internal/GroupSlot.cs
new file mode 100644
index 00000000..f1685d07
--- /dev/null
+++ b/src/ReactiveList/Internal/GroupSlot.cs
@@ -0,0 +1,18 @@
+// Copyright (c) ReactiveUI and Contributors. All rights reserved.
+// ReactiveUI and Contributors licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for full license information.
+
+#if REACTIVELIST_REACTIVE
+namespace ReactiveList.Reactive.Internal;
+#else
+namespace ReactiveList.Internal;
+#endif
+
+/// One group of a grouped view with its mutable members and public wrapper.
+/// The grouping key type.
+/// The member type.
+/// The group key.
+/// The mutable members.
+/// The public group wrapper.
+internal sealed record GroupSlot(TKey Key, ObservableCollection Items, ReactiveGroup Group)
+ where TKey : notnull;
diff --git a/src/ReactiveList/Internal/GroupedViewEngine.cs b/src/ReactiveList/Internal/GroupedViewEngine.cs
new file mode 100644
index 00000000..9fb7fba9
--- /dev/null
+++ b/src/ReactiveList/Internal/GroupedViewEngine.cs
@@ -0,0 +1,298 @@
+// Copyright (c) ReactiveUI and Contributors. All rights reserved.
+// ReactiveUI and Contributors licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for full license information.
+
+#if REACTIVELIST_REACTIVE
+namespace ReactiveList.Reactive.Internal;
+#else
+namespace ReactiveList.Internal;
+#endif
+
+/// Maintains groups of a reactive list. Members keep arrival order when inserted and source order when rebuilt.
+/// The non-nullable element type.
+/// The non-nullable grouping key type.
+internal sealed class GroupedViewEngine : IViewMirrorSink, IDisposable
+ where T : notnull
+ where TKey : notnull
+{
+ /// Drains retained source notifications into this engine.
+ private readonly ViewMirrorPump _pump;
+
+ /// Extracts the grouping key for each source item.
+ private readonly Func _keySelector;
+
+ /// The group for each key.
+ private readonly Dictionary> _slots = [];
+
+ /// The observable collection backing the public group view.
+ private readonly ObservableCollection> _groupCollection = [];
+
+ /// Initializes a new instance of the class.
+ /// The source to group.
+ /// Extracts the grouping key.
+ internal GroupedViewEngine(IReactiveSource source, Func keySelector)
+ {
+ ThrowHelper.ThrowIfNull(keySelector);
+
+ _keySelector = keySelector;
+ _pump = new(source);
+ Groups = new(_groupCollection);
+ CollectionChanges = FacadeNotificationHelper.ObserveCollectionChanges(_groupCollection);
+ MirrorReset();
+ }
+
+ /// Gets the observable stream of collection-change notifications.
+ internal IObservable CollectionChanges { get; }
+
+ /// Gets the observable stream of property-change notifications.
+ internal IObservable PropertyChanges => _pump.PropertyChanges;
+
+ /// Gets the read-only group collection.
+ internal ReadOnlyObservableCollection> Groups { get; }
+
+ /// Gets the number of groups.
+ internal int Count => _slots.Count;
+
+ /// Gets the retained notifications and ordered source mirror.
+ private ViewChangeBuffer Buffer => _pump.Buffer;
+
+ /// Stops observing and releases retained notifications.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void Dispose() => _pump.Dispose();
+
+ ///
+ public void ItemsInserted(int index, int count)
+ {
+ for (var i = index; i < index + count; i++)
+ {
+ AddToGroup(Buffer.Items[i]);
+ }
+ }
+
+ ///
+ public void ItemRemoved(int index, T item)
+ {
+ if (TryLocate(item, out var slot, out var position))
+ {
+ RemoveAt(slot, position);
+ }
+ }
+
+ ///
+ public void ItemReplaced(int index, T previous, T current)
+ {
+ if (!TryLocate(previous, out var slot, out var position))
+ {
+ AddToGroup(current);
+ return;
+ }
+
+ if (EqualityComparer.Default.Equals(slot.Key, _keySelector(current)))
+ {
+ slot.Items[position] = current;
+ return;
+ }
+
+ RemoveAt(slot, position);
+ AddToGroup(current);
+ }
+
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void ItemMoved(int oldIndex, int newIndex, T item)
+ {
+ }
+
+ ///
+ public void ItemRefreshed(int index, T item)
+ {
+ if (!TryLocate(item, out var slot, out var position))
+ {
+ AddToGroup(item);
+ return;
+ }
+
+ if (EqualityComparer.Default.Equals(slot.Key, _keySelector(item)))
+ {
+ return;
+ }
+
+ RemoveAt(slot, position);
+ AddToGroup(item);
+ }
+
+ ///
+ public void MirrorCleared()
+ {
+ _slots.Clear();
+ _groupCollection.Clear();
+ }
+
+ ///
+ public void MirrorReset()
+ {
+ MirrorCleared();
+ var items = Buffer.Items;
+ for (var i = 0; i < items.Count; i++)
+ {
+ AddToGroup(items[i]);
+ }
+ }
+
+ /// Starts observing the source.
+ /// The coalescing window.
+ /// The scheduler that applies changes.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal void Start(TimeSpan throttle, ISequencer scheduler) => _pump.Start(this, throttle, scheduler);
+
+ /// Rebuilds the groups from the live source on the calling thread.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal void Refresh() => _pump.Refresh();
+
+ /// Determines whether a group exists.
+ /// The group key.
+ /// when the group exists.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal bool ContainsKey(TKey key) => _slots.ContainsKey(key);
+
+ /// Gets the members of a group.
+ /// The group key.
+ /// The group members.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal ObservableCollection GetItems(TKey key) => _slots[key].Items;
+
+ /// Tries to get the members of a group.
+ /// The group key.
+ /// The members, or an empty list.
+ /// when the group exists.
+ internal bool TryGetValue(TKey key, out IReadOnlyList value)
+ {
+ if (_slots.TryGetValue(key, out var slot))
+ {
+ value = slot.Items;
+ return true;
+ }
+
+ value = [];
+ return false;
+ }
+
+ /// Copies the group keys.
+ /// The keys.
+ internal TKey[] SnapshotKeys()
+ {
+ var keys = new TKey[_slots.Count];
+ _slots.Keys.CopyTo(keys, 0);
+ return keys;
+ }
+
+ /// Copies the group members.
+ /// The group member lists.
+ internal IReadOnlyList[] SnapshotValues()
+ {
+ var values = new IReadOnlyList[_slots.Count];
+ var index = 0;
+ foreach (var slot in _slots.Values)
+ {
+ values[index] = slot.Items;
+ index++;
+ }
+
+ return values;
+ }
+
+ /// Copies the key and members of every group.
+ /// The group pairs.
+ internal KeyValuePair>[] SnapshotPairs()
+ {
+ var pairs = new KeyValuePair>[_slots.Count];
+ var index = 0;
+ foreach (var slot in _slots.Values)
+ {
+ pairs[index] = new(slot.Key, slot.Items);
+ index++;
+ }
+
+ return pairs;
+ }
+
+ /// Finds an occurrence of the item in a group.
+ /// The group.
+ /// The item to find.
+ /// The index, or -1.
+ private static int IndexIn(GroupSlot slot, T item)
+ {
+ for (var i = 0; i < slot.Items.Count; i++)
+ {
+ if (ViewChangeBuffer.SameItem(slot.Items[i], item))
+ {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ /// Adds an item to the group for its key, creating the group when needed.
+ /// The item to add.
+ private void AddToGroup(T item)
+ {
+ var key = _keySelector(item);
+ if (!_slots.TryGetValue(key, out var slot))
+ {
+ ObservableCollection members = [];
+ slot = new(key, members, new(key, members));
+ _slots[key] = slot;
+ _groupCollection.Add(slot.Group);
+ }
+
+ slot.Items.Add(item);
+ }
+
+ /// Removes one member and drops the group when it becomes empty.
+ /// The group.
+ /// The member index.
+ private void RemoveAt(GroupSlot slot, int position)
+ {
+ slot.Items.RemoveAt(position);
+ if (slot.Items.Count != 0)
+ {
+ return;
+ }
+
+ _ = _slots.Remove(slot.Key);
+ _ = _groupCollection.Remove(slot.Group);
+ }
+
+ /// Finds the group and index of an item, trying its current key first and scanning every group when the key changed.
+ /// The item to find.
+ /// The group that holds the item.
+ /// The index within the group.
+ /// when the item was found.
+ private bool TryLocate(T item, out GroupSlot slot, out int position)
+ {
+ if (_slots.TryGetValue(_keySelector(item), out var candidate) && IndexIn(candidate, item) is var found and >= 0)
+ {
+ slot = candidate;
+ position = found;
+ return true;
+ }
+
+ foreach (var other in _slots.Values)
+ {
+ var index = IndexIn(other, item);
+ if (index < 0)
+ {
+ continue;
+ }
+
+ slot = other;
+ position = index;
+ return true;
+ }
+
+ slot = null!;
+ position = -1;
+ return false;
+ }
+}
diff --git a/src/ReactiveList/Internal/IViewMirrorSink.cs b/src/ReactiveList/Internal/IViewMirrorSink.cs
new file mode 100644
index 00000000..08545b85
--- /dev/null
+++ b/src/ReactiveList/Internal/IViewMirrorSink.cs
@@ -0,0 +1,48 @@
+// Copyright (c) ReactiveUI and Contributors. All rights reserved.
+// ReactiveUI and Contributors licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for full license information.
+
+#if REACTIVELIST_REACTIVE
+namespace ReactiveList.Reactive.Internal;
+#else
+namespace ReactiveList.Internal;
+#endif
+
+/// Receives the structural changes a applied to its source mirror.
+/// The source item type.
+internal interface IViewMirrorSink
+ where T : notnull
+{
+ /// Items were inserted into the mirror.
+ /// The index of the first inserted item.
+ /// The number of inserted items.
+ void ItemsInserted(int index, int count);
+
+ /// One item was removed from the mirror.
+ /// The index the item occupied before removal.
+ /// The removed item.
+ void ItemRemoved(int index, T item);
+
+ /// One item in the mirror was replaced.
+ /// The index of the replaced item.
+ /// The item that was replaced.
+ /// The replacement item.
+ void ItemReplaced(int index, T previous, T current);
+
+ /// One item in the mirror moved.
+ /// The previous index.
+ /// The new index.
+ /// The moved item.
+ void ItemMoved(int oldIndex, int newIndex, T item);
+
+ /// One item in the mirror was refreshed in place.
+ /// The index of the refreshed item.
+ /// The refreshed item.
+ void ItemRefreshed(int index, T item);
+
+ /// The mirror was emptied.
+ void MirrorCleared();
+
+ /// The mirror was replaced wholesale and the sink must rebuild from it.
+ void MirrorReset();
+}
diff --git a/src/ReactiveList/Internal/PendingNotification.cs b/src/ReactiveList/Internal/PendingNotification.cs
new file mode 100644
index 00000000..5d4ecf13
--- /dev/null
+++ b/src/ReactiveList/Internal/PendingNotification.cs
@@ -0,0 +1,15 @@
+// Copyright (c) ReactiveUI and Contributors. All rights reserved.
+// ReactiveUI and Contributors licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for full license information.
+
+#if REACTIVELIST_REACTIVE
+namespace ReactiveList.Reactive.Internal;
+#else
+namespace ReactiveList.Internal;
+#endif
+
+/// A source notification retained with the source revision that produced it.
+/// The source item type.
+/// The retained notification.
+/// The source revision that produced the notification.
+internal readonly record struct PendingNotification(CacheNotify Notification, long Version);
diff --git a/src/ReactiveList/Internal/ProjectionRules.cs b/src/ReactiveList/Internal/ProjectionRules.cs
new file mode 100644
index 00000000..dfd17ddc
--- /dev/null
+++ b/src/ReactiveList/Internal/ProjectionRules.cs
@@ -0,0 +1,19 @@
+// Copyright (c) ReactiveUI and Contributors. All rights reserved.
+// ReactiveUI and Contributors licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for full license information.
+
+#if REACTIVELIST_REACTIVE
+namespace ReactiveList.Reactive.Internal;
+#else
+namespace ReactiveList.Internal;
+#endif
+
+/// Describes which items a stream projection holds and how to rebuild it from the source.
+/// The projected element type.
+/// Returns whether an item belongs in the projection.
+/// Reads the matching items from the source, or when the projection cannot rebuild itself.
+/// Returns the exact number of items the projection must hold when the source is quiet, or when unknown.
+internal sealed record ProjectionRules(
+ Func Matches,
+ Func>? Snapshot,
+ Func? ExpectedCount);
diff --git a/src/ReactiveList/Internal/ReactiveListScheduler.cs b/src/ReactiveList/Internal/ReactiveListScheduler.cs
index 43bb69a9..e7963e27 100644
--- a/src/ReactiveList/Internal/ReactiveListScheduler.cs
+++ b/src/ReactiveList/Internal/ReactiveListScheduler.cs
@@ -19,6 +19,15 @@ internal static class ReactiveListScheduler
Sequencer.CurrentThread;
#endif
+ /// Gets the scheduler that runs work inline on the calling thread.
+ /// The immediate scheduler.
+ internal static ISequencer Immediate =>
+#if REACTIVELIST_REACTIVE
+ System.Reactive.Concurrency.ImmediateScheduler.Instance;
+#else
+ Sequencer.Immediate;
+#endif
+
/// Gets the default scheduler.
internal static ISequencer Default =>
#if REACTIVELIST_REACTIVE
diff --git a/src/ReactiveList/Internal/SortedViewEngine.cs b/src/ReactiveList/Internal/SortedViewEngine.cs
new file mode 100644
index 00000000..76a6c186
--- /dev/null
+++ b/src/ReactiveList/Internal/SortedViewEngine.cs
@@ -0,0 +1,208 @@
+// Copyright (c) ReactiveUI and Contributors. All rights reserved.
+// ReactiveUI and Contributors licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for full license information.
+
+#if REACTIVELIST_REACTIVE
+namespace ReactiveList.Reactive.Internal;
+#else
+namespace ReactiveList.Internal;
+#endif
+
+/// Maintains a sorted projection of a reactive list. Equal items keep arrival order when inserted and source order when rebuilt.
+/// The non-nullable element type.
+internal sealed class SortedViewEngine : IViewMirrorSink, IDisposable
+ where T : notnull
+{
+ /// Drains retained source notifications into this engine.
+ private readonly ViewMirrorPump _pump;
+
+ /// The comparer that orders the projection.
+ private readonly IComparer _comparer;
+
+ /// Initializes a new instance of the class.
+ /// The source to project.
+ /// The comparer that orders the projection.
+ internal SortedViewEngine(IReactiveSource source, IComparer comparer)
+ {
+ ThrowHelper.ThrowIfNull(comparer);
+
+ _comparer = comparer;
+ _pump = new(source);
+ Sorted = [];
+ Items = new(Sorted);
+ CollectionChanges = FacadeNotificationHelper.ObserveCollectionChanges(Sorted);
+ MirrorReset();
+ }
+
+ /// Gets the observable stream of collection-change notifications.
+ internal IObservable CollectionChanges { get; }
+
+ /// Gets the observable stream of property-change notifications.
+ internal IObservable PropertyChanges => _pump.PropertyChanges;
+
+ /// Gets the read-only projection.
+ internal ReadOnlyObservableCollection Items { get; }
+
+ /// Gets the mutable projection.
+ internal BatchObservableCollection Sorted { get; }
+
+ /// Gets the retained notifications and ordered source mirror.
+ private ViewChangeBuffer Buffer => _pump.Buffer;
+
+ /// Stops observing and releases retained notifications.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void Dispose() => _pump.Dispose();
+
+ ///
+ public void ItemsInserted(int index, int count)
+ {
+ if (count > BatchObservableCollection.ResetThreshold)
+ {
+ MirrorReset();
+ return;
+ }
+
+ for (var i = index; i < index + count; i++)
+ {
+ InsertSorted(Buffer.Items[i]);
+ }
+ }
+
+ ///
+ public void ItemRemoved(int index, T item)
+ {
+ var position = LocateSorted(item);
+ if (position >= 0)
+ {
+ Sorted.RemoveAt(position);
+ }
+ }
+
+ ///
+ public void ItemReplaced(int index, T previous, T current)
+ {
+ var position = LocateSorted(previous);
+ if (position >= 0 && _comparer.Compare(previous, current) == 0)
+ {
+ Sorted[position] = current;
+ return;
+ }
+
+ if (position >= 0)
+ {
+ Sorted.RemoveAt(position);
+ }
+
+ InsertSorted(current);
+ }
+
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void ItemMoved(int oldIndex, int newIndex, T item)
+ {
+ }
+
+ ///
+ public void ItemRefreshed(int index, T item)
+ {
+ var position = LocateSorted(item);
+ if (position < 0)
+ {
+ InsertSorted(item);
+ return;
+ }
+
+ var after = position + 1 < Sorted.Count ? _comparer.Compare(item, Sorted[position + 1]) : -1;
+ var before = position > 0 ? _comparer.Compare(Sorted[position - 1], item) : -1;
+ if (after <= 0 && before <= 0)
+ {
+ return;
+ }
+
+ Sorted.RemoveAt(position);
+ InsertSorted(item);
+ }
+
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void MirrorCleared() => Sorted.Clear();
+
+ ///
+ public void MirrorReset()
+ {
+ var items = Buffer.Items.ToArray();
+ StableMergeSort.Sort(items, _comparer);
+ Sorted.ReconcileTo([.. items]);
+ }
+
+ /// Starts observing the source.
+ /// The coalescing window.
+ /// The scheduler that applies changes.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal void Start(TimeSpan throttle, ISequencer scheduler) => _pump.Start(this, throttle, scheduler);
+
+ /// Rebuilds the projection from the live source on the calling thread.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal void Refresh() => _pump.Refresh();
+
+ /// Inserts an item after every item that compares less than or equal to it.
+ /// The item to insert.
+ private void InsertSorted(T item)
+ {
+ var low = 0;
+ var high = Sorted.Count;
+ while (low < high)
+ {
+ var middle = low + ((high - low) >> 1);
+ if (_comparer.Compare(Sorted[middle], item) <= 0)
+ {
+ low = middle + 1;
+ }
+ else
+ {
+ high = middle;
+ }
+ }
+
+ Sorted.Insert(low, item);
+ }
+
+ /// Finds an occurrence of the item, using the comparer first and a linear scan when the order is not trustworthy.
+ /// The item to find.
+ /// The projection index, or -1.
+ private int LocateSorted(T item)
+ {
+ var low = 0;
+ var high = Sorted.Count;
+ while (low < high)
+ {
+ var middle = low + ((high - low) >> 1);
+ if (_comparer.Compare(Sorted[middle], item) < 0)
+ {
+ low = middle + 1;
+ }
+ else
+ {
+ high = middle;
+ }
+ }
+
+ for (var i = low; i < Sorted.Count && _comparer.Compare(Sorted[i], item) == 0; i++)
+ {
+ if (ViewChangeBuffer.SameItem(Sorted[i], item))
+ {
+ return i;
+ }
+ }
+
+ for (var i = 0; i < Sorted.Count; i++)
+ {
+ if (ViewChangeBuffer.SameItem(Sorted[i], item))
+ {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+}
diff --git a/src/ReactiveList/Internal/SourceSnapshot.cs b/src/ReactiveList/Internal/SourceSnapshot.cs
new file mode 100644
index 00000000..e91d3d0e
--- /dev/null
+++ b/src/ReactiveList/Internal/SourceSnapshot.cs
@@ -0,0 +1,15 @@
+// Copyright (c) ReactiveUI and Contributors. All rights reserved.
+// ReactiveUI and Contributors licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for full license information.
+
+#if REACTIVELIST_REACTIVE
+namespace ReactiveList.Reactive.Internal;
+#else
+namespace ReactiveList.Internal;
+#endif
+
+/// The matching items read from a source together with the source size at the same moment.
+/// The projected element type.
+/// The matching items.
+/// The number of items the source held, matching or not.
+internal readonly record struct SourceSnapshot(List Items, int SourceCount);
diff --git a/src/ReactiveList/Internal/StableMergeSort.cs b/src/ReactiveList/Internal/StableMergeSort.cs
new file mode 100644
index 00000000..19d129a1
--- /dev/null
+++ b/src/ReactiveList/Internal/StableMergeSort.cs
@@ -0,0 +1,118 @@
+// Copyright (c) ReactiveUI and Contributors. All rights reserved.
+// ReactiveUI and Contributors licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for full license information.
+
+#if REACTIVELIST_REACTIVE
+namespace ReactiveList.Reactive.Internal;
+#else
+namespace ReactiveList.Internal;
+#endif
+
+/// Sorts arrays stably and never throws for inconsistent comparers.
+internal static class StableMergeSort
+{
+ /// The run length below which insertion sort is used.
+ private const int InsertionThreshold = 8;
+
+ /// Sorts the items so equal elements keep their original relative order.
+ /// The element type.
+ /// The items to sort in place.
+ /// The comparer that orders the items.
+ internal static void Sort(T[] items, IComparer comparer)
+ {
+ if (items.Length < 2)
+ {
+ return;
+ }
+
+ var scratch = new T[items.Length];
+ SortRange(items, scratch, 0, items.Length, comparer);
+ }
+
+ /// Sorts one half-open range.
+ /// The element type.
+ /// The items being sorted.
+ /// The merge buffer.
+ /// The inclusive start.
+ /// The exclusive end.
+ /// The comparer.
+ private static void SortRange(T[] items, T[] scratch, int start, int end, IComparer comparer)
+ {
+ var length = end - start;
+ if (length <= InsertionThreshold)
+ {
+ InsertionSort(items, start, end, comparer);
+ return;
+ }
+
+ var middle = start + (length >> 1);
+ SortRange(items, scratch, start, middle, comparer);
+ SortRange(items, scratch, middle, end, comparer);
+ if (comparer.Compare(items[middle - 1], items[middle]) <= 0)
+ {
+ return;
+ }
+
+ Merge(items, scratch, start, middle, end, comparer);
+ }
+
+ /// Sorts a short range by insertion.
+ /// The element type.
+ /// The items being sorted.
+ /// The inclusive start.
+ /// The exclusive end.
+ /// The comparer.
+ private static void InsertionSort(T[] items, int start, int end, IComparer comparer)
+ {
+ for (var i = start + 1; i < end; i++)
+ {
+ var value = items[i];
+ var j = i - 1;
+ while (j >= start && comparer.Compare(items[j], value) > 0)
+ {
+ items[j + 1] = items[j];
+ j--;
+ }
+
+ items[j + 1] = value;
+ }
+ }
+
+ /// Merges two adjacent sorted runs.
+ /// The element type.
+ /// The items being sorted.
+ /// The merge buffer.
+ /// The inclusive start of the left run.
+ /// The exclusive end of the left run and start of the right run.
+ /// The exclusive end of the right run.
+ /// The comparer.
+ private static void Merge(T[] items, T[] scratch, int start, int middle, int end, IComparer comparer)
+ {
+ Array.Copy(items, start, scratch, start, middle - start);
+ var left = start;
+ var right = middle;
+ var write = start;
+ while (left < middle && right < end)
+ {
+ if (comparer.Compare(items[right], scratch[left]) < 0)
+ {
+ items[write] = items[right];
+ right++;
+ }
+ else
+ {
+ items[write] = scratch[left];
+ left++;
+ }
+
+ write++;
+ }
+
+ while (left < middle)
+ {
+ items[write] = scratch[left];
+ left++;
+ write++;
+ }
+ }
+}
diff --git a/src/ReactiveList/Internal/ViewDispatcher.cs b/src/ReactiveList/Internal/ViewDispatcher.cs
new file mode 100644
index 00000000..a7c48d97
--- /dev/null
+++ b/src/ReactiveList/Internal/ViewDispatcher.cs
@@ -0,0 +1,109 @@
+// Copyright (c) ReactiveUI and Contributors. All rights reserved.
+// ReactiveUI and Contributors licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for full license information.
+
+#if REACTIVELIST_REACTIVE
+namespace ReactiveList.Reactive.Internal;
+#else
+namespace ReactiveList.Internal;
+#endif
+
+/// Coalesces source notifications into at most one pending drain on the view scheduler.
+internal sealed class ViewDispatcher
+{
+ /// The scheduler that runs the drain callback.
+ private readonly ISequencer _scheduler;
+
+ /// The coalescing window, or zero to drain as soon as possible.
+ private readonly TimeSpan _throttle;
+
+ /// The callback that applies pending work.
+ private readonly Action _drain;
+
+ /// Whether the scheduler runs work inline on the calling thread.
+ private readonly bool _immediate;
+
+ /// The callback run on the view scheduler.
+ private readonly Action _run;
+
+ /// The callback run when the coalescing window elapses.
+ private readonly Action _onWindowElapsed;
+
+ /// Non-zero while a drain is waiting to run.
+ private int _scheduled;
+
+ /// Non-zero once the dispatcher has been disposed.
+ private int _disposed;
+
+ /// Initializes a new instance of the class.
+ /// The scheduler that runs the drain.
+ /// The coalescing window.
+ /// The callback that applies pending work.
+ internal ViewDispatcher(ISequencer scheduler, TimeSpan throttle, Action drain)
+ {
+ ThrowHelper.ThrowIfNull(scheduler);
+ ThrowHelper.ThrowIfNull(drain);
+
+ _scheduler = scheduler;
+ _throttle = throttle;
+ _drain = drain;
+ _immediate = ReferenceEquals(scheduler, ReactiveListScheduler.Immediate);
+ _run = Run;
+ _onWindowElapsed = OnWindowElapsed;
+ }
+
+ /// Requests a drain after new work was captured.
+ internal void Notify()
+ {
+ if (Volatile.Read(ref _disposed) != 0)
+ {
+ return;
+ }
+
+ if (_throttle <= TimeSpan.Zero && _immediate)
+ {
+ _drain();
+ return;
+ }
+
+ if (Interlocked.Exchange(ref _scheduled, 1) != 0)
+ {
+ return;
+ }
+
+ if (_throttle <= TimeSpan.Zero)
+ {
+ _ = ReactiveListScheduler.Schedule(_scheduler, TimeSpan.Zero, _run);
+ return;
+ }
+
+ _ = ReactiveListScheduler.Schedule(ReactiveListScheduler.Default, _throttle, _onWindowElapsed);
+ }
+
+ /// Stops scheduling and drops any drain that has not run yet.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal void Dispose() => Volatile.Write(ref _disposed, 1);
+
+ /// Hands the elapsed coalescing window to the view scheduler.
+ private void OnWindowElapsed()
+ {
+ if (Volatile.Read(ref _disposed) != 0)
+ {
+ return;
+ }
+
+ _ = ReactiveListScheduler.Schedule(_scheduler, TimeSpan.Zero, _run);
+ }
+
+ /// Clears the pending flag, then drains.
+ private void Run()
+ {
+ _ = Interlocked.Exchange(ref _scheduled, 0);
+ if (Volatile.Read(ref _disposed) != 0)
+ {
+ return;
+ }
+
+ _drain();
+ }
+}
diff --git a/src/ReactiveList/Internal/ViewMirrorPump.cs b/src/ReactiveList/Internal/ViewMirrorPump.cs
new file mode 100644
index 00000000..2f582927
--- /dev/null
+++ b/src/ReactiveList/Internal/ViewMirrorPump.cs
@@ -0,0 +1,197 @@
+// Copyright (c) ReactiveUI and Contributors. All rights reserved.
+// ReactiveUI and Contributors licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for full license information.
+
+#if REACTIVELIST_REACTIVE
+namespace ReactiveList.Reactive.Internal;
+#else
+namespace ReactiveList.Internal;
+#endif
+
+/// Drains retained source notifications into a sink with a single consumer at a time.
+/// The non-nullable source element type.
+internal sealed class ViewMirrorPump : IDisposable
+ where T : notnull
+{
+ /// The cached count change notification.
+ private static readonly PropertyChangedEventArgs CountChangedArgs = new("Count");
+
+ /// The source being projected.
+ private readonly IReactiveSource _source;
+
+ /// Publishes property-change notifications when subscribed.
+ private readonly Signal _propertyChanges = new();
+
+ /// The subscription to the source stream.
+ private readonly MultipleDisposable _disposables = [];
+
+ /// The sink that receives structural changes, set by .
+ private IViewMirrorSink? _sink;
+
+ /// Applies work queued by the owner before notifications are consumed, or .
+ private Func? _applyQueued;
+
+ /// Reports whether the owner has queued work, or .
+ private Func? _hasQueued;
+
+ /// The dispatcher that coalesces drains.
+ private ViewDispatcher? _dispatcher;
+
+ /// Non-zero while a drain owns the projection.
+ private int _draining;
+
+ /// Non-zero when a rebuild from the live source was requested.
+ private int _resetRequested;
+
+ /// Non-zero once disposed.
+ private int _disposed;
+
+ /// Initializes a new instance of the class.
+ /// The source to mirror.
+ internal ViewMirrorPump(IReactiveSource source)
+ {
+ ThrowHelper.ThrowIfNull(source);
+
+ _source = source;
+ Buffer = new(source);
+ }
+
+ /// Gets the observable stream of property-change notifications.
+ internal IObservable PropertyChanges => _propertyChanges;
+
+ /// Gets the retained notifications and ordered source mirror.
+ internal ViewChangeBuffer Buffer { get; }
+
+ /// Gets a value indicating whether the pump was disposed.
+ internal bool IsDisposed => Volatile.Read(ref _disposed) != 0;
+
+ /// Stops observing and releases retained notifications.
+ public void Dispose()
+ {
+ if (Interlocked.Exchange(ref _disposed, 1) != 0)
+ {
+ return;
+ }
+
+ _dispatcher?.Dispose();
+ _disposables.Dispose();
+ Buffer.Dispose();
+ _propertyChanges.Dispose();
+ }
+
+ /// Starts observing the source.
+ /// The sink that receives structural changes.
+ /// The coalescing window.
+ /// The scheduler that applies changes.
+ /// Applies work queued by the owner, or .
+ /// Reports whether the owner has queued work, or .
+ internal void Start(
+ IViewMirrorSink sink,
+ TimeSpan throttle,
+ ISequencer scheduler,
+ Func? applyQueued = null,
+ Func? hasQueued = null)
+ {
+ ThrowHelper.ThrowIfNull(sink);
+ ThrowHelper.ThrowIfNull(scheduler);
+ _sink = sink;
+ _applyQueued = applyQueued;
+ _hasQueued = hasQueued;
+ _dispatcher = new(scheduler, throttle, Drain);
+ _disposables.Add(_source.Stream.Subscribe(OnSourceNotification));
+ }
+
+ /// Rebuilds the sink from the live source on the calling thread.
+ internal void Refresh()
+ {
+ Volatile.Write(ref _resetRequested, 1);
+ Drain();
+ }
+
+ /// Asks for a drain on the view scheduler.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal void RequestDrain() => _dispatcher?.Notify();
+
+ /// Applies queued work on the calling thread.
+ internal void Drain()
+ {
+ while (!IsDisposed)
+ {
+ if (Interlocked.Exchange(ref _draining, 1) != 0)
+ {
+ return;
+ }
+
+ var changed = false;
+ try
+ {
+ changed = DrainCore();
+ }
+ finally
+ {
+ Volatile.Write(ref _draining, 0);
+ }
+
+ if (changed && _propertyChanges.HasObservers)
+ {
+ _propertyChanges.OnNext(CountChangedArgs);
+ }
+
+ if (!HasWork())
+ {
+ return;
+ }
+ }
+ }
+
+ /// Retains a source notification and asks for a drain.
+ /// The source notification.
+ private void OnSourceNotification(CacheNotify notification)
+ {
+ if (Buffer.Capture(notification, _source.Version))
+ {
+ _dispatcher?.Notify();
+ }
+ }
+
+ /// Gets whether more work arrived while draining.
+ /// when another drain pass is needed.
+ private bool HasWork() =>
+ Volatile.Read(ref _resetRequested) != 0 || _hasQueued?.Invoke() == true || Buffer.HasPending;
+
+ /// Applies every queued change.
+ /// when the sink may have changed.
+ private bool DrainCore()
+ {
+ if (_sink is not { } sink)
+ {
+ return false;
+ }
+
+ var changed = false;
+ do
+ {
+ if (_applyQueued?.Invoke() == true)
+ {
+ changed = true;
+ }
+
+ if (Interlocked.Exchange(ref _resetRequested, 0) != 0)
+ {
+ Buffer.Reset();
+ sink.MirrorReset();
+ changed = true;
+ }
+
+ while (!IsDisposed && Buffer.ApplyNext(sink))
+ {
+ changed = true;
+ }
+
+ Buffer.VerifyAtHead(sink);
+ }
+ while (!IsDisposed && HasWork());
+
+ return changed;
+ }
+}
diff --git a/src/ReactiveList/Views/DynamicFilteredReactiveView.cs b/src/ReactiveList/Views/DynamicFilteredReactiveView.cs
index 7fbe3c36..4757889a 100644
--- a/src/ReactiveList/Views/DynamicFilteredReactiveView.cs
+++ b/src/ReactiveList/Views/DynamicFilteredReactiveView.cs
@@ -7,6 +7,7 @@ namespace ReactiveList.Reactive.Views;
#else
namespace ReactiveList.Views;
#endif
+
/// Provides a dynamically filtered view over an that updates on source or predicate changes.
/// The type of elements in the view.
[System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")]
@@ -16,14 +17,17 @@ public sealed class DynamicFilteredReactiveView : IReadOnlyList, INotifyCo
/// Holds the synchronization gate and lazy notification relays for this facade.
private readonly FacadeRelayState _relays = new();
- /// Contains the mutable state and subscriptions owned by this view.
- private readonly State _state;
+ /// The engine that owns filtering and the source subscription.
+ private readonly FilteredViewEngine _engine;
+
+ /// The subscription to the filter observable.
+ private readonly IDisposable _filterSubscription;
/// Initializes a new instance of the class.
/// The source reactive list to filter.
/// An observable that emits filter predicates.
/// The scheduler for dispatching updates.
- /// The quiet period for predicate changes and retained source updates; zero dispatches without debounce.
+ /// The coalescing window before predicate changes and retained source updates are applied; zero applies them immediately.
/// Thrown when filterObservable is null.
public DynamicFilteredReactiveView(
IReactiveList source,
@@ -31,15 +35,19 @@ public DynamicFilteredReactiveView(
ISequencer scheduler,
TimeSpan throttle)
{
- _state = new(source);
+ ThrowHelper.ThrowIfNull(source);
ThrowHelper.ThrowIfNull(filterObservable);
- _state.Start(filterObservable, scheduler, throttle);
+ ThrowHelper.ThrowIfNull(scheduler);
+
+ _engine = new(source, static _ => true);
+ _engine.Start(throttle, scheduler);
+ _filterSubscription = filterObservable.Subscribe(OnFilterChanged);
}
///
public event NotifyCollectionChangedEventHandler? CollectionChanged
{
- add => FacadeNotificationHelper.AddCollectionChanged(_relays, this, _state.CollectionChanges, value);
+ add => FacadeNotificationHelper.AddCollectionChanged(_relays, this, _engine.CollectionChanges, value);
remove => FacadeNotificationHelper.RemoveCollectionChanged(_relays, value);
}
@@ -47,33 +55,33 @@ public event NotifyCollectionChangedEventHandler? CollectionChanged
///
public event PropertyChangedEventHandler? PropertyChanged
{
- add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _state.PropertyChanges, value);
+ add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _engine.PropertyChanges, value);
remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value);
}
/// Gets the number of items in the filtered view.
- public int Count => _state.Count;
+ public int Count => _engine.Filtered.Count;
/// Gets the underlying read-only observable collection for UI binding.
- public ReadOnlyObservableCollection Items => _state.Items;
+ public ReadOnlyObservableCollection Items => _engine.Items;
/// Gets the item at the specified index.
/// The zero-based index of the item to get.
/// The item at the specified index.
- public T this[int index] => _state.GetItem(index);
+ public T this[int index] => _engine.Filtered[index];
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public IEnumerator GetEnumerator() => _state.GetEnumerator();
+ public IEnumerator GetEnumerator() => _engine.Filtered.GetEnumerator();
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
- /// Forces a rebuild of the filtered view from the source using the current filter.
+ /// Forces a rebuild of the filtered view from the source.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public void Refresh() => _state.Refresh();
+ public void Refresh() => _engine.Refresh();
/// Assigns the current collection of items to a property using the specified setter action.
/// An action that sets a property to the current read-only observable collection of items. Cannot be null.
@@ -96,132 +104,14 @@ public DynamicFilteredReactiveView ToProperty(out ReadOnlyObservableCollectio
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public void Dispose() => _state.Dispose();
-
- /// Owns the mutable data and subscriptions behind the public facade.
- private sealed class State : IDisposable
+ public void Dispose()
{
- /// The subscriptions owned by this view.
- private readonly MultipleDisposable _disposables = [];
-
- /// Serializes filter changes and collection updates.
- private readonly Lock _lock = new();
-
- /// The buffered reconciliation state shared with .
- private readonly FilteredViewBufferState _buffer;
-
- /// Publishes property-change notifications when subscribed.
- private readonly Signal _propertyChanges = new();
-
- /// The predicate currently applied to source items.
- private Func _currentFilter = static _ => true;
-
- /// Initializes a new instance of the class.
- /// The source reactive list to filter.
- /// Thrown when source is .
- public State(IReactiveList source)
- {
- ThrowHelper.ThrowIfNull(source);
-
- ObservableCollection filteredItems = [];
- _buffer = new(source, filteredItems, new(source));
- CollectionChanges = FacadeNotificationHelper.ObserveCollectionChanges(filteredItems);
- Items = new(filteredItems);
- }
-
- /// Gets the observable stream of collection-change notifications.
- public IObservable CollectionChanges { get; }
-
- /// Gets the observable stream of property-change notifications.
- public IObservable PropertyChanges => _propertyChanges;
-
- /// Gets the number of items currently in the filtered view.
- public int Count => _buffer.FilteredItems.Count;
-
- /// Gets the read-only collection exposed by the facade.
- public ReadOnlyObservableCollection Items { get; }
-
- /// Gets the item at the specified index.
- /// The zero-based index of the item to get.
- /// The item at the specified index.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public T GetItem(int index) => _buffer.FilteredItems[index];
-
- /// Starts dynamic-filter and source subscriptions after this state is fully constructed.
- /// An observable that emits filter predicates.
- /// The scheduler for dispatching updates.
- /// The throttle duration for updates.
- public void Start(
- IObservable> filterObservable,
- ISequencer scheduler,
- TimeSpan throttle)
- {
- FilteredViewReconciler.RequestRebuild(_buffer, _currentFilter);
-
- var filters = throttle > TimeSpan.Zero ? filterObservable.Throttle(throttle) : filterObservable;
- var filterSubscription = filters
- .ObserveOn(scheduler)
- .Subscribe(OnFilterChanged);
- _disposables.Add(filterSubscription);
-
- _disposables.Add(FilteredViewReconciler.SubscribeChanges(_buffer, throttle, scheduler, OnSourceChanged));
- }
-
- /// Gets an enumerator over the filtered items.
- /// An enumerator over the filtered items.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public IEnumerator GetEnumerator() => _buffer.FilteredItems.GetEnumerator();
-
- /// Rebuilds the filtered view using its current predicate.
- public void Refresh()
- {
- lock (_lock)
- {
- FilteredViewReconciler.RefreshFromSource(_buffer, _currentFilter);
- }
-
- EmitCountChanged();
- }
-
- /// Stops the dynamic-filter and source subscriptions.
- public void Dispose()
- {
- _disposables.Dispose();
- _propertyChanges.Dispose();
- }
-
- /// Handles filter change notifications.
- /// The new filter value.
- private void OnFilterChanged(Func newFilter)
- {
- lock (_lock)
- {
- _currentFilter = newFilter ?? (static _ => true);
- FilteredViewReconciler.RequestRebuild(_buffer, _currentFilter);
- }
-
- EmitCountChanged();
- }
-
- /// Consumes retained source changes without reading ahead of queued notifications.
- private void OnSourceChanged()
- {
- lock (_lock)
- {
- FilteredViewReconciler.ApplyUpdates(_buffer, _currentFilter);
- }
-
- EmitCountChanged();
- }
-
- /// Emits a count property-changed notification when the facade has subscribers.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void EmitCountChanged()
- {
- if (_propertyChanges.HasObservers)
- {
- _propertyChanges.OnNext(new(nameof(Count)));
- }
- }
+ _filterSubscription.Dispose();
+ _engine.Dispose();
}
+
+ /// Queues a predicate emitted by the filter observable.
+ /// The new predicate, or to include every item.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private void OnFilterChanged(Func filter) => _engine.SetFilter(filter ?? (static _ => true));
}
diff --git a/src/ReactiveList/Views/FilteredReactiveView.cs b/src/ReactiveList/Views/FilteredReactiveView.cs
index fef16b3e..07556da1 100644
--- a/src/ReactiveList/Views/FilteredReactiveView.cs
+++ b/src/ReactiveList/Views/FilteredReactiveView.cs
@@ -7,6 +7,7 @@ namespace ReactiveList.Reactive.Views;
#else
namespace ReactiveList.Views;
#endif
+
/// Provides a filtered, read-only view over an that updates when the source changes.
/// The type of elements in the view.
[System.Diagnostics.DebuggerDisplay("FilteredReactiveView: {Count}")]
@@ -16,28 +17,29 @@ public sealed class FilteredReactiveView : IReadOnlyList, INotifyCollectio
/// Holds the synchronization gate and lazy notification relays for this facade.
private readonly FacadeRelayState _relays = new();
- /// The completed state object that owns filtering and source subscriptions.
- private readonly State _state;
+ /// The engine that owns filtering and the source subscription.
+ private readonly FilteredViewEngine _engine;
/// Initializes a new instance of the class.
/// The source reactive list to filter.
/// The filter predicate.
/// The scheduler for dispatching updates.
- /// The quiet period before consuming retained source changes; zero dispatches without debounce.
+ /// The coalescing window before retained source changes are applied; zero applies them immediately.
public FilteredReactiveView(
IReactiveList source,
Func filter,
ISequencer scheduler,
TimeSpan throttle)
{
- _state = new(source, filter, scheduler, throttle);
- _state.Start();
+ ThrowHelper.ThrowIfNull(scheduler);
+ _engine = new(source, filter);
+ _engine.Start(throttle, scheduler);
}
///
public event NotifyCollectionChangedEventHandler? CollectionChanged
{
- add => FacadeNotificationHelper.AddCollectionChanged(_relays, this, _state.CollectionChanges, value);
+ add => FacadeNotificationHelper.AddCollectionChanged(_relays, this, _engine.CollectionChanges, value);
remove => FacadeNotificationHelper.RemoveCollectionChanged(_relays, value);
}
@@ -45,25 +47,25 @@ public event NotifyCollectionChangedEventHandler? CollectionChanged
///
public event PropertyChangedEventHandler? PropertyChanged
{
- add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _state.PropertyChanges, value);
+ add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _engine.PropertyChanges, value);
remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value);
}
/// Gets the number of items in the filtered view.
- public int Count => _state.Count;
+ public int Count => _engine.Filtered.Count;
/// Gets the underlying read-only observable collection for UI binding.
- public ReadOnlyObservableCollection Items => _state.Items;
+ public ReadOnlyObservableCollection Items => _engine.Items;
/// Gets the item at the specified index.
/// The zero-based index of the item to get.
/// The item at the specified index.
- public T this[int index] => _state.GetItem(index);
+ public T this[int index] => _engine.Filtered[index];
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public IEnumerator GetEnumerator() => _state.GetEnumerator();
+ public IEnumerator GetEnumerator() => _engine.Filtered.GetEnumerator();
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -71,7 +73,7 @@ public event PropertyChangedEventHandler? PropertyChanged
/// Forces a rebuild of the filtered view from the source.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public void Refresh() => _state.Refresh();
+ public void Refresh() => _engine.Refresh();
/// Assigns the current collection of items to a property using the specified setter action.
/// An action that sets a property to the current read-only observable collection of items. Cannot be null.
@@ -94,115 +96,5 @@ public FilteredReactiveView ToProperty(out ReadOnlyObservableCollection co
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public void Dispose() => _state.Dispose();
-
- /// Owns the mutable filtered view after construction has completed.
- private sealed class State : IDisposable
- {
- /// The predicate that determines whether an item is included.
- private readonly Func _filter;
-
- /// The scheduler used to dispatch source notifications.
- private readonly ISequencer _scheduler;
-
- /// The throttle applied to source notifications.
- private readonly TimeSpan _throttle;
-
- /// The subscriptions owned by this state.
- private readonly MultipleDisposable _disposables = [];
-
- /// Synchronizes access to the filtered items collection.
- private readonly Lock _lock = new();
-
- /// The buffered reconciliation state shared with .
- private readonly FilteredViewBufferState _buffer;
-
- /// Publishes property-change notifications when subscribed.
- private readonly Signal _propertyChanges = new();
-
- /// Initializes a new instance of the class without publishing callbacks.
- /// The source reactive list to filter.
- /// The filter predicate.
- /// The scheduler for dispatching updates.
- /// The throttle duration for updates.
- /// Thrown when source or filter is .
- internal State(
- IReactiveList source,
- Func filter,
- ISequencer scheduler,
- TimeSpan throttle)
- {
- ThrowHelper.ThrowIfNull(source);
- ThrowHelper.ThrowIfNull(filter);
-
- _filter = filter;
- _scheduler = scheduler;
- _throttle = throttle;
-
- ObservableCollection filteredItems = [];
- _buffer = new(source, filteredItems, new(source));
- CollectionChanges = FacadeNotificationHelper.ObserveCollectionChanges(filteredItems);
- Items = new(filteredItems);
- FilteredViewReconciler.RequestRebuild(_buffer, _filter);
- }
-
- /// Gets the observable stream of collection-change notifications.
- internal IObservable CollectionChanges { get; }
-
- /// Gets the observable stream of property-change notifications.
- internal IObservable PropertyChanges => _propertyChanges;
-
- /// Gets the number of filtered items.
- internal int Count => _buffer.FilteredItems.Count;
-
- /// Gets the read-only observable filtered items.
- internal ReadOnlyObservableCollection Items { get; }
-
- /// Disposes the source subscription and property signal.
- public void Dispose()
- {
- _disposables.Dispose();
- _propertyChanges.Dispose();
- }
-
- /// Gets the item at the specified index.
- /// The zero-based item index.
- /// The filtered item.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal T GetItem(int index) => _buffer.FilteredItems[index];
-
- /// Starts source observation after state construction.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal void Start() =>
- _disposables.Add(FilteredViewReconciler.SubscribeChanges(_buffer, _throttle, _scheduler, OnSourceChanged));
-
- /// Returns an enumerator over the filtered items.
- /// An enumerator over the filtered items.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal IEnumerator GetEnumerator() => _buffer.FilteredItems.GetEnumerator();
-
- /// Rebuilds the view from the current source state.
- internal void Refresh()
- {
- lock (_lock)
- {
- FilteredViewReconciler.RefreshFromSource(_buffer, _filter);
- }
- }
-
- /// Handles source change notifications.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void OnSourceChanged()
- {
- lock (_lock)
- {
- FilteredViewReconciler.ApplyUpdates(_buffer, _filter);
- }
-
- if (_propertyChanges.HasObservers)
- {
- _propertyChanges.OnNext(new(nameof(Count)));
- }
- }
- }
+ public void Dispose() => _engine.Dispose();
}
diff --git a/src/ReactiveList/Views/GroupedReactiveView.cs b/src/ReactiveList/Views/GroupedReactiveView.cs
index 79970595..bb2188bf 100644
--- a/src/ReactiveList/Views/GroupedReactiveView.cs
+++ b/src/ReactiveList/Views/GroupedReactiveView.cs
@@ -7,6 +7,7 @@ namespace ReactiveList.Reactive.Views;
#else
namespace ReactiveList.Views;
#endif
+
/// Provides a grouped view over a that automatically updates when the source list changes.
/// The type of elements in the view.
/// The type of the grouping key.
@@ -22,28 +23,29 @@ public sealed class GroupedReactiveView :
/// Holds the synchronization gate and lazy notification relays for this facade.
private readonly FacadeRelayState _relays = new();
- /// The completed state object that owns grouping and source subscriptions.
- private readonly State _state;
+ /// The engine that owns grouping and the source subscription.
+ private readonly GroupedViewEngine _engine;
/// Initializes a new instance of the class.
/// The source reactive list to group.
/// A function to extract the grouping key.
/// The scheduler for dispatching updates.
- /// The throttle duration for updates. Zero disables throttling; updates still use the specified scheduler.
+ /// The coalescing window for updates. Zero applies them as soon as the scheduler runs.
public GroupedReactiveView(
IReactiveList source,
Func keySelector,
ISequencer scheduler,
TimeSpan throttle)
{
- _state = new(source, keySelector, scheduler, throttle);
- _state.Start();
+ ThrowHelper.ThrowIfNull(scheduler);
+ _engine = new(source, keySelector);
+ _engine.Start(throttle, scheduler);
}
///
public event NotifyCollectionChangedEventHandler? CollectionChanged
{
- add => FacadeNotificationHelper.AddCollectionChanged(_relays, this, _state.CollectionChanges, value);
+ add => FacadeNotificationHelper.AddCollectionChanged(_relays, this, _engine.CollectionChanges, value);
remove => FacadeNotificationHelper.RemoveCollectionChanged(_relays, value);
}
@@ -51,48 +53,49 @@ public event NotifyCollectionChangedEventHandler? CollectionChanged
///
public event PropertyChangedEventHandler? PropertyChanged
{
- add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _state.PropertyChanges, value);
+ add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _engine.PropertyChanges, value);
remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value);
}
/// Gets the number of groups.
- public int Count => _state.Count;
+ public int Count => _engine.Count;
/// Gets the collection of groups for UI binding.
- public ReadOnlyObservableCollection> Groups => _state.Groups;
+ public ReadOnlyObservableCollection> Groups => _engine.Groups;
/// Gets the collection of groups for UI binding. This is an alias for .
/// This property exists to satisfy the interface.
public ReadOnlyObservableCollection> Items => Groups;
/// Gets the keys of all groups.
- public IEnumerable Keys => _state.Keys;
+ public IEnumerable Keys => _engine.SnapshotKeys();
/// Gets the values (item lists) of all groups.
- public IEnumerable> Values => _state.Values;
+ public IEnumerable> Values => _engine.SnapshotValues();
/// Gets the items in the specified group.
/// The group key.
/// The items in the group.
- public IReadOnlyList this[TKey key] => _state.GetItems(key);
+ public IReadOnlyList this[TKey key] => _engine.GetItems(key);
/// Determines whether the view contains a group with the specified key.
/// The key to locate.
/// true if the view contains a group with the key; otherwise, false.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public bool ContainsKey(TKey key) => _state.ContainsKey(key);
+ public bool ContainsKey(TKey key) => _engine.ContainsKey(key);
/// Gets the items in the specified group, if it exists.
/// The group key.
/// When this method returns, contains the items, if the key is found; otherwise, null.
/// true if the view contains a group with the specified key; otherwise, false.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public bool TryGetValue(TKey key, out IReadOnlyList value) => _state.TryGetValue(key, out value);
+ public bool TryGetValue(TKey key, out IReadOnlyList value) => _engine.TryGetValue(key, out value);
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public IEnumerator>> GetEnumerator() => _state.GetEnumerator();
+ public IEnumerator>> GetEnumerator() =>
+ ((IEnumerable>>)_engine.SnapshotPairs()).GetEnumerator();
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -100,7 +103,7 @@ public event PropertyChangedEventHandler? PropertyChanged
/// Forces a rebuild of the grouped view from the source.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public void Refresh() => _state.Refresh();
+ public void Refresh() => _engine.Refresh();
/// Assigns the current collection of groups to a property using the specified setter action.
/// An action that sets a property to the current read-only observable collection of groups. Cannot be null.
@@ -125,302 +128,5 @@ public GroupedReactiveView ToProperty(out ReadOnlyObservableCollection<
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public void Dispose() => _state.Dispose();
-
- /// Owns the mutable grouped view after construction has completed.
- private sealed class State : IDisposable
- {
- /// The list whose changes feed this grouped view.
- private readonly IReactiveList _source;
-
- /// Extracts the grouping key for each source item.
- private readonly Func _keySelector;
-
- /// The mutable item collection for each group key.
- private readonly Dictionary> _groups = [];
-
- /// The observable collection backing the public group view.
- private readonly ObservableCollection> _groupCollection = [];
-
- /// The scheduler used to dispatch source notifications.
- private readonly ISequencer _scheduler;
-
- /// The throttle applied to source notifications.
- private readonly TimeSpan _throttle;
-
- /// The subscriptions owned by this state.
- private readonly MultipleDisposable _disposables = [];
-
- /// Serializes source notifications and group updates.
- private readonly Lock _lock = new();
-
- /// Publishes property-change notifications when subscribed.
- private readonly Signal _propertyChanges = new();
-
- /// Initializes a new instance of the class without publishing callbacks.
- /// The source reactive list to group.
- /// A function to extract the grouping key.
- /// The scheduler for dispatching updates.
- /// The throttle duration for updates.
- /// Thrown when source is .
- internal State(
- IReactiveList source,
- Func keySelector,
- ISequencer scheduler,
- TimeSpan throttle)
- {
- ThrowHelper.ThrowIfNull(source);
- ThrowHelper.ThrowIfNull(keySelector);
-
- _source = source;
- _keySelector = keySelector;
- _scheduler = scheduler;
- _throttle = throttle;
- CollectionChanges = FacadeNotificationHelper.ObserveCollectionChanges(_groupCollection);
- Groups = new(_groupCollection);
- RebuildView();
- }
-
- /// Gets the observable stream of collection-change notifications.
- internal IObservable CollectionChanges { get; }
-
- /// Gets the observable stream of property-change notifications.
- internal IObservable PropertyChanges => _propertyChanges;
-
- /// Gets the number of groups.
- internal int Count => _groups.Count;
-
- /// Gets the read-only observable collection of groups.
- internal ReadOnlyObservableCollection> Groups { get; }
-
- /// Gets all group keys.
- internal IEnumerable Keys => _groups.Keys;
-
- /// Gets all group item collections.
- internal IEnumerable> Values => EnumerateValues();
-
- /// Disposes the source subscription and property signal.
- public void Dispose()
- {
- _disposables.Dispose();
- _propertyChanges.Dispose();
- }
-
- /// Gets the items in the specified group.
- /// The group key.
- /// The items in the group.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal ObservableCollection GetItems(TKey key) => _groups[key];
-
- /// Starts source observation after state construction.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal void Start() =>
- _disposables.Add(ReactiveViewHelpers.SubscribeChangeSets(_source, _throttle, _scheduler, OnSourceChanged));
-
- /// Determines whether a group exists.
- /// The group key.
- /// when the group exists; otherwise, .
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal bool ContainsKey(TKey key) => _groups.ContainsKey(key);
-
- /// Gets a group when it exists.
- /// The group key.
- /// The located item collection or an empty collection.
- /// when the group exists; otherwise, .
- internal bool TryGetValue(TKey key, out IReadOnlyList value)
- {
- if (_groups.TryGetValue(key, out var list))
- {
- value = list;
- return true;
- }
-
- value = [];
- return false;
- }
-
- /// Returns an enumerator over the groups.
- /// An enumerator over the groups.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal IEnumerator>> GetEnumerator() => EnumerateGroups().GetEnumerator();
-
- /// Rebuilds the view from the current source state.
- internal void Refresh()
- {
- lock (_lock)
- {
- RebuildView();
- }
- }
-
- /// Handles source change notifications.
- /// The changes value.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void OnSourceChanged(ChangeSet changes)
- {
- lock (_lock)
- {
- for (var i = 0; i < changes.Count; i++)
- {
- ProcessChange(changes[i]);
- }
- }
-
- if (_propertyChanges.HasObservers)
- {
- _propertyChanges.OnNext(new(nameof(Count)));
- }
- }
-
- /// Processes a source collection change.
- /// The change value.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void ProcessChange(Change change)
- {
- if (change.Reason is ChangeReason.Add)
- {
- AddToGroup(change.Current);
- }
- else if (change.Reason is ChangeReason.Remove)
- {
- RemoveFromGroup(change.Current);
- }
- else if (change.Reason is ChangeReason.Update)
- {
- UpdateGroup(change);
- }
- else if (change.Reason is ChangeReason.Clear)
- {
- _groups.Clear();
- _groupCollection.Clear();
- }
- else if (change.Reason is ChangeReason.Move or ChangeReason.Refresh)
- {
- RebuildView();
- }
- }
-
- /// Updates an item in its existing group or moves it to its new group.
- /// The update change to apply.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void UpdateGroup(Change change)
- {
- var previous = change.Previous;
- if (previous is null)
- {
- AddToGroup(change.Current);
- return;
- }
-
- var oldKey = _keySelector(previous);
- var newKey = _keySelector(change.Current);
- if (!EqualityComparer.Default.Equals(oldKey, newKey))
- {
- RemoveFromGroup(previous);
- AddToGroup(change.Current);
- return;
- }
-
- if (!_groups.TryGetValue(oldKey, out var group))
- {
- return;
- }
-
- var index = group.IndexOf(previous);
- if (index < 0)
- {
- return;
- }
-
- group[index] = change.Current;
- }
-
- /// Adds data for the AddToGroup operation.
- /// The item value.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void AddToGroup(T item)
- {
- var key = _keySelector(item);
- if (!_groups.TryGetValue(key, out var group))
- {
- group = [];
- _groups[key] = group;
- _groupCollection.Add(new(key, group));
- }
-
- group.Add(item);
- }
-
- /// Removes data for the RemoveFromGroup operation.
- /// The item value.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void RemoveFromGroup(T item)
- {
- var key = _keySelector(item);
- if (!_groups.TryGetValue(key, out var group))
- {
- return;
- }
-
- _ = group.Remove(item);
- if (group.Count != 0)
- {
- return;
- }
-
- _ = _groups.Remove(key);
- ReactiveGroup? reactiveGroup = null;
- var comparer = EqualityComparer.Default;
- for (var i = 0; i < _groupCollection.Count; i++)
- {
- var candidate = _groupCollection[i];
- if (!comparer.Equals(candidate.Key, key))
- {
- continue;
- }
-
- reactiveGroup = candidate;
- break;
- }
-
- if (reactiveGroup is null)
- {
- return;
- }
-
- _ = _groupCollection.Remove(reactiveGroup);
- }
-
- /// Rebuilds the view from the current source state.
- private void RebuildView()
- {
- _groups.Clear();
- _groupCollection.Clear();
-
- foreach (var item in _source)
- {
- AddToGroup(item);
- }
- }
-
- /// Enumerates the group item collections without LINQ allocation.
- /// The group item collections.
- private IEnumerable> EnumerateValues()
- {
- foreach (var value in _groups.Values)
- {
- yield return value;
- }
- }
-
- /// Enumerates the groups using the public read-only value type.
- /// The key and read-only item collection for each group.
- private IEnumerable>> EnumerateGroups()
- {
- foreach (var group in _groups)
- {
- yield return new(group.Key, group.Value);
- }
- }
- }
+ public void Dispose() => _engine.Dispose();
}
diff --git a/src/ReactiveList/Views/SortedReactiveView.cs b/src/ReactiveList/Views/SortedReactiveView.cs
index 70e94723..1261793d 100644
--- a/src/ReactiveList/Views/SortedReactiveView.cs
+++ b/src/ReactiveList/Views/SortedReactiveView.cs
@@ -7,6 +7,7 @@ namespace ReactiveList.Reactive.Views;
#else
namespace ReactiveList.Views;
#endif
+
/// Provides a sorted, read-only view over a that automatically updates when the source list changes.
/// The type of elements in the view.
[System.Diagnostics.DebuggerDisplay("SortedReactiveView: {Count}")]
@@ -16,28 +17,29 @@ public sealed class SortedReactiveView : IReadOnlyList, INotifyCollectionC
/// Holds the synchronization gate and lazy notification relays for this facade.
private readonly FacadeRelayState _relays = new();
- /// The completed state object that owns sorting and source subscriptions.
- private readonly State _state;
+ /// The engine that owns sorting and the source subscription.
+ private readonly SortedViewEngine _engine;
/// Initializes a new instance of the class.
/// The source reactive list to sort.
/// The comparer for sorting items.
/// The scheduler for dispatching updates.
- /// The throttle duration for updates. Zero disables throttling; updates still use the specified scheduler.
+ /// The coalescing window for updates. Zero applies them as soon as the scheduler runs.
public SortedReactiveView(
IReactiveList source,
IComparer comparer,
ISequencer scheduler,
TimeSpan throttle)
{
- _state = new(source, comparer, scheduler, throttle);
- _state.Start();
+ ThrowHelper.ThrowIfNull(scheduler);
+ _engine = new(source, comparer);
+ _engine.Start(throttle, scheduler);
}
///
public event NotifyCollectionChangedEventHandler? CollectionChanged
{
- add => FacadeNotificationHelper.AddCollectionChanged(_relays, this, _state.CollectionChanges, value);
+ add => FacadeNotificationHelper.AddCollectionChanged(_relays, this, _engine.CollectionChanges, value);
remove => FacadeNotificationHelper.RemoveCollectionChanged(_relays, value);
}
@@ -45,25 +47,25 @@ public event NotifyCollectionChangedEventHandler? CollectionChanged
///
public event PropertyChangedEventHandler? PropertyChanged
{
- add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _state.PropertyChanges, value);
+ add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _engine.PropertyChanges, value);
remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value);
}
/// Gets the number of items in the sorted view.
- public int Count => _state.Count;
+ public int Count => _engine.Sorted.Count;
/// Gets the underlying read-only observable collection for UI binding.
- public ReadOnlyObservableCollection Items => _state.Items;
+ public ReadOnlyObservableCollection Items => _engine.Items;
/// Gets the item at the specified index.
/// The zero-based index of the item to get.
/// The item at the specified index.
- public T this[int index] => _state.GetItem(index);
+ public T this[int index] => _engine.Sorted[index];
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public IEnumerator GetEnumerator() => _state.GetEnumerator();
+ public IEnumerator GetEnumerator() => _engine.Sorted.GetEnumerator();
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -71,7 +73,7 @@ public event PropertyChangedEventHandler? PropertyChanged
/// Forces a rebuild of the sorted view from the source.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public void Refresh() => _state.Refresh();
+ public void Refresh() => _engine.Refresh();
/// Assigns the current collection of items to a property using the specified setter action.
/// An action that sets a property to the current read-only observable collection of items. Cannot be null.
@@ -94,224 +96,5 @@ public SortedReactiveView ToProperty(out ReadOnlyObservableCollection coll
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public void Dispose() => _state.Dispose();
-
- /// Owns the mutable sorted view after construction has completed.
- private sealed class State : IDisposable
- {
- /// The reactive list that supplies items to this view.
- private readonly IReactiveList _source;
-
- /// The comparer used to order items in this view.
- private readonly IComparer _comparer;
-
- /// The mutable collection that backs the read-only sorted items collection.
- private readonly ObservableCollection _sortedItems = [];
-
- /// The scheduler used to dispatch source notifications.
- private readonly ISequencer _scheduler;
-
- /// The throttle applied to source notifications.
- private readonly TimeSpan _throttle;
-
- /// The subscriptions owned by this state.
- private readonly MultipleDisposable _disposables = [];
-
- /// Synchronizes access to the sorted items collection.
- private readonly Lock _lock = new();
-
- /// Publishes property-change notifications when subscribed.
- private readonly Signal _propertyChanges = new();
-
- /// Initializes a new instance of the class without publishing callbacks.
- /// The source reactive list to sort.
- /// The comparer for sorting items.
- /// The scheduler for dispatching updates.
- /// The throttle duration for updates.
- /// Thrown when source or comparer is .
- internal State(
- IReactiveList source,
- IComparer comparer,
- ISequencer scheduler,
- TimeSpan throttle)
- {
- ThrowHelper.ThrowIfNull(source);
- ThrowHelper.ThrowIfNull(comparer);
-
- _source = source;
- _comparer = comparer;
- _scheduler = scheduler;
- _throttle = throttle;
- CollectionChanges = FacadeNotificationHelper.ObserveCollectionChanges(_sortedItems);
- Items = new(_sortedItems);
- RebuildView();
- }
-
- /// Gets the observable stream of collection-change notifications.
- internal IObservable CollectionChanges { get; }
-
- /// Gets the observable stream of property-change notifications.
- internal IObservable PropertyChanges => _propertyChanges;
-
- /// Gets the number of sorted items.
- internal int Count => _sortedItems.Count;
-
- /// Gets the read-only observable sorted items.
- internal ReadOnlyObservableCollection Items { get; }
-
- /// Disposes the source subscription and property signal.
- public void Dispose()
- {
- _disposables.Dispose();
- _propertyChanges.Dispose();
- }
-
- /// Gets the item at the specified index.
- /// The zero-based item index.
- /// The sorted item.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal T GetItem(int index) => _sortedItems[index];
-
- /// Starts source observation after state construction.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal void Start() =>
- _disposables.Add(ReactiveViewHelpers.SubscribeChangeSets(_source, _throttle, _scheduler, OnSourceChanged));
-
- /// Returns an enumerator over the sorted items.
- /// An enumerator over the sorted items.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal IEnumerator GetEnumerator() => _sortedItems.GetEnumerator();
-
- /// Rebuilds the view from the current source state.
- internal void Refresh()
- {
- lock (_lock)
- {
- RebuildView();
- }
- }
-
- /// Handles source change notifications.
- /// The changes value.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void OnSourceChanged(ChangeSet changes)
- {
- lock (_lock)
- {
- var needsRebuild = false;
-
- for (var i = 0; i < changes.Count; i++)
- {
- var change = changes[i];
- if (change.Reason is ChangeReason.Add)
- {
- InsertSorted(change.Current);
- }
- else if (change.Reason is ChangeReason.Remove)
- {
- _ = _sortedItems.Remove(change.Current);
- }
- else if (change.Reason is ChangeReason.Update)
- {
- UpdateItem(change);
- }
- else if (change.Reason is ChangeReason.Clear)
- {
- _sortedItems.Clear();
- }
- else if (change.Reason is ChangeReason.Move or ChangeReason.Refresh)
- {
- needsRebuild = true;
- }
- }
-
- if (needsRebuild)
- {
- RebuildView();
- }
- }
-
- if (_propertyChanges.HasObservers)
- {
- _propertyChanges.OnNext(new(nameof(Count)));
- }
- }
-
- /// Replaces an item while maintaining sorted order.
- /// The update to apply.
- private void UpdateItem(Change change)
- {
- if (change.Previous is not null)
- {
- _ = _sortedItems.Remove(change.Previous);
- }
-
- InsertSorted(change.Current);
- }
-
- /// Inserts data for the InsertSorted operation.
- /// The item value.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void InsertSorted(T item)
- {
- var index = BinarySearch(item);
- if (index < 0)
- {
- index = ~index;
- }
-
- _sortedItems.Insert(index, item);
- }
-
- /// Searches for the sorted insertion index.
- /// The item value.
- /// The matching item index or the bitwise complement of the insertion index.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private int BinarySearch(T item)
- {
- var lo = 0;
- var hi = _sortedItems.Count - 1;
-
- while (lo <= hi)
- {
- var mid = lo + ((hi - lo) >> 1);
- var comparison = _comparer.Compare(_sortedItems[mid], item);
-
- if (comparison == 0)
- {
- return mid;
- }
-
- if (comparison < 0)
- {
- lo = mid + 1;
- }
- else
- {
- hi = mid - 1;
- }
- }
-
- return ~lo;
- }
-
- /// Rebuilds the view from the current source state.
- private void RebuildView()
- {
- _sortedItems.Clear();
- var sourceItems = _source.Items;
- var count = sourceItems.Count;
- var sorted = new List(count);
- for (var i = 0; i < count; i++)
- {
- sorted.Add(sourceItems[i]);
- }
-
- sorted.Sort(_comparer);
- for (var i = 0; i < sorted.Count; i++)
- {
- _sortedItems.Add(sorted[i]);
- }
- }
- }
+ public void Dispose() => _engine.Dispose();
}
diff --git a/src/ReactiveList/Views/ViewChangeBuffer.cs b/src/ReactiveList/Views/ViewChangeBuffer.cs
index 308099de..29e57941 100644
--- a/src/ReactiveList/Views/ViewChangeBuffer.cs
+++ b/src/ReactiveList/Views/ViewChangeBuffer.cs
@@ -8,7 +8,7 @@ namespace ReactiveList.Reactive.Views;
namespace ReactiveList.Views;
#endif
-/// Retains structural changes before dispatch and maintains the consumed source snapshot.
+/// Retains source notifications until a view drains them and keeps an ordered mirror of the source.
/// The source item type.
internal sealed class ViewChangeBuffer
where T : notnull
@@ -16,20 +16,37 @@ internal sealed class ViewChangeBuffer
/// Synchronizes notification producers with the consuming view.
private readonly Lock _gate = new();
- /// The changes retained independently of coalesced dispatch signals.
- private readonly Queue<(ChangeSet Changes, long Version)> _pending = [];
+ /// The notifications retained until the view drains them.
+ private readonly Queue> _pending = [];
+
+ /// The source mirrored by .
+ private readonly IReactiveSource _source;
/// The source revision already covered by an explicit snapshot.
private long _coveredVersion;
+ /// The source revision of the most recently applied notification or snapshot.
+ private long _appliedVersion;
+
+ /// Whether a batch notification was applied and the mirror has not been compared with the source since.
+ private bool _verifyPending;
+
+ /// Whether the buffer has been disposed.
+ private bool _disposed;
+
/// Initializes a new instance of the class.
- /// The source to snapshot.
- internal ViewChangeBuffer(IReactiveSource source) => Reset(source);
+ /// The source to mirror.
+ internal ViewChangeBuffer(IReactiveSource source)
+ {
+ ThrowHelper.ThrowIfNull(source);
+ _source = source;
+ Reset();
+ }
- /// Gets the source items after consumed changes.
+ /// Gets the source items after the consumed notifications.
internal List Items { get; } = [];
- /// Gets whether dispatch-time changes remain to be consumed.
+ /// Gets whether notifications remain to be consumed.
internal bool HasPending
{
get
@@ -67,141 +84,369 @@ internal static int FindIndex(IEnumerable items, T item)
return equalIndex;
}
- /// Retains a stable change set before its dispatch signal is throttled.
- /// The copied structural changes.
- /// The emitting source revision.
- /// A dispatch signal.
- internal bool Capture(ChangeSet changes, long version)
+ /// Compares two items by reference for reference types and by value for value types.
+ /// The first item.
+ /// The second item.
+ /// when the items are the same occurrence.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal static bool SameItem(T? left, T? right) =>
+ typeof(T).IsValueType
+ ? EqualityComparer.Default.Equals(left!, right!)
+ : ReferenceEquals(left, right);
+
+ /// Retains a notification until the view drains it.
+ /// The source notification.
+ /// The source revision that produced the notification.
+ /// when the notification was retained.
+ internal bool Capture(CacheNotify notification, long version)
{
lock (_gate)
{
- _pending.Enqueue((changes, version));
+ if (!_disposed)
+ {
+ _pending.Enqueue(new(notification, version));
+ return true;
+ }
+ }
+
+ notification.Batch?.Dispose();
+ return false;
+ }
+
+ /// Applies the next retained notification that is not already covered by a snapshot.
+ /// The sink type.
+ /// The sink that receives the structural changes.
+ /// when a notification was consumed.
+ internal bool ApplyNext(TSink sink)
+ where TSink : IViewMirrorSink
+ {
+ if (!TryTake(out var pending))
+ {
+ return false;
+ }
+
+ try
+ {
+ Apply(pending, sink);
+ }
+ finally
+ {
+ pending.Notification.Batch?.Dispose();
}
return true;
}
- /// Takes the next changes not already represented by an explicit snapshot.
- /// The retained changes.
- /// Whether a change set was available.
- internal bool TryTake(out ChangeSet changes)
+ /// Replaces the mirror with a consistent snapshot of the source and excludes already covered queued notifications.
+ internal void Reset()
+ {
+ var version = _source.Version;
+ T[] snapshot = [.. _source];
+ while (version != _source.Version)
+ {
+ version = _source.Version;
+ snapshot = [.. _source];
+ }
+
+ lock (_gate)
+ {
+ _coveredVersion = version;
+ }
+
+ _appliedVersion = version;
+ _verifyPending = false;
+ Items.Clear();
+ Items.AddRange(snapshot);
+ }
+
+ /// Compares the mirror with the source once every notification has been applied and repairs any difference.
+ /// The sink type.
+ /// The sink that is told when the mirror is replaced.
+ internal void VerifyAtHead(TSink sink)
+ where TSink : IViewMirrorSink
+ {
+ if (!_verifyPending)
+ {
+ return;
+ }
+
+ var version = _source.Version;
+ if (version != _appliedVersion)
+ {
+ return;
+ }
+
+ T[] snapshot = [.. _source];
+ if (version != _source.Version)
+ {
+ return;
+ }
+
+ _verifyPending = false;
+ if (MatchesMirror(snapshot))
+ {
+ return;
+ }
+
+ ResetFromSource(sink);
+ }
+
+ /// Drops every retained notification and stops accepting new ones.
+ internal void Dispose()
+ {
+ lock (_gate)
+ {
+ _disposed = true;
+ while (_pending.Count > 0)
+ {
+ _pending.Dequeue().Notification.Batch?.Dispose();
+ }
+ }
+ }
+
+ /// Takes the next notification not already represented by an explicit snapshot.
+ /// The retained notification.
+ /// Whether a notification was available.
+ private bool TryTake(out PendingNotification pending)
{
lock (_gate)
{
while (_pending.Count > 0)
{
- var pending = _pending.Dequeue();
- if (pending.Version <= _coveredVersion)
+ var candidate = _pending.Dequeue();
+ if (candidate.Version <= _coveredVersion)
{
+ candidate.Notification.Batch?.Dispose();
continue;
}
- changes = pending.Changes;
+ pending = candidate;
return true;
}
}
- changes = default;
+ pending = default;
return false;
}
- /// Snapshots an explicit refresh and excludes already-covered queued changes.
- /// The source to snapshot.
- internal void Reset(IReactiveSource source)
+ /// Applies one notification to the mirror and reports the change to the sink.
+ /// The sink type.
+ /// The notification to apply.
+ /// The sink that receives the structural changes.
+ private void Apply(PendingNotification pending, TSink sink)
+ where TSink : IViewMirrorSink