diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index 3b6519ad..eb77c22b 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -15,7 +15,7 @@ jobs: permissions: contents: read actions: write - uses: reactiveui/actions-common/.github/workflows/workflow-common-setup-and-build.yml@af603d4a2e933d92681b77919452a8bde4be9e13 # main + uses: reactiveui/actions-common/.github/workflows/workflow-common-setup-and-build.yml@e07297f2914b5af0b96e82ddb6872835156a0287 # main with: configuration: Release productNamespacePrefix: ReactiveList diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index bd6e76a5..ba4f90e3 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -20,7 +20,7 @@ jobs: contents: read packages: read actions: read - uses: reactiveui/actions-common/.github/workflows/workflow-common-codeql.yml@af603d4a2e933d92681b77919452a8bde4be9e13 # main + uses: reactiveui/actions-common/.github/workflows/workflow-common-codeql.yml@e07297f2914b5af0b96e82ddb6872835156a0287 # main with: srcFolder: src solutionFile: ReactiveList.slnx diff --git a/.github/workflows/lock.yml b/.github/workflows/lock.yml index 8f1b7060..e349c3d8 100644 --- a/.github/workflows/lock.yml +++ b/.github/workflows/lock.yml @@ -16,4 +16,4 @@ jobs: permissions: issues: write pull-requests: write - uses: reactiveui/actions-common/.github/workflows/workflow-common-lock-threads.yml@af603d4a2e933d92681b77919452a8bde4be9e13 # main + uses: reactiveui/actions-common/.github/workflows/workflow-common-lock-threads.yml@e07297f2914b5af0b96e82ddb6872835156a0287 # main diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 92fefcd6..6d21d563 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -34,7 +34,7 @@ jobs: contents: write id-token: write packages: read - uses: reactiveui/actions-common/.github/workflows/workflow-common-release.yml@af603d4a2e933d92681b77919452a8bde4be9e13 # main + uses: reactiveui/actions-common/.github/workflows/workflow-common-release.yml@e07297f2914b5af0b96e82ddb6872835156a0287 # main with: solutionFile: ReactiveList.slnx minverMinimumMajorMinor: '7.0' @@ -78,7 +78,7 @@ jobs: permissions: contents: write needs: [release, publish-nuget] - uses: reactiveui/actions-common/.github/workflows/workflow-common-create-release.yml@af603d4a2e933d92681b77919452a8bde4be9e13 # main + uses: reactiveui/actions-common/.github/workflows/workflow-common-create-release.yml@e07297f2914b5af0b96e82ddb6872835156a0287 # main with: version: ${{ needs.release.outputs.semver2 }} tag: ${{ needs.release.outputs.tag }} diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 3c531c2b..e7c5d963 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -17,4 +17,4 @@ jobs: contents: read id-token: write security-events: write - uses: reactiveui/actions-common/.github/workflows/workflow-common-scorecard.yml@af603d4a2e933d92681b77919452a8bde4be9e13 # main + uses: reactiveui/actions-common/.github/workflows/workflow-common-scorecard.yml@e07297f2914b5af0b96e82ddb6872835156a0287 # main diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 06d8e8c9..4d28b145 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -11,7 +11,7 @@ permissions: jobs: sonarcloud: - uses: reactiveui/actions-common/.github/workflows/workflow-common-sonarcloud.yml@af603d4a2e933d92681b77919452a8bde4be9e13 # main + uses: reactiveui/actions-common/.github/workflows/workflow-common-sonarcloud.yml@e07297f2914b5af0b96e82ddb6872835156a0287 # main with: productNamespacePrefix: ReactiveList solutionFile: ReactiveList.slnx diff --git a/AGENTS.md b/AGENTS.md index 71d55fb9..ec4e66ea 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,7 +62,7 @@ Thread safety is a core contract of `ReactiveList`. Every collection, secondary | Area | Mandatory Rule | | :--- | :--- | | **Lock primitive** | Use the repo `Lock` alias (`System.Threading.Lock` on `net10.0+`, `object` on `.NET Framework`) for short, non-recursive mutual exclusion. Never `lock (this)` or lock on public instances or `Type` objects. | -| **Sharded lock order** | In four-shard quaternary collections (`QuaternaryBase`, `QuaternaryList`, `QuaternaryDictionary`), multi-shard operations (`Count`, snapshots, `Clear`, `RemoveRange`, index rebuilds) must acquire shard locks in strict ascending index order (`0` to `ShardCount - 1`) and release them in reverse order inside `finally`. Never acquire a lower-numbered shard lock while holding a higher-numbered one. | +| **Sharded lock order** | In `QuaternaryList` and `QuaternaryDictionary`, operations that acquire multiple shard locks must take them in ascending order and release them in reverse order inside `finally`. Never acquire a lower-numbered shard lock while holding a higher-numbered one. | | **Idempotent disposal** | Guard `Dispose` and `Dispose(bool)` with an atomic latch: `if (Interlocked.Exchange(ref _disposed, 1) != 0) { return; }` (`PSH1306`). Check `Volatile.Read(ref _disposed) != 0` on entry to operations that throw `ObjectDisposedException`. | | **Memory-model visibility** | Every non-`Interlocked` read of a field mutated via `Interlocked.*` (`_disposed`, `_version`, counters, state references) must use `Volatile.Read` (`PSH1307`). Never publish multi-field state via plain writes; swap a single immutable state object or snapshot reference with `Interlocked.CompareExchange` or `Volatile.Write`. | | **Callback reentrancy** | Never invoke external user delegates (filter predicates when avoidable, `IObserver.OnNext`, `CollectionChanged`, `PropertyChanged`) while holding internal shard or mutation locks if reentrant callbacks can deadlock or observe half-updated invariants. Capture notification state inside the lock, release the lock, and dispatch outside or via the single-reader notification channel. | @@ -84,7 +84,7 @@ Structure public and internal mutation/query methods so cheap checks reject no-o ### 2. Cold-Gate Splitting for JIT Inlining -The .NET JIT refuses to inline methods that contain `try`/`finally` blocks (including `lock` statements), large switch/loop bodies, or inline `throw new ...` expressions: +The .NET 10 and later JIT can inline some methods that contain `try`/`finally`. The presence of a lock is not enough to decide whether to split a method. Use measurements to justify a split on modern targets. Keep large branches and uncommon work out of the steady-state path: - Keep hot steady-state paths (`Count`, indexer reads, `AsSpan`, observerless fast checks, lazy-initialized pipeline/channel reads) small and mark tiny wrappers `[MethodImpl(MethodImplOptions.AggressiveInlining)]`. - Read lazy-initialized references (`_streamPipeline`, `_eventChannel`) via `Volatile.Read` on the warm path, and split lock-protected initialization (`EnsureEventProcessorStarted`, `EnsurePipelineCreated`), buffer resizing, contention fallback, and exception throwing into `[MethodImpl(MethodImplOptions.NoInlining)]` slow-path methods. @@ -99,12 +99,14 @@ The .NET JIT refuses to inline methods that contain `try`/`finally` blocks (incl ## 4. Allocation, Data-Layout, and Idiomatic C# Rules +Use sealed classes and composition instead of custom base classes. Interfaces are allowed. Inherit from a class or leave it unsealed only when an external dependency requires it. + Library hot paths must minimize GC pressure, pointer chasing, and interface dispatch across all supported target frameworks. - **Zero LINQ, zero `Regex`, and zero `yield return` on production hot paths:** `System.Linq`, `System.Text.RegularExpressions`, and iterator state machines (`yield return`) are banned on hot paths in `src/ReactiveList` and `src/ReactiveList.Reactive` (LINQ is permitted in test projects for assertion clarity). Use indexed `for` loops over `T[]`, `Span`, `ReadOnlySpan`, and `List`. - **Frozen collections are banned:** Do not use `System.Collections.Frozen`, `FrozenDictionary`, `FrozenSet`, `ToFrozenDictionary`, or `ToFrozenSet`. `ReactiveList` is a reusable library and cannot assume a long-running host process to amortize construction cost. Use `Dictionary` and `HashSet` with explicit capacity hints where size is known, and always pass `StringComparer.Ordinal` for string keys (index names, property names). - **Concrete collection types (`CA1859`):** Type fields, locals, parameters, and internal return values as concrete `List`, `Dictionary`, `HashSet`, or `T[]` rather than `IList`, `ICollection`, `IDictionary`, or `IEnumerable` so `foreach` uses non-allocating struct enumerators and method calls devirtualize. -- **Single-lookup dictionary operations:** Never pair `ContainsKey` with an indexer read/write. Use `TryGetValue`, `Remove(key, out value)`, and on `NET8_0_OR_GREATER` `CollectionsMarshal.GetValueRefOrAddDefault` / `CollectionsMarshal.GetValueRefOrNullRef` (`#if`-guarded cleanly for `.NET Framework`). +- **Single-lookup dictionary operations:** Never pair `ContainsKey` with an indexer read/write. Use `TryGetValue`, `Remove(key, out value)`, and `DictionaryCompat` for ref-based updates. Keep runtime choices such as `CollectionsMarshal` and their .NET Framework fallbacks in shared internal static helpers, not at the call sites. - **Zero closure allocations (`IDE0320`):** Mark all production lambdas and local functions `static`. Pass context explicitly through state parameters (`Scope.Create(state, static s => ...)`) using named positional `record` or `readonly record struct` types rather than value tuples across method boundaries. - **Cached event args and singletons:** Reuse `static readonly` `PropertyChangedEventArgs` (`Count`, `Item[]`), `NotifyCollectionChangedEventArgs` (`Reset`), empty `ChangeSet.Empty`, `Array.Empty()` / `[]`, and stateless `IComparer` instances instead of allocating per notification. - **Safe `ArrayPool` discipline:** Always return rented `ArrayPool.Shared` buffers inside `finally` (or via deterministic `PooledBatch.Dispose()`). Pass `clearArray: RuntimeHelpers.IsReferenceOrContainsReferences()` (or `Array.Clear(buffer, 0, count)`) when returning buffers so pooled arrays never retain references to user objects. Never use `stackalloc` inside a loop. diff --git a/README.md b/README.md index fdaa2a75..4da309a3 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ Supported targets: `net10.0`, `net11.0`, `net47`, `net471`, `net472`, `net48`, a - [Core concepts](#core-concepts) - [Collections](#collections) - [Views](#views) +- [Live queries](#live-queries) - [Extension methods](#extension-methods) - [API overview](#api-overview) - [Thread safety](#thread-safety) @@ -229,7 +230,7 @@ A cache notification (`CacheNotify`) describes one change to a collection. A | Member | Meaning | | --- | --- | -| `Action` | The `CacheAction` that occurred (`Added`, `Removed`, `Updated`, `Moved`, `Refreshed`, `Cleared`, `BatchOperation`, `BatchAdded`, or `BatchRemoved`). | +| `Action` | The `CacheAction` that occurred (`Added`, `Removed`, `Updated`, `Moved`, `Refreshed`, `Cleared`, `BatchOperation`, `BatchAdded`, `BatchRemoved`, or `Reset`). `Reset` means the contents were replaced as a whole: it is raised when a deferral ends with changes, and on `VersionedStream` after a replace, an edit, a silent clear or a removal by predicate. A `Reset` without a snapshot tells the consumer to copy the source again. | | `Item` | The affected item for single-item operations. | | `Batch` | The `PooledBatch` for batch operations. Call `AutoDisposeBatches()` or dispose the batch after reading it. | | `CurrentIndex` | The item's new index, or `-1` when no index applies. | @@ -238,7 +239,7 @@ A cache notification (`CacheNotify`) describes one change to a collection. A ### ChangeSet -A change set (`ChangeSet`) is a read-only list of `Change` entries for step-by-step diff processing, similar to DynamicData. Call `ToChangeSets()` on `Stream` or `Connect()` on a collection to receive change sets. +A change set (`ChangeSet`) is a read-only list of `Change` entries for step-by-step diff processing. Call `ToChangeSets()` on `Stream` or `Connect()` on a collection to receive change sets. Each `Change` carries a `ChangeReason` (`Add`, `Remove`, `Update`, `Move`, `Refresh`, or `Clear`) along with current and previous items and indexes. `ChangeSet` exposes `Count`, `Adds`, `Removes`, `Updates`, `Moves`, and `AsSpan()`. @@ -353,6 +354,59 @@ using var search = products.CreateView( public sealed record Product(string Name, string Category, bool IsActive); ``` +## Live queries + +Import `ReactiveList.Queries`, or `ReactiveList.Reactive.Queries` for the System.Reactive package. Start with a reactive collection's `Live` property and finish with a view or a stream: + +```csharp +using ReactiveList.Collections; +using ReactiveList.Queries; +using ReactiveUI.Primitives; +using ReactiveUI.Primitives.Concurrency; +using ReactiveUI.Primitives.Signals; + +using var orders = new ReactiveList(); +using var latestOpenOrders = orders.Live + .Where(static order => order.IsOpen) + .OrderByDescending(static order => order.Id) + .Take(20) + .ToView(Sequencer.Default); + +var openCount = orders.Live.Count(static order => order.IsOpen); +using var countSubscription = openCount.Subscribe(Console.WriteLine); + +orders.Add(new(1, IsOpen: true)); + +public sealed record Order(int Id, bool IsOpen); +``` + +The view uses one subscription to the source for filtering, sorting and the window. `Count`, `Any`, `Contains` and dictionary `ObserveValue` report the current result when you subscribe and emit again only when it changes. `SelectMany` merges one observable per matching item and detaches it when that item leaves the query. + +Query syntax works too, and each clause maps to one operator. A chain of `where`, `orderby`, `Skip`, `Take` and `select` still plans onto one view with one source subscription: + +```csharp +var page = from order in orders.Live + where order.IsOpen + orderby order.Id descending + select order.Id; +using var ids = page.ToView(Sequencer.Default); + +var byStatus = from order in orders.Live + orderby order.Id + group order.Id by order.IsOpen; +using var groups = byStatus.ToView(Sequencer.Default); +``` + +- **Order:** `OrderBy`, `ThenBy` and their descending forms are stable. Items that tie keep the order of the source. A sharded source has no stable order, so add a final `ThenBy` on a unique key when you need an exact result. +- **Windows:** `Skip` and `Take` compose as in LINQ, so `Take(10).Skip(2)` exposes the third to the tenth item. Either takes an `IObservable` and the window follows it. The view is empty until each observable emits. Moving a window changes only the items that enter or leave it. +- **Groups:** groups appear in the order their key first occurs in the query result, as `GroupBy` does in LINQ. Members keep the query order. `GroupBy(key, element)` holds a projected value in each group. A group view can be read from any thread while it changes. +- **Projections:** `Select` after `OrderBy`, `Skip` or `Take` projects what the window exposes and keeps the order and window. `Where`, `Count`, `Any`, `Contains` and `GroupBy` after such a projection see the projected items. + +`LiveView` and `LiveGroupView` expose `BatchResetLimit`, with the same default and meaning as the regular views. Set it to raise one reset for batches larger than the limit, or for a window move larger than the limit, instead of reporting each item separately. +If a source's items never change in place, initialize it with `Options = new() { ItemsAreImmutable = true }`. Views can then ignore refresh notifications. Replacements are still applied. + +Use `DeferNotifications()` on a reactive list or sharded collection to group several writes. Reads see each write as soon as it commits. When the last nested scope closes, the collection publishes one reset whose batch contains the final snapshot. Empty scopes publish nothing. + ## Extension methods ### `CacheNotifyExtensions` 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/Polyfills/ArgumentExceptionHelper.cs b/src/Polyfills/ArgumentExceptionHelper.cs new file mode 100644 index 00000000..35663501 --- /dev/null +++ b/src/Polyfills/ArgumentExceptionHelper.cs @@ -0,0 +1,30 @@ +// 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. + +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace ReactiveList.Polyfills; + +/// Polyfill for ArgumentNullException.ThrowIfNull on target frameworks that predate it. +[ExcludeFromCodeCoverage] +internal static class ArgumentExceptionHelper +{ + /// Throws an if is . + /// The reference type argument to validate as non-null. + /// The name of the parameter with which corresponds. + /// is . + internal static void ThrowIfNull( + [NotNull] object? argument, + [CallerArgumentExpression(nameof(argument))] + string? paramName = null) + { + if (argument is not null) + { + return; + } + + throw new ArgumentNullException(paramName); + } +} diff --git a/src/Polyfills/ArgumentOutOfRangeExceptionHelper.cs b/src/Polyfills/ArgumentOutOfRangeExceptionHelper.cs new file mode 100644 index 00000000..e3063407 --- /dev/null +++ b/src/Polyfills/ArgumentOutOfRangeExceptionHelper.cs @@ -0,0 +1,72 @@ +// 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. + +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace ReactiveList.Polyfills; + +/// Polyfill for modern guard helpers on target frameworks that predate them. +[ExcludeFromCodeCoverage] +internal static class ArgumentOutOfRangeExceptionHelper +{ + /// Throws when is negative. + /// The value to validate. + /// The parameter name. + /// is negative. + internal static void ThrowIfNegative(int value, [CallerArgumentExpression(nameof(value))] string? paramName = null) + { + if (value >= 0) + { + return; + } + + throw new ArgumentOutOfRangeException(paramName, value, null); + } + + /// Throws when is less than . + /// The value to validate. + /// The lower bound. + /// The parameter name. + /// is less than . + internal static void ThrowIfLessThan(int value, int other, [CallerArgumentExpression(nameof(value))] string? paramName = null) + { + if (value >= other) + { + return; + } + + throw new ArgumentOutOfRangeException(paramName, value, null); + } + + /// Throws when is greater than . + /// The value to validate. + /// The upper bound. + /// The parameter name. + /// is greater than . + internal static void ThrowIfGreaterThan(int value, int other, [CallerArgumentExpression(nameof(value))] string? paramName = null) + { + if (value <= other) + { + return; + } + + throw new ArgumentOutOfRangeException(paramName, value, null); + } + + /// Throws when is greater than or equal to . + /// The value to validate. + /// The exclusive upper bound. + /// The parameter name. + /// is greater than or equal to . + internal static void ThrowIfGreaterThanOrEqual(int value, int other, [CallerArgumentExpression(nameof(value))] string? paramName = null) + { + if (value < other) + { + return; + } + + throw new ArgumentOutOfRangeException(paramName, value, null); + } +} diff --git a/src/ReactiveList/Internal/CallerArgumentExpressionAttribute.cs b/src/Polyfills/CallerArgumentExpressionAttribute.cs similarity index 51% rename from src/ReactiveList/Internal/CallerArgumentExpressionAttribute.cs rename to src/Polyfills/CallerArgumentExpressionAttribute.cs index a47b1b69..3af8a10d 100644 --- a/src/ReactiveList/Internal/CallerArgumentExpressionAttribute.cs +++ b/src/Polyfills/CallerArgumentExpressionAttribute.cs @@ -2,7 +2,6 @@ // 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 NETFRAMEWORK namespace System.Runtime.CompilerServices; /// Indicates that a parameter captures the expression passed for another parameter. @@ -13,22 +12,3 @@ internal sealed class CallerArgumentExpressionAttribute(string parameterName) : /// Gets the source parameter name. public string ParameterName { get; } = parameterName; } -#elif REACTIVELIST_REACTIVE -namespace ReactiveList.Reactive.Internal; - -/// Marks the runtime-provided caller-argument-expression compatibility path. -file enum CallerArgumentExpressionAttribute -{ - /// Indicates that the target runtime provides the attribute. - RuntimeProvided = 0, -} -#else -namespace ReactiveList.Internal; - -/// Marks the runtime-provided caller-argument-expression compatibility path. -file enum CallerArgumentExpressionAttribute -{ - /// Indicates that the target runtime provides the attribute. - RuntimeProvided = 0, -} -#endif diff --git a/src/Polyfills/IsExternalInit.cs b/src/Polyfills/IsExternalInit.cs new file mode 100644 index 00000000..547bdf75 --- /dev/null +++ b/src/Polyfills/IsExternalInit.cs @@ -0,0 +1,14 @@ +// 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. + +namespace System.Runtime.CompilerServices; + +/// Reserved for compiler support. +internal sealed class IsExternalInit +{ + /// Initializes a new instance of the class. + internal IsExternalInit() + { + } +} diff --git a/src/ReactiveList/Internal/MaybeNullWhenAttribute.cs b/src/Polyfills/MaybeNullWhenAttribute.cs similarity index 54% rename from src/ReactiveList/Internal/MaybeNullWhenAttribute.cs rename to src/Polyfills/MaybeNullWhenAttribute.cs index e364a3ab..82546ae7 100644 --- a/src/ReactiveList/Internal/MaybeNullWhenAttribute.cs +++ b/src/Polyfills/MaybeNullWhenAttribute.cs @@ -2,7 +2,6 @@ // 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 NETFRAMEWORK namespace System.Diagnostics.CodeAnalysis; /// Specifies that an output may be null when the method returns the specified value. @@ -13,22 +12,3 @@ internal sealed class MaybeNullWhenAttribute(bool returnValue) : Attribute /// Gets a value indicating whether the attribute condition applies on true returns. public bool ReturnValue { get; } = returnValue; } -#elif REACTIVELIST_REACTIVE -namespace ReactiveList.Reactive.Internal; - -/// Marks the runtime-provided nullable-annotation compatibility path. -file enum MaybeNullWhenAttribute -{ - /// Indicates that the target runtime provides the attribute. - RuntimeProvided = 0, -} -#else -namespace ReactiveList.Internal; - -/// Marks the runtime-provided nullable-annotation compatibility path. -file enum MaybeNullWhenAttribute -{ - /// Indicates that the target runtime provides the attribute. - RuntimeProvided = 0, -} -#endif diff --git a/src/Polyfills/NotNullAttribute.cs b/src/Polyfills/NotNullAttribute.cs new file mode 100644 index 00000000..45b0adba --- /dev/null +++ b/src/Polyfills/NotNullAttribute.cs @@ -0,0 +1,9 @@ +// 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. + +namespace System.Diagnostics.CodeAnalysis; + +/// Specifies that an output is not even if the corresponding type allows it. +[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue)] +internal sealed class NotNullAttribute : Attribute; diff --git a/src/Polyfills/ObjectDisposedExceptionHelper.cs b/src/Polyfills/ObjectDisposedExceptionHelper.cs new file mode 100644 index 00000000..c30bf886 --- /dev/null +++ b/src/Polyfills/ObjectDisposedExceptionHelper.cs @@ -0,0 +1,26 @@ +// 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. + +using System.Diagnostics.CodeAnalysis; + +namespace ReactiveList.Polyfills; + +/// Polyfill for ObjectDisposedException.ThrowIf on target frameworks that predate it. +[ExcludeFromCodeCoverage] +internal static class ObjectDisposedExceptionHelper +{ + /// Throws an if is . + /// The condition to evaluate for a disposed instance. + /// The object whose type name is used to build the exception message. + /// is . + internal static void ThrowIf(bool condition, object instance) + { + if (!condition) + { + return; + } + + throw new ObjectDisposedException(instance?.GetType().FullName); + } +} diff --git a/src/Polyfills/Polyfills.props b/src/Polyfills/Polyfills.props new file mode 100644 index 00000000..45ea2c46 --- /dev/null +++ b/src/Polyfills/Polyfills.props @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/src/Polyfills/SkipLocalsInitAttribute.cs b/src/Polyfills/SkipLocalsInitAttribute.cs new file mode 100644 index 00000000..e6d5b3cf --- /dev/null +++ b/src/Polyfills/SkipLocalsInitAttribute.cs @@ -0,0 +1,9 @@ +// 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. + +namespace System.Runtime.CompilerServices; + +/// Indicates that local variables should not be zero-initialized. +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Module)] +internal sealed class SkipLocalsInitAttribute : Attribute; diff --git a/src/ReactiveList.Reactive/PublicAPI/net10.0/PublicAPI.txt b/src/ReactiveList.Reactive/PublicAPI/net10.0/PublicAPI.txt index 3d3f45d6..8cfe769b 100644 --- a/src/ReactiveList.Reactive/PublicAPI/net10.0/PublicAPI.txt +++ b/src/ReactiveList.Reactive/PublicAPI/net10.0/PublicAPI.txt @@ -167,7 +167,7 @@ namespace ReactiveList.Reactive.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -181,14 +181,14 @@ namespace ReactiveList.Reactive.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Reactive.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -226,6 +226,21 @@ namespace ReactiveList.Reactive.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] [System.Runtime.CompilerServices.SkipLocalsInit] public sealed class QuadDictionary : ReactiveList.Reactive.Collections.IQuad> @@ -325,64 +340,23 @@ namespace ReactiveList.Reactive.Collections public static bool operator !=(ReactiveList.Reactive.Collections.QuadList.Enumerator left, ReactiveList.Reactive.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Reactive.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + [System.Runtime.CompilerServices.SkipLocalsInit] + public sealed class QuaternaryDictionary : ReactiveList.Reactive.Collections.IQuaternaryDictionary, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item, ReactiveList.Reactive.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - [System.Runtime.CompilerServices.SkipLocalsInit] - public class QuaternaryDictionary : ReactiveList.Reactive.Collections.QuaternaryBase, TValue>, ReactiveList.Reactive.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -390,17 +364,22 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler) where TIndexKey : notnull { } public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -410,64 +389,183 @@ namespace ReactiveList.Reactive.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] [System.Runtime.CompilerServices.SkipLocalsInit] - public class QuaternaryList : ReactiveList.Reactive.Collections.QuaternaryBase, ReactiveList.Reactive.Collections.IQuaternaryList where T : notnull + public sealed class QuaternaryList : ReactiveList.Reactive.Collections.IQuaternaryList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Reactive.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Reactive.Collections.IReactiveList>, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Reactive.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Reactive.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Reactive.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Reactive.Collections.ReactiveList item, ReactiveList.Reactive.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -484,11 +582,13 @@ namespace ReactiveList.Reactive.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -501,6 +601,7 @@ namespace ReactiveList.Reactive.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -511,9 +612,11 @@ namespace ReactiveList.Reactive.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -525,7 +628,6 @@ namespace ReactiveList.Reactive.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -552,6 +654,19 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Reactive.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Reactive.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Reactive.Core { @@ -566,6 +681,7 @@ namespace ReactiveList.Reactive.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -783,7 +899,7 @@ namespace ReactiveList.Reactive.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -796,12 +912,180 @@ namespace ReactiveList.Reactive.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Reactive.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Reactive.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Reactive.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Reactive.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Reactive.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.IObservable> filterObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -819,19 +1103,20 @@ namespace ReactiveList.Reactive.Views public ReactiveList.Reactive.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Reactive.Collections.IReactiveSource source, System.IObservable> filterObservable, in System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Reactive.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -852,6 +1137,7 @@ namespace ReactiveList.Reactive.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Reactive.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -872,6 +1158,7 @@ namespace ReactiveList.Reactive.Views public sealed class FilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func filter, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -892,6 +1179,7 @@ namespace ReactiveList.Reactive.Views public sealed class GroupedReactiveView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func keySelector, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -922,19 +1210,20 @@ namespace ReactiveList.Reactive.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, in System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, in System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -955,6 +1244,7 @@ namespace ReactiveList.Reactive.Views public sealed class SortedReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList.Reactive/PublicAPI/net11.0/PublicAPI.txt b/src/ReactiveList.Reactive/PublicAPI/net11.0/PublicAPI.txt index 3d3f45d6..8cfe769b 100644 --- a/src/ReactiveList.Reactive/PublicAPI/net11.0/PublicAPI.txt +++ b/src/ReactiveList.Reactive/PublicAPI/net11.0/PublicAPI.txt @@ -167,7 +167,7 @@ namespace ReactiveList.Reactive.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -181,14 +181,14 @@ namespace ReactiveList.Reactive.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Reactive.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -226,6 +226,21 @@ namespace ReactiveList.Reactive.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] [System.Runtime.CompilerServices.SkipLocalsInit] public sealed class QuadDictionary : ReactiveList.Reactive.Collections.IQuad> @@ -325,64 +340,23 @@ namespace ReactiveList.Reactive.Collections public static bool operator !=(ReactiveList.Reactive.Collections.QuadList.Enumerator left, ReactiveList.Reactive.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Reactive.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + [System.Runtime.CompilerServices.SkipLocalsInit] + public sealed class QuaternaryDictionary : ReactiveList.Reactive.Collections.IQuaternaryDictionary, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item, ReactiveList.Reactive.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - [System.Runtime.CompilerServices.SkipLocalsInit] - public class QuaternaryDictionary : ReactiveList.Reactive.Collections.QuaternaryBase, TValue>, ReactiveList.Reactive.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -390,17 +364,22 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler) where TIndexKey : notnull { } public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -410,64 +389,183 @@ namespace ReactiveList.Reactive.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] [System.Runtime.CompilerServices.SkipLocalsInit] - public class QuaternaryList : ReactiveList.Reactive.Collections.QuaternaryBase, ReactiveList.Reactive.Collections.IQuaternaryList where T : notnull + public sealed class QuaternaryList : ReactiveList.Reactive.Collections.IQuaternaryList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Reactive.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Reactive.Collections.IReactiveList>, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Reactive.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Reactive.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Reactive.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Reactive.Collections.ReactiveList item, ReactiveList.Reactive.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -484,11 +582,13 @@ namespace ReactiveList.Reactive.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -501,6 +601,7 @@ namespace ReactiveList.Reactive.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -511,9 +612,11 @@ namespace ReactiveList.Reactive.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -525,7 +628,6 @@ namespace ReactiveList.Reactive.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -552,6 +654,19 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Reactive.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Reactive.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Reactive.Core { @@ -566,6 +681,7 @@ namespace ReactiveList.Reactive.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -783,7 +899,7 @@ namespace ReactiveList.Reactive.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -796,12 +912,180 @@ namespace ReactiveList.Reactive.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Reactive.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Reactive.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Reactive.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Reactive.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Reactive.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.IObservable> filterObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -819,19 +1103,20 @@ namespace ReactiveList.Reactive.Views public ReactiveList.Reactive.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Reactive.Collections.IReactiveSource source, System.IObservable> filterObservable, in System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Reactive.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -852,6 +1137,7 @@ namespace ReactiveList.Reactive.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Reactive.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -872,6 +1158,7 @@ namespace ReactiveList.Reactive.Views public sealed class FilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func filter, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -892,6 +1179,7 @@ namespace ReactiveList.Reactive.Views public sealed class GroupedReactiveView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func keySelector, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -922,19 +1210,20 @@ namespace ReactiveList.Reactive.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, in System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, in System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -955,6 +1244,7 @@ namespace ReactiveList.Reactive.Views public sealed class SortedReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList.Reactive/PublicAPI/net47/PublicAPI.txt b/src/ReactiveList.Reactive/PublicAPI/net47/PublicAPI.txt index 2ac4eca6..3aecc9be 100644 --- a/src/ReactiveList.Reactive/PublicAPI/net47/PublicAPI.txt +++ b/src/ReactiveList.Reactive/PublicAPI/net47/PublicAPI.txt @@ -167,7 +167,7 @@ namespace ReactiveList.Reactive.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -181,14 +181,14 @@ namespace ReactiveList.Reactive.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Reactive.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -226,6 +226,21 @@ namespace ReactiveList.Reactive.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] public sealed class QuadDictionary : ReactiveList.Reactive.Collections.IQuad> { @@ -323,63 +338,22 @@ namespace ReactiveList.Reactive.Collections public static bool operator !=(ReactiveList.Reactive.Collections.QuadList.Enumerator left, ReactiveList.Reactive.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Reactive.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + public sealed class QuaternaryDictionary : ReactiveList.Reactive.Collections.IQuaternaryDictionary, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item, ReactiveList.Reactive.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - public class QuaternaryDictionary : ReactiveList.Reactive.Collections.QuaternaryBase, TValue>, ReactiveList.Reactive.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -387,17 +361,22 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler) where TIndexKey : notnull { } public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -407,63 +386,182 @@ namespace ReactiveList.Reactive.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] - public class QuaternaryList : ReactiveList.Reactive.Collections.QuaternaryBase, ReactiveList.Reactive.Collections.IQuaternaryList where T : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] + public sealed class QuaternaryList : ReactiveList.Reactive.Collections.IQuaternaryList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Reactive.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Reactive.Collections.IReactiveList>, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Reactive.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Reactive.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Reactive.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Reactive.Collections.ReactiveList item, ReactiveList.Reactive.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -480,11 +578,13 @@ namespace ReactiveList.Reactive.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -497,6 +597,7 @@ namespace ReactiveList.Reactive.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -507,9 +608,11 @@ namespace ReactiveList.Reactive.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -521,7 +624,6 @@ namespace ReactiveList.Reactive.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -548,6 +650,19 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Reactive.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Reactive.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Reactive.Core { @@ -562,6 +677,7 @@ namespace ReactiveList.Reactive.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -779,7 +895,7 @@ namespace ReactiveList.Reactive.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -792,12 +908,180 @@ namespace ReactiveList.Reactive.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Reactive.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Reactive.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Reactive.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Reactive.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Reactive.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.IObservable> filterObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -815,19 +1099,20 @@ namespace ReactiveList.Reactive.Views public ReactiveList.Reactive.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Reactive.Collections.IReactiveSource source, System.IObservable> filterObservable, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Reactive.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -848,6 +1133,7 @@ namespace ReactiveList.Reactive.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Reactive.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -868,6 +1154,7 @@ namespace ReactiveList.Reactive.Views public sealed class FilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func filter, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -888,6 +1175,7 @@ namespace ReactiveList.Reactive.Views public sealed class GroupedReactiveView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func keySelector, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -918,19 +1206,20 @@ namespace ReactiveList.Reactive.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -951,6 +1240,7 @@ namespace ReactiveList.Reactive.Views public sealed class SortedReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList.Reactive/PublicAPI/net471/PublicAPI.txt b/src/ReactiveList.Reactive/PublicAPI/net471/PublicAPI.txt index 2ac4eca6..3aecc9be 100644 --- a/src/ReactiveList.Reactive/PublicAPI/net471/PublicAPI.txt +++ b/src/ReactiveList.Reactive/PublicAPI/net471/PublicAPI.txt @@ -167,7 +167,7 @@ namespace ReactiveList.Reactive.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -181,14 +181,14 @@ namespace ReactiveList.Reactive.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Reactive.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -226,6 +226,21 @@ namespace ReactiveList.Reactive.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] public sealed class QuadDictionary : ReactiveList.Reactive.Collections.IQuad> { @@ -323,63 +338,22 @@ namespace ReactiveList.Reactive.Collections public static bool operator !=(ReactiveList.Reactive.Collections.QuadList.Enumerator left, ReactiveList.Reactive.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Reactive.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + public sealed class QuaternaryDictionary : ReactiveList.Reactive.Collections.IQuaternaryDictionary, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item, ReactiveList.Reactive.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - public class QuaternaryDictionary : ReactiveList.Reactive.Collections.QuaternaryBase, TValue>, ReactiveList.Reactive.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -387,17 +361,22 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler) where TIndexKey : notnull { } public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -407,63 +386,182 @@ namespace ReactiveList.Reactive.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] - public class QuaternaryList : ReactiveList.Reactive.Collections.QuaternaryBase, ReactiveList.Reactive.Collections.IQuaternaryList where T : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] + public sealed class QuaternaryList : ReactiveList.Reactive.Collections.IQuaternaryList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Reactive.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Reactive.Collections.IReactiveList>, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Reactive.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Reactive.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Reactive.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Reactive.Collections.ReactiveList item, ReactiveList.Reactive.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -480,11 +578,13 @@ namespace ReactiveList.Reactive.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -497,6 +597,7 @@ namespace ReactiveList.Reactive.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -507,9 +608,11 @@ namespace ReactiveList.Reactive.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -521,7 +624,6 @@ namespace ReactiveList.Reactive.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -548,6 +650,19 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Reactive.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Reactive.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Reactive.Core { @@ -562,6 +677,7 @@ namespace ReactiveList.Reactive.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -779,7 +895,7 @@ namespace ReactiveList.Reactive.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -792,12 +908,180 @@ namespace ReactiveList.Reactive.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Reactive.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Reactive.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Reactive.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Reactive.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Reactive.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.IObservable> filterObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -815,19 +1099,20 @@ namespace ReactiveList.Reactive.Views public ReactiveList.Reactive.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Reactive.Collections.IReactiveSource source, System.IObservable> filterObservable, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Reactive.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -848,6 +1133,7 @@ namespace ReactiveList.Reactive.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Reactive.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -868,6 +1154,7 @@ namespace ReactiveList.Reactive.Views public sealed class FilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func filter, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -888,6 +1175,7 @@ namespace ReactiveList.Reactive.Views public sealed class GroupedReactiveView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func keySelector, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -918,19 +1206,20 @@ namespace ReactiveList.Reactive.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -951,6 +1240,7 @@ namespace ReactiveList.Reactive.Views public sealed class SortedReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList.Reactive/PublicAPI/net472/PublicAPI.txt b/src/ReactiveList.Reactive/PublicAPI/net472/PublicAPI.txt index 2ac4eca6..3aecc9be 100644 --- a/src/ReactiveList.Reactive/PublicAPI/net472/PublicAPI.txt +++ b/src/ReactiveList.Reactive/PublicAPI/net472/PublicAPI.txt @@ -167,7 +167,7 @@ namespace ReactiveList.Reactive.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -181,14 +181,14 @@ namespace ReactiveList.Reactive.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Reactive.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -226,6 +226,21 @@ namespace ReactiveList.Reactive.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] public sealed class QuadDictionary : ReactiveList.Reactive.Collections.IQuad> { @@ -323,63 +338,22 @@ namespace ReactiveList.Reactive.Collections public static bool operator !=(ReactiveList.Reactive.Collections.QuadList.Enumerator left, ReactiveList.Reactive.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Reactive.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + public sealed class QuaternaryDictionary : ReactiveList.Reactive.Collections.IQuaternaryDictionary, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item, ReactiveList.Reactive.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - public class QuaternaryDictionary : ReactiveList.Reactive.Collections.QuaternaryBase, TValue>, ReactiveList.Reactive.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -387,17 +361,22 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler) where TIndexKey : notnull { } public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -407,63 +386,182 @@ namespace ReactiveList.Reactive.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] - public class QuaternaryList : ReactiveList.Reactive.Collections.QuaternaryBase, ReactiveList.Reactive.Collections.IQuaternaryList where T : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] + public sealed class QuaternaryList : ReactiveList.Reactive.Collections.IQuaternaryList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Reactive.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Reactive.Collections.IReactiveList>, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Reactive.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Reactive.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Reactive.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Reactive.Collections.ReactiveList item, ReactiveList.Reactive.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -480,11 +578,13 @@ namespace ReactiveList.Reactive.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -497,6 +597,7 @@ namespace ReactiveList.Reactive.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -507,9 +608,11 @@ namespace ReactiveList.Reactive.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -521,7 +624,6 @@ namespace ReactiveList.Reactive.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -548,6 +650,19 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Reactive.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Reactive.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Reactive.Core { @@ -562,6 +677,7 @@ namespace ReactiveList.Reactive.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -779,7 +895,7 @@ namespace ReactiveList.Reactive.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -792,12 +908,180 @@ namespace ReactiveList.Reactive.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Reactive.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Reactive.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Reactive.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Reactive.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Reactive.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.IObservable> filterObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -815,19 +1099,20 @@ namespace ReactiveList.Reactive.Views public ReactiveList.Reactive.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Reactive.Collections.IReactiveSource source, System.IObservable> filterObservable, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Reactive.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -848,6 +1133,7 @@ namespace ReactiveList.Reactive.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Reactive.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -868,6 +1154,7 @@ namespace ReactiveList.Reactive.Views public sealed class FilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func filter, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -888,6 +1175,7 @@ namespace ReactiveList.Reactive.Views public sealed class GroupedReactiveView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func keySelector, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -918,19 +1206,20 @@ namespace ReactiveList.Reactive.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -951,6 +1240,7 @@ namespace ReactiveList.Reactive.Views public sealed class SortedReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList.Reactive/PublicAPI/net48/PublicAPI.txt b/src/ReactiveList.Reactive/PublicAPI/net48/PublicAPI.txt index 2ac4eca6..3aecc9be 100644 --- a/src/ReactiveList.Reactive/PublicAPI/net48/PublicAPI.txt +++ b/src/ReactiveList.Reactive/PublicAPI/net48/PublicAPI.txt @@ -167,7 +167,7 @@ namespace ReactiveList.Reactive.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -181,14 +181,14 @@ namespace ReactiveList.Reactive.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Reactive.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -226,6 +226,21 @@ namespace ReactiveList.Reactive.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] public sealed class QuadDictionary : ReactiveList.Reactive.Collections.IQuad> { @@ -323,63 +338,22 @@ namespace ReactiveList.Reactive.Collections public static bool operator !=(ReactiveList.Reactive.Collections.QuadList.Enumerator left, ReactiveList.Reactive.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Reactive.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + public sealed class QuaternaryDictionary : ReactiveList.Reactive.Collections.IQuaternaryDictionary, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item, ReactiveList.Reactive.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - public class QuaternaryDictionary : ReactiveList.Reactive.Collections.QuaternaryBase, TValue>, ReactiveList.Reactive.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -387,17 +361,22 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler) where TIndexKey : notnull { } public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -407,63 +386,182 @@ namespace ReactiveList.Reactive.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] - public class QuaternaryList : ReactiveList.Reactive.Collections.QuaternaryBase, ReactiveList.Reactive.Collections.IQuaternaryList where T : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] + public sealed class QuaternaryList : ReactiveList.Reactive.Collections.IQuaternaryList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Reactive.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Reactive.Collections.IReactiveList>, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Reactive.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Reactive.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Reactive.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Reactive.Collections.ReactiveList item, ReactiveList.Reactive.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -480,11 +578,13 @@ namespace ReactiveList.Reactive.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -497,6 +597,7 @@ namespace ReactiveList.Reactive.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -507,9 +608,11 @@ namespace ReactiveList.Reactive.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -521,7 +624,6 @@ namespace ReactiveList.Reactive.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -548,6 +650,19 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Reactive.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Reactive.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Reactive.Core { @@ -562,6 +677,7 @@ namespace ReactiveList.Reactive.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -779,7 +895,7 @@ namespace ReactiveList.Reactive.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -792,12 +908,180 @@ namespace ReactiveList.Reactive.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Reactive.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Reactive.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Reactive.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Reactive.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Reactive.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.IObservable> filterObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -815,19 +1099,20 @@ namespace ReactiveList.Reactive.Views public ReactiveList.Reactive.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Reactive.Collections.IReactiveSource source, System.IObservable> filterObservable, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Reactive.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -848,6 +1133,7 @@ namespace ReactiveList.Reactive.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Reactive.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -868,6 +1154,7 @@ namespace ReactiveList.Reactive.Views public sealed class FilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func filter, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -888,6 +1175,7 @@ namespace ReactiveList.Reactive.Views public sealed class GroupedReactiveView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func keySelector, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -918,19 +1206,20 @@ namespace ReactiveList.Reactive.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -951,6 +1240,7 @@ namespace ReactiveList.Reactive.Views public sealed class SortedReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList.Reactive/PublicAPI/net481/PublicAPI.txt b/src/ReactiveList.Reactive/PublicAPI/net481/PublicAPI.txt index 2ac4eca6..3aecc9be 100644 --- a/src/ReactiveList.Reactive/PublicAPI/net481/PublicAPI.txt +++ b/src/ReactiveList.Reactive/PublicAPI/net481/PublicAPI.txt @@ -167,7 +167,7 @@ namespace ReactiveList.Reactive.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -181,14 +181,14 @@ namespace ReactiveList.Reactive.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Reactive.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -226,6 +226,21 @@ namespace ReactiveList.Reactive.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] public sealed class QuadDictionary : ReactiveList.Reactive.Collections.IQuad> { @@ -323,63 +338,22 @@ namespace ReactiveList.Reactive.Collections public static bool operator !=(ReactiveList.Reactive.Collections.QuadList.Enumerator left, ReactiveList.Reactive.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Reactive.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + public sealed class QuaternaryDictionary : ReactiveList.Reactive.Collections.IQuaternaryDictionary, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Reactive.Core.CacheAction action, TItem? item, ReactiveList.Reactive.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - public class QuaternaryDictionary : ReactiveList.Reactive.Collections.QuaternaryBase, TValue>, ReactiveList.Reactive.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -387,17 +361,22 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler) where TIndexKey : notnull { } public ReactiveList.Reactive.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, System.Reactive.Concurrency.IScheduler scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -407,63 +386,182 @@ namespace ReactiveList.Reactive.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] - public class QuaternaryList : ReactiveList.Reactive.Collections.QuaternaryBase, ReactiveList.Reactive.Collections.IQuaternaryList where T : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] + public sealed class QuaternaryList : ReactiveList.Reactive.Collections.IQuaternaryList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Reactive.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Reactive.Collections.IReactiveList>, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Reactive.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Reactive.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Reactive.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Reactive.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Reactive.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Reactive.Collections.ReactiveList item, ReactiveList.Reactive.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Reactive.Collections.IReactiveList, ReactiveList.Reactive.Collections.IReactiveSourceWithOptions, ReactiveList.Reactive.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -480,11 +578,13 @@ namespace ReactiveList.Reactive.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Reactive.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -497,6 +597,7 @@ namespace ReactiveList.Reactive.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -507,9 +608,11 @@ namespace ReactiveList.Reactive.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Reactive.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -521,7 +624,6 @@ namespace ReactiveList.Reactive.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -548,6 +650,19 @@ namespace ReactiveList.Reactive.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Reactive.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Reactive.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Reactive.Core { @@ -562,6 +677,7 @@ namespace ReactiveList.Reactive.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -779,7 +895,7 @@ namespace ReactiveList.Reactive.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Reactive.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -792,12 +908,180 @@ namespace ReactiveList.Reactive.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Reactive.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveGroupView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Reactive.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Reactive.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Reactive.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Reactive.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Reactive.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Reactive.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Reactive.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + public readonly ReactiveList.Reactive.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Reactive.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Reactive.Queries.LiveView ToView(System.Reactive.Concurrency.IScheduler? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Reactive.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.IObservable> filterObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -815,19 +1099,20 @@ namespace ReactiveList.Reactive.Views public ReactiveList.Reactive.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Reactive.Collections.IReactiveSource source, System.IObservable> filterObservable, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Reactive.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -848,6 +1133,7 @@ namespace ReactiveList.Reactive.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Reactive.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -868,6 +1154,7 @@ namespace ReactiveList.Reactive.Views public sealed class FilteredReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func filter, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -888,6 +1175,7 @@ namespace ReactiveList.Reactive.Views public sealed class GroupedReactiveView : ReactiveList.Reactive.Views.IReactiveView, ReactiveList.Reactive.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Func keySelector, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -918,19 +1206,20 @@ namespace ReactiveList.Reactive.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, System.Reactive.Concurrency.IScheduler scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Reactive.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Reactive.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -951,6 +1240,7 @@ namespace ReactiveList.Reactive.Views public sealed class SortedReactiveView : ReactiveList.Reactive.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Reactive.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, System.Reactive.Concurrency.IScheduler scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList.Reactive/ReactiveList.Reactive.csproj b/src/ReactiveList.Reactive/ReactiveList.Reactive.csproj index bce0872b..804f0537 100644 --- a/src/ReactiveList.Reactive/ReactiveList.Reactive.csproj +++ b/src/ReactiveList.Reactive/ReactiveList.Reactive.csproj @@ -37,6 +37,8 @@ + + @@ -55,6 +57,7 @@ + diff --git a/src/ReactiveList/Collections/IQuad.cs b/src/ReactiveList/Collections/IQuad.cs index 09a82e1e..53c4a16f 100644 --- a/src/ReactiveList/Collections/IQuad.cs +++ b/src/ReactiveList/Collections/IQuad.cs @@ -12,7 +12,7 @@ namespace ReactiveList.Collections; /// /// IQuad represents an internal shard that stores elements. It is optimized for fast add/remove /// operations and is not intended to emit its own change notifications. Change tracking is handled -/// by the parent QuaternaryBase collection through its Stream pipeline. +/// by the parent sharded collection through its Stream pipeline. /// public interface IQuad : IEnumerable, IDisposable { diff --git a/src/ReactiveList/Collections/IQuaternaryDictionary.cs b/src/ReactiveList/Collections/IQuaternaryDictionary.cs index 6d8b239e..7e940268 100644 --- a/src/ReactiveList/Collections/IQuaternaryDictionary.cs +++ b/src/ReactiveList/Collections/IQuaternaryDictionary.cs @@ -41,12 +41,12 @@ public interface IQuaternaryDictionary : IDictionary /// Adds a value index with the specified name, using the provided key selector to generate index keys for values. /// The type of the key used for indexing. Must be non-nullable. - /// The unique name of the value index to add. Cannot be null or empty. + /// The unique name of the value index to add. Cannot be null or empty. /// A function that extracts the index key from a value. Cannot be null. /// Value indexes enable efficient lookups and queries based on the key generated by the /// key selector. Adding an index with a duplicate name may result in an error or overwrite, depending on the /// implementation. - void AddValueIndex(string name, Func keySelector) + void AddValueIndex(string indexName, Func keySelector) where TIndexKey : notnull; /// Attempts to add the specified key and value to the collection. diff --git a/src/ReactiveList/Collections/IQuaternaryList.cs b/src/ReactiveList/Collections/IQuaternaryList.cs index f51feeb3..525f5bbf 100644 --- a/src/ReactiveList/Collections/IQuaternaryList.cs +++ b/src/ReactiveList/Collections/IQuaternaryList.cs @@ -30,14 +30,14 @@ public interface IQuaternaryList : ICollection, IReactiveSource new IEnumerator GetEnumerator(); /// Adds an index to the collection using the specified name and key selector. - /// The type of the key used for the index. Must be non-nullable. - /// The unique name of the index to add. Cannot be null or empty. + /// The type of the key used for the index. Must be non-nullable. + /// The unique name of the index to add. Cannot be null or empty. /// A function that extracts the key from each element in the collection. Cannot be null. /// If an index with the specified name already exists, this method may throw an exception or /// overwrite the existing index, depending on the implementation. Indexes can improve lookup performance for /// queries using the specified key. - void AddIndex(string name, Func keySelector) - where TKey : notnull; + void AddIndex(string indexName, Func keySelector) + where TIndexKey : notnull; /// Adds the elements of the specified collection to the end of the list. /// The collection whose elements should be added to the end of the list. The collection itself cannot be null, but @@ -47,19 +47,19 @@ void AddIndex(string name, Func keySelector) void AddRange(IEnumerable collection); /// Retrieves all entities of type T that match the specified key in the given index. - /// The type of the key used to query the index. Must be non-nullable. + /// The type of the key used to query the index. Must be non-nullable. /// The name of the index to query. Specifies which index to use for the lookup. /// The key value to search for within the specified index. Must not be null. /// An enumerable collection of entities of type T that match the specified key. The collection is empty if no /// matching entities are found. - IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) - where TKey : notnull; + IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) + where TIndexKey : notnull; /// Removes all elements in the specified collection from the current collection. /// The collection of elements to remove from the current collection. All matching elements will be removed. Cannot /// be null. /// If an element in the specified collection does not exist in the current collection, it is - /// ignored. The method removes all occurrences of each element found in the collection. + /// ignored. An element that appears n times in the specified collection removes up to n equal copies. void RemoveRange(IEnumerable collection); /// Removes all elements that match the specified predicate from the collection. @@ -76,8 +76,8 @@ IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) void Edit(Action> editAction); /// Replaces all existing items with new items atomically, emitting a single change notification. - /// The new items to replace all existing items with. Cannot be null. + /// The new items to replace all existing items with. Cannot be null. /// This operation clears all existing items and adds the new items in a single atomic operation. /// Only one change notification is emitted for the entire operation. - void ReplaceAll(IEnumerable items); + void ReplaceAll(IEnumerable collection); } diff --git a/src/ReactiveList/Collections/IReactiveSource.cs b/src/ReactiveList/Collections/IReactiveSource.cs index 14b01e8b..c9011369 100644 --- a/src/ReactiveList/Collections/IReactiveSource.cs +++ b/src/ReactiveList/Collections/IReactiveSource.cs @@ -10,7 +10,7 @@ namespace ReactiveList.Collections; /// Base interface for all reactive collections providing change observation. /// The type of elements in the collection. Must be non-nullable. /// -/// This interface provides a unified API for reactive collections, compatible with DynamicData patterns. +/// This interface provides a unified API for reactive collections: a count, a version, and a stream of change notifications. /// All implementations should support change tracking via IObservable streams. /// public interface IReactiveSource : IEnumerable, INotifyCollectionChanged, IDisposable @@ -36,6 +36,7 @@ public interface IReactiveSource : IEnumerable, INotifyCollectionChanged, /// /// Single item changes (Added, Removed, Updated, Moved, Refreshed) /// Batch operations (BatchAdded, BatchRemoved, BatchOperation) + /// Full replacement snapshots (Reset) /// Clear operations (Cleared) /// /// The Stream uses a channel-based pipeline for efficient, low-allocation event delivery. @@ -46,10 +47,7 @@ public interface IReactiveSource : IEnumerable, INotifyCollectionChanged, /// An enumerator for the source. new IEnumerator GetEnumerator(); -#if NET6_0_OR_GREATER || NETFRAMEWORK - /// Creates a snapshot of current items as an array. /// An array containing all current items. T[] ToArray(); -#endif } diff --git a/src/ReactiveList/Collections/IReactiveSourceWithOptions.cs b/src/ReactiveList/Collections/IReactiveSourceWithOptions.cs new file mode 100644 index 00000000..aa520efd --- /dev/null +++ b/src/ReactiveList/Collections/IReactiveSourceWithOptions.cs @@ -0,0 +1,16 @@ +// 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.Collections; +#else +namespace ReactiveList.Collections; +#endif + +/// Lets a reactive source specify optional behavior for views that subscribe to it. +public interface IReactiveSourceWithOptions +{ + /// Gets the options that apply for the lifetime of the source. + ReactiveSourceOptions Options { get; } +} diff --git a/src/ReactiveList/Collections/IVersionedSnapshotSource.cs b/src/ReactiveList/Collections/IVersionedSnapshotSource.cs new file mode 100644 index 00000000..052173be --- /dev/null +++ b/src/ReactiveList/Collections/IVersionedSnapshotSource.cs @@ -0,0 +1,28 @@ +// 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.Collections; +#else +namespace ReactiveList.Collections; +#endif + +/// A collection that can copy its items together with the version the copy corresponds to, and that publishes each change with its version. +/// The item type. +/// Use this to build a view that starts from a snapshot and then replays changes without missing or double-applying one: +/// subscribe to , take a snapshot with , then ignore every +/// notification whose version is at most the snapshot version. Apply the remaining changes in delivery order. +/// A batch operation without an item payload requires taking a new snapshot. +public interface IVersionedSnapshotSource + where T : notnull +{ + /// Gets an observable of change notifications, each paired with the version the change produced. + /// Changes made while nobody was subscribed are not replayed. + IObservable> VersionedStream { get; } + + /// Copies every item and reports the version of that copy. + /// The stream version the copy corresponds to. + /// The items. A notification whose version is at most is already reflected in them. + T[] CopyVersioned(out long version); +} diff --git a/src/ReactiveList/Collections/NotificationDeferral.cs b/src/ReactiveList/Collections/NotificationDeferral.cs new file mode 100644 index 00000000..adee6f1b --- /dev/null +++ b/src/ReactiveList/Collections/NotificationDeferral.cs @@ -0,0 +1,26 @@ +// 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.Collections; +#else +namespace ReactiveList.Collections; +#endif + +/// Releases one collection-wide notification deferral when disposed. +/// Copies refer to the same deferral. Disposing a default value has no effect. +[System.Diagnostics.DebuggerDisplay("Notification deferral")] +public readonly record struct NotificationDeferral : IDisposable +{ + /// The release shared by every copy of this token. + private readonly NotificationDeferralState? _state; + + /// Initializes a new instance of the struct. + /// The release state. + internal NotificationDeferral(NotificationDeferralState state) => _state = state; + + /// Releases this deferral. Notifications resume when the last deferral is released. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _state?.Release(); +} diff --git a/src/ReactiveList/Collections/QuadDictionary.cs b/src/ReactiveList/Collections/QuadDictionary.cs index bbc357ed..eb0405e3 100644 --- a/src/ReactiveList/Collections/QuadDictionary.cs +++ b/src/ReactiveList/Collections/QuadDictionary.cs @@ -18,7 +18,7 @@ namespace ReactiveList.Collections; /// and memory efficiency is important. It uses array pooling to minimize allocations and supports custom equality /// comparers for keys. The dictionary is not thread-safe and should not be accessed concurrently from multiple threads. /// Call Dispose to return internal arrays to the pool when the dictionary is no longer needed. -/// Change notifications are NOT emitted from this class - the parent QuaternaryBase handles all notifications +/// Change notifications are NOT emitted from this class - the parent QuaternaryDictionary handles all notifications /// through its Stream pipeline. /// [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] @@ -40,8 +40,10 @@ public sealed class QuadDictionary : IQuadMarks the end of a bucket chain. private const int EndOfChain = -1; - /// Comparer used to hash and compare keys. - private readonly IEqualityComparer _comparer; + /// Comparer used to hash and compare keys, or for the default comparer of a value-type key. + /// Calling directly lets the JIT inline the comparison for value-type keys, + /// which an interface call on a stored comparer prevents. + private readonly IEqualityComparer? _comparer; /// Pooled storage for dictionary entries. private Entry[] _entries; @@ -64,6 +66,9 @@ public sealed class QuadDictionary : IQuadThe number of reusable entries in the free list. private int _freeCount; + /// The pair count, published as one value for readers that hold no lock. + private int _publishedCount; + /// Initializes a new instance of the class with default settings. /// This constructor creates an empty QuadDictionary using default configuration values. Use this /// overload when no custom comparer or options are required. @@ -76,7 +81,7 @@ public QuadDictionary() /// The equality comparer for keys, or to use the default comparer. public QuadDictionary(IEqualityComparer? comparer) { - _comparer = comparer ?? EqualityComparer.Default; + _comparer = SelectComparer(comparer); _buckets = ArrayPool.Shared.Rent(MinimumSize); _entries = ArrayPool.Shared.Rent(MinimumSize); _bucketsLength = MinimumSize; @@ -99,6 +104,13 @@ public int Count /// Gets all values in the dictionary. public IEnumerable Values => ProjectEntries(static (_, value) => value); + /// Gets the number of key/value pairs for a reader that holds no lock. + internal int VolatileCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Volatile.Read(ref _publishedCount); + } + /// Gets or sets the value associated with the specified key. /// The key of the value to get or set. /// The value associated with the specified key. @@ -131,7 +143,7 @@ public TValue this[TKey key] while (index >= 0) { ref var entry = ref _entries[index]; - if (entry.GetHashCodeValue() == hashCode && _comparer.Equals(entry.GetKey(), key)) + if (entry.GetHashCodeValue() == hashCode && KeysEqual(entry.GetKey(), key)) { exists = true; return ref Entry.ValueRef(ref entry); @@ -160,7 +172,7 @@ public bool TryAdd(TKey key, TValue value) while (index >= 0) { ref var entry = ref _entries[index]; - if (entry.GetHashCodeValue() == hashCode && _comparer.Equals(entry.GetKey(), key)) + if (entry.GetHashCodeValue() == hashCode && KeysEqual(entry.GetKey(), key)) { return false; // Key already exists } @@ -202,7 +214,7 @@ public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) while (index >= 0) { ref var entry = ref _entries[index]; - if (entry.GetHashCodeValue() == hashCode && _comparer.Equals(entry.GetKey(), key)) + if (entry.GetHashCodeValue() == hashCode && KeysEqual(entry.GetKey(), key)) { value = entry.GetValue(); return true; @@ -242,7 +254,7 @@ public bool Remove(TKey key, [MaybeNullWhen(false)] out TValue value) while (index >= 0) { ref var entry = ref _entries[index]; - if (entry.GetHashCodeValue() == hashCode && _comparer.Equals(entry.GetKey(), key)) + if (entry.GetHashCodeValue() == hashCode && KeysEqual(entry.GetKey(), key)) { value = entry.GetValue(); @@ -270,6 +282,7 @@ public bool Remove(TKey key, [MaybeNullWhen(false)] out TValue value) entry.SetNext(FreeListSentinel - _freeList); _freeList = index; _freeCount++; + PublishCount(); return true; } @@ -296,9 +309,10 @@ public void Clear() _entries.AsSpan(0, _entryIndex).Clear(); } - _entryIndex = 0; _freeList = -1; _freeCount = 0; + _entryIndex = 0; + PublishCount(); } /// Ensures that the dictionary can hold up to the specified number of entries without resizing. @@ -336,7 +350,7 @@ IEnumerator> IQuad>.GetEnu /// The list to copy to. public void CopyKeysTo(List list) { - ThrowHelper.ThrowIfNull(list); + ArgumentExceptionHelper.ThrowIfNull(list); CopyEntriesTo(list, static (key, _) => key); } @@ -344,7 +358,7 @@ public void CopyKeysTo(List list) /// The list to copy to. public void CopyValuesTo(List list) { - ThrowHelper.ThrowIfNull(list); + ArgumentExceptionHelper.ThrowIfNull(list); CopyEntriesTo(list, static (_, value) => value); } @@ -352,7 +366,7 @@ public void CopyValuesTo(List list) /// The list to copy to. public void CopyTo(List> list) { - ThrowHelper.ThrowIfNull(list); + ArgumentExceptionHelper.ThrowIfNull(list); CopyEntriesTo(list, static (key, value) => new(key, value)); } @@ -374,22 +388,28 @@ public void Dispose() _entries = null!; } - /// Projects all active entries using the specified selector. - /// The projected element type. - /// Projects each active key/value pair. - /// An enumerable sequence of projected elements. - private IEnumerable ProjectEntries(Func selector) + /// Chooses the comparer to store. + /// The comparer given by the caller, or . + /// The comparer, or when the default comparer of a value-type key is used directly. + private static IEqualityComparer? SelectComparer(IEqualityComparer? comparer) { - for (var i = 0; i < _entryIndex; i++) + if (comparer is not null && !ReferenceEquals(comparer, EqualityComparer.Default)) { - ref var entry = ref _entries[i]; - if (entry.GetNext() < EndOfChain) - { - continue; - } - - yield return selector(entry.GetKey(), entry.GetValue()); + return comparer; } + + return typeof(TKey).IsValueType ? null : EqualityComparer.Default; + } + + /// Copies all active entries, projected by the selector, into a new list. + /// The projected element type. + /// Projects each active key/value pair. + /// A list holding the projected elements at the time of the call. + private List ProjectEntries(Func selector) + { + List result = [with(capacity: Count)]; + CopyEntriesTo(result, selector); + return result; } /// Copies projected values from all active entries into . @@ -398,7 +418,7 @@ private IEnumerable ProjectEntries(Func /// Projects each active key/value pair. private void CopyEntriesTo(List list, Func selector) { - ThrowHelper.ThrowIfNull(list); + ArgumentExceptionHelper.ThrowIfNull(list); for (var i = 0; i < _entryIndex; i++) { @@ -448,6 +468,8 @@ private void CopyEntriesTo(List list, Func(List list, FuncPublishes the pair count for readers that hold no lock. + /// + /// A lock-free reader cannot subtract the free count from the entry position itself: a writer can change + /// both between the two reads, which can give a negative count. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void PublishCount() => Volatile.Write(ref _publishedCount, _entryIndex - _freeCount); + /// Doubles the capacity of the internal entries array to accommodate additional elements. /// The new capacity is rounded up to the next power of two to optimize memory usage and /// performance. This method is intended for internal use and should not be called directly by consumers of the @@ -502,7 +532,16 @@ private void ResizeTo(int newSize) /// The key for which to compute the hash code. Can be null. /// A non-negative 32-bit unsigned integer representing the hash code of the key. Returns 0 if the key is null. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private uint InternalGetHashCode(TKey key) => (uint)(key is null ? 0 : _comparer.GetHashCode(key) & 0x7FFFFFFF); + private uint InternalGetHashCode(TKey key) => + (uint)(key is null ? 0 : (_comparer is null ? EqualityComparer.Default.GetHashCode(key) : _comparer.GetHashCode(key)) & 0x7FFFFFFF); + + /// Determines whether two keys are equal under the dictionary's comparer. + /// The first key. + /// The second key. + /// when the keys are equal. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool KeysEqual(TKey left, TKey right) => + _comparer is null ? EqualityComparer.Default.Equals(left, right) : _comparer.Equals(left, right); /// Calculates the index of the bucket corresponding to the specified hash code within the current bucket array. /// The hash code for which to determine the bucket index. Typically generated from a key to be stored or retrieved. diff --git a/src/ReactiveList/Collections/QuadList.cs b/src/ReactiveList/Collections/QuadList.cs index 091b9ab2..e4e4a0b2 100644 --- a/src/ReactiveList/Collections/QuadList.cs +++ b/src/ReactiveList/Collections/QuadList.cs @@ -13,7 +13,7 @@ namespace ReactiveList.Collections; /// QuadList is an internal shard optimized for scenarios where frequent additions and removals are required. /// It uses array pooling to minimize allocations. The list is not thread-safe and should not /// be accessed concurrently from multiple threads. Call Dispose to return internal arrays to the pool. -/// Change notifications are NOT emitted from this class - the parent QuaternaryBase handles all notifications +/// Change notifications are NOT emitted from this class - the parent QuaternaryList handles all notifications /// through its Stream pipeline. /// [System.Diagnostics.DebuggerDisplay("QuadList: {Count}")] @@ -47,6 +47,13 @@ public int Count get => _count; } + /// Gets the number of elements for a reader that holds no lock. + internal int VolatileCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Volatile.Read(ref _count); + } + /// Gets or sets the element at the specified index. /// The zero-based index of the element to get or set. /// The element at the specified index. @@ -227,8 +234,8 @@ public void Dispose() _items = null!; } - /// Adds data for the AddAssumeCapacity operation. - /// The item value. + /// Appends an item without checking capacity; the caller has already reserved room. + /// The item to append. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void AddAssumeCapacity(T item) { @@ -236,65 +243,90 @@ internal void AddAssumeCapacity(T item) _count++; } - /// Removes data for the RemoveMatching operation. - /// The removeCounts value. - /// The removedItems value. + /// Removes up to the requested number of copies of each item, keeping the order of the rest. + /// The copies still to remove per item; counts are consumed as items are removed. + /// Optional buffer receiving each removed item, empty to skip; it must hold every item that can be removed. /// The number of items removed from the list. - internal int RemoveMatching(Dictionary removeCounts, List? removedItems) + internal int RemoveMatching(ref PooledItemCounts removeCounts, Span removedItems) { var items = _items; var count = _count; var writeIndex = 0; var removed = 0; + var readIndex = 0; - for (var readIndex = 0; readIndex < count; readIndex++) + try { - var item = items[readIndex]; - if (removeCounts.TryGetValue(item, out var remaining)) + for (; readIndex < count; readIndex++) { - if (remaining == 1) + var item = items[readIndex]; + if (removeCounts.TryConsume(item)) { - _ = removeCounts.Remove(item); + if (!removedItems.IsEmpty) + { + removedItems[removed] = item; + } + + removed++; + continue; } - else + + if (writeIndex != readIndex) { - removeCounts[item] = remaining - 1; + items[writeIndex] = item; } - removedItems?.Add(item); - removed++; - continue; + writeIndex++; } - - if (writeIndex != readIndex) + } + finally + { + // Hashing a stored item runs user code. If it throws, the items already examined stay compacted and the rest are + // kept as they are, so the shard never holds a duplicated or lost item. + writeIndex = KeepUnexamined(items, readIndex, count, writeIndex); + if (removed != 0) { - items[writeIndex] = item; - } + if (ArrayPoolClearHelper.IsReferenceOrContainsReferences()) + { + Array.Clear(items, writeIndex, count - writeIndex); + } - writeIndex++; + _count = writeIndex; + } } - if (removed == 0) + return removed; + } + + /// Moves the items that a removal did not examine down to the write position. + /// The backing array. + /// The first item that was not examined; equal to when the pass finished. + /// The number of items before the removal. + /// The number of items kept so far. + /// The number of items that remain. + private static int KeepUnexamined(T[] items, int readIndex, int count, int writeIndex) + { + var tail = count - readIndex; + if (tail <= 0) { - return 0; + return writeIndex; } - if (ArrayPoolClearHelper.IsReferenceOrContainsReferences()) + if (writeIndex != readIndex) { - Array.Clear(items, writeIndex, removed); + Array.Copy(items, readIndex, items, writeIndex, tail); } - _count = writeIndex; - return removed; + return writeIndex + tail; } - /// Performs the ThrowIndexOutOfRange operation. + /// Throws the exception for an index outside the list. /// Always thrown for an invalid index. [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowIndexOutOfRange() => throw new ArgumentOutOfRangeException("index"); - /// Adds data for the AddWithResize operation. - /// The item value. + /// Grows the backing array, then appends an item. + /// The item to append. [MethodImpl(MethodImplOptions.NoInlining)] private void AddWithResize(T item) { @@ -304,8 +336,8 @@ private void AddWithResize(T item) _count = count + 1; } - /// Performs the Grow operation. - /// The minCapacity value. + /// Replaces the backing array with a larger pooled array. + /// The smallest capacity the new array must have. private void Grow(int minCapacity) { var newCapacity = _items.Length == 0 ? MinimumSize : _items.Length * CapacityGrowthFactor; diff --git a/src/ReactiveList/Collections/QuaternaryBase.cs b/src/ReactiveList/Collections/QuaternaryBase.cs deleted file mode 100644 index 6640d572..00000000 --- a/src/ReactiveList/Collections/QuaternaryBase.cs +++ /dev/null @@ -1,632 +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.Collections; -#else -namespace ReactiveList.Collections; -#endif -/// -/// Provides a base class for partitioned, observable collections that support quaternary (four-way) sharding and cache -/// change notifications. -/// -/// The type of items stored in the collection. Must be non-nullable. -/// The type used for secondary indexing within the collection. -/// This class implements partitioning logic using four shards to improve concurrency and scalability for -/// collections that require frequent updates and notifications. It provides observable change tracking via both -/// INotifyCollectionChanged and IObservable patterns, making it suitable for use in UI-bound or reactive scenarios. -/// Derived classes should implement enumeration and may extend synchronization or notification behavior as needed. -/// Thread safety is managed internally using per-shard locks and a background event processing pipeline. -[System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] -public abstract class QuaternaryBase : IReactiveSource, INotifyPropertyChanged - where TItem : notnull -{ - /// The number of shards used for partitioning. - protected static readonly int ShardCount = GetShardCount(); - - /// The fixed number of shards used by every closed collection type. - private const int FixedShardCount = 4; - - /// The property name used when the collection indexer changes. - private const string ItemArray = "Item[]"; - - /// Cached property-change arguments for . - private static readonly PropertyChangedEventArgs CountPropertyChangedEventArgs = new(nameof(Count)); - - /// Cached property-change arguments for the collection indexer. - private static readonly PropertyChangedEventArgs ItemArrayPropertyChangedEventArgs = new(ItemArray); - - /// The synchronization context captured when this collection was created. - private readonly SynchronizationContext? _syncContext; - - /// The channel used to queue collection notifications. - private Channel>? _eventChannel; - - /// The lazily initialized gate protecting event processor startup. - private Lock? _eventGate; - - /// The signal that publishes queued collection notifications. - private Signal>? _pipeline; - - /// Cancellation source for the event processor. - private CancellationTokenSource? _cts; - - /// The currently registered collection-change handlers. - private NotifyCollectionChangedEventHandler? _collectionChanged; - - /// The current item count. - private int _count; - - /// Indicates whether the event processor has started. - private int _eventProcessorStarted; - - /// The number of active stream subscribers. - private int _hasSubscribers; - - /// The collection version incremented by each emitted change. - private long _version; - - /// Initializes a new instance of the class. - /// This constructor captures the current synchronization context, which is typically associated - /// with the UI thread in WPF or Windows Forms applications. It also initiates a background task to process events - /// asynchronously. Derived classes can rely on the synchronization context being set for thread-safe operations - /// that require marshaling to the original context. - protected QuaternaryBase() - { - // Capture the current synchronization context (UI thread context in WPF/WinForms) - _syncContext = SynchronizationContext.Current; - } - - /// Occurs when the collection changes. - public event NotifyCollectionChangedEventHandler? CollectionChanged - { - add - { - if (value is null) - { - return; - } - - EnsureEventProcessorStarted(); - _collectionChanged += value; - } - - remove => _collectionChanged -= value; - } - - /// - public event PropertyChangedEventHandler? PropertyChanged; - - /// Gets the total number of items contained in all quads. - public int Count - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => Volatile.Read(ref _count); - } - - /// Gets a value indicating whether the collection is read-only. - public bool IsReadOnly => false; - - /// Gets an observable sequence that emits cache change notifications as they occur. - /// - /// This is the primary observable for change notifications. It provides all change information - /// including single item changes and batch operations. The Stream uses a channel-based pipeline - /// for efficient, low-allocation event delivery. - /// - public IObservable> Stream => Signal.Create>(observer => - { - EnsureEventProcessorStarted(); - _ = Interlocked.Increment(ref _hasSubscribers); - var subscription = _pipeline!.Subscribe(observer); - return Scope.Create( - (Subscription: subscription, Source: this), - static state => - { - state.Subscription.Dispose(); - _ = Interlocked.Decrement(ref state.Source._hasSubscribers); - }); - }); - - /// Gets a value indicating whether the object has been disposed. - public bool IsDisposed { get; private set; } - - /// Gets the current version number of the collection, which is incremented on each modification. - /// This property can be used for efficient change detection without acquiring locks. - /// The version is incremented atomically using . - public long Version => Interlocked.Read(ref _version); - - /// Gets thread-safe secondary indices associated with the current instance. - /// Each entry maps a unique index name to its corresponding secondary index. This dictionary - /// enables efficient retrieval and management of secondary indices in concurrent scenarios. - protected ConcurrentDictionary> Indices { get; } = new(); - - /// Gets the array of ReaderWriterLockSlim instances used to synchronize access to shared resources. - protected ReaderWriterLockSlim[] Locks { get; } = - [ - new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion), - new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion), - new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion), - new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion) - ]; - - /// Gets the shard containers used by the base class for generic lifecycle operations. - protected abstract IReadOnlyList> BaseQuads { get; } - - /// Removes all items from the cache. - public void Clear() - { - QuaternaryShardHelpers.EnterAllWriteLocks(Locks); - try - { - for (var i = 0; i < ShardCount; i++) - { - BaseQuads[i].Clear(); - } - - SetCount(0); - } - finally - { - QuaternaryShardHelpers.ExitAllWriteLocks(Locks); - } - - // Clear indices outside of locks - if (!Indices.IsEmpty) - { - foreach (var pair in Indices) - { - pair.Value.Clear(); - } - } - - Emit(CacheAction.Cleared, default); - } - - /// Releases all resources used by the current instance. - public void Dispose() - { - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - /// Returns an array containing all elements in the collection. - /// An array of type TItem that contains all elements of the collection. The array is empty if the collection - /// contains no elements. - public TItem[] ToArray() => - [.. this]; - - /// Returns an enumerator that iterates through the collection. - /// An enumerator that can be used to iterate through the collection. - public abstract IEnumerator GetEnumerator(); - - /// Returns an enumerator that iterates through a collection. - /// An object that can be used to iterate through the collection. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - - /// Gets or initializes the synchronization gate protecting event processor startup. - /// The event startup gate. - internal Lock GetOrCreateEventGate() - { - var gate = Volatile.Read(ref _eventGate); - if (gate is not null) - { - return gate; - } - - var newGate = new Lock(); - return Interlocked.CompareExchange(ref _eventGate, newGate, null) ?? newGate; - } - - /// Attempts to enqueue a cache event for processing and increments the version counter. - /// The cache action type. - /// The item associated with the action. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected void Emit(CacheAction action, TItem? item) => - Emit(action, item, null); - - /// Attempts to enqueue a cache event for processing and increments the version counter. - /// The cache action type. - /// The item associated with the action. - /// The batch of items, or for a single-item event. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected void Emit(CacheAction action, TItem? item, PooledBatch? batch) - { - // Increment version atomically for change tracking - _ = Interlocked.Increment(ref _version); - OnPropertyChanged(CountPropertyChangedEventArgs); - OnPropertyChanged(ItemArrayPropertyChangedEventArgs); - - // Fast path: skip channel write if no subscribers and no INCC - if (!HasChangeObservers()) - { - batch?.Dispose(); - return; - } - - EnsureEventProcessorStarted(); - if (_eventChannel!.Writer.TryWrite(new(action, item, batch))) - { - return; - } - - batch?.Dispose(); - } - - /// Emits a batch operation using the specified items and count without additional validation or copying. - /// The array of items to include in the batch operation. Must contain at least elements. - /// The number of items from to include in the batch operation. Must be greater than or - /// equal to zero and less than or equal to the length of . - /// This method is intended for scenarios where the caller can guarantee the validity of the - /// input parameters. No parameter validation is performed. The method may rent temporary arrays from the shared - /// pool for performance reasons. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) - { - if (!HasChangeObservers()) - { - Emit(CacheAction.BatchOperation, default); - return; - } - - EmitCopiedBatch(CacheAction.BatchOperation, items, count); - } - - /// Emits a batch added notification using the specified items and count without additional validation or copying. - /// The array of items to include in the batch operation. Must contain at least elements. - /// The number of items from to include in the batch operation. Must be greater than or - /// equal to zero and less than or equal to the length of . - /// This method is intended for scenarios where the caller can guarantee the validity of the - /// input parameters. No parameter validation is performed. The method may rent temporary arrays from the shared - /// pool for performance reasons. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) - { - if (!HasChangeObservers()) - { - Emit(CacheAction.BatchAdded, default); - return; - } - - EmitCopiedBatch(CacheAction.BatchAdded, items, count); - } - - /// Emits a batch added notification using the specified number of items from the provided list. - /// The list of items to include in the batch operation. Items are taken from the start of the list. - /// The number of items from the list to include in the batch. Must be less than or equal to the number of items in - /// the list and greater than or equal to zero. - /// The method copies the specified number of items from the list into a pooled array before - /// emitting the batch added notification. The caller is responsible for ensuring that the list contains at least the - /// specified number of items. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(IList items, int count) - { - ThrowHelper.ThrowIfNull(items); - - if (!HasChangeObservers()) - { - Emit(CacheAction.BatchAdded, default); - return; - } - - EmitListBatch(CacheAction.BatchAdded, items, count); - } - - /// Raises a batch removed event for the specified items. - /// The array of items that have been removed. Only the first elements are considered. - /// The number of items to include from the array. Must be less than or equal to the length - /// of . - /// This method uses a pooled array to optimize memory usage when emitting the batch removed - /// event. The caller should ensure that the array contains at least elements. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) - { - if (!HasChangeObservers()) - { - Emit(CacheAction.BatchRemoved, default); - return; - } - - EmitCopiedBatch(CacheAction.BatchRemoved, items, count); - } - - /// Emits a batch removed notification using an already-owned array. - /// The owned array containing removed items. - /// The number of valid items in . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) - { - if (!HasChangeObservers()) - { - Emit(CacheAction.BatchRemoved, default); - return; - } - - EmitOwnedBatch(CacheAction.BatchRemoved, items, count); - } - - /// Emits a notification that a batch of items has been removed from the list. - /// The list containing the items that were removed. The first elements are considered - /// removed. - /// The number of items removed from the list. Must be greater than or equal to 0 and less than or equal to the - /// number of items in . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(IList items, int count) - { - ThrowHelper.ThrowIfNull(items); - - if (!HasChangeObservers()) - { - Emit(CacheAction.BatchRemoved, default); - return; - } - - EmitListBatch(CacheAction.BatchRemoved, items, count); - } - - /// Notifies all registered indices that a new item has been added. - /// The item that was added and should be communicated to all indices. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) - { - if (Indices.IsEmpty) - { - return; - } - - foreach (var kvp in Indices) - { - kvp.Value.OnAdded(item); - } - } - - /// Notifies all registered index listeners that the specified item has been removed. - /// The item that was removed and for which index listeners should be notified. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) - { - if (Indices.IsEmpty) - { - return; - } - - foreach (var kvp in Indices) - { - kvp.Value.OnRemoved(item); - } - } - - /// Releases the unmanaged resources and optionally releases the managed resources. - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool disposing) - { - if (IsDisposed) - { - return; - } - - if (disposing) - { - _cts?.Cancel(); - _cts?.Dispose(); - foreach (var l in Locks) - { - l.Dispose(); - } - - _pipeline?.OnCompleted(); - _pipeline?.Dispose(); - } - - IsDisposed = true; - } - - /// Atomically adds the specified delta to the cached item count. - /// The count delta to apply. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) => Interlocked.Add(ref _count, value); - - /// Sets the cached item count to the specified value. - /// The new count value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) => Volatile.Write(ref _count, value); - - /// Gets a value indicating whether the collection has observable or INCC subscribers. - /// when change notifications need to be materialized; otherwise, . - [MethodImpl(MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() => - Interlocked.CompareExchange(ref _hasSubscribers, 0, 0) != 0 || _collectionChanged is not null; - - /// Gets the fixed shard count while associating the cached field with the closed item type. - /// The item type associated with the closed generic collection. - /// The number of collection shards. - private static int GetShardCount() - { - _ = typeof(T); - return FixedShardCount; - } - - /// Creates data for the CreateBatch operation. - /// The items value. - /// The count value. - /// A pooled batch wrapping a copy of the specified items. - private static PooledBatch CreateBatch(TItem[] items, int count) - { - var batchItems = new TItem[count]; - Array.Copy(items, batchItems, count); - return new(batchItems, count, ReturnToPool: false); - } - - /// Asynchronously processes events from the event channel until cancellation is requested. - /// A task that represents the asynchronous operation. - /// This method reads events from the internal event channel and processes them through the - /// pipeline. The operation continues until the associated cancellation token is triggered. If a legacy collection - /// changed handler is registered, it is invoked for each event. - private async Task ProcessEventsAsync() - { - var channel = _eventChannel; - var pipeline = _pipeline; - var cts = _cts; - if (channel is null || pipeline is null || cts is null) - { - return; - } - - var reader = channel.Reader; - try - { - while (await reader.WaitToReadAsync(cts.Token).ConfigureAwait(false)) - { - while (reader.TryRead(out var evt)) - { - pipeline.OnNext(evt); - - if (_collectionChanged is not null) - { - InvokeLegacyINCC(evt); - } - } - } - } - catch (OperationCanceledException) - { - } - } - - /// - /// Raises the CollectionChanged event to notify subscribers of changes to the collection, using legacy - /// INotifyCollectionChanged semantics. - /// - /// The cache notification event containing information about the collection change to be propagated. - /// This method adapts cache change events to the INotifyCollectionChanged pattern, using the - /// Reset action for batch or ambiguous operations to ensure correct UI updates, especially in sharded or - /// partitioned collections. The event is dispatched on the captured synchronization context if available, which is - /// typically required for UI thread updates. - private void InvokeLegacyINCC(CacheNotify evt) - { - var handler = _collectionChanged; - if (handler is null) - { - evt.Batch?.Dispose(); - return; - } - - NotifyCollectionChangedEventArgs args; - - if (evt.Batch is not null) - { - // Batch operations use Reset to avoid index issues with sharded collections - args = new(NotifyCollectionChangedAction.Reset); - evt.Batch.Dispose(); - } - else - { - var action = evt.Action switch - { - CacheAction.Added => NotifyCollectionChangedAction.Add, - CacheAction.Removed => NotifyCollectionChangedAction.Remove, - CacheAction.Cleared => NotifyCollectionChangedAction.Reset, - _ => NotifyCollectionChangedAction.Reset - }; - - // For Add/Remove with single items, we can't provide index in sharded collection - // Use Reset for safety to ensure UI updates correctly - args = action is NotifyCollectionChangedAction.Add or NotifyCollectionChangedAction.Remove ? new(NotifyCollectionChangedAction.Reset) : new(action); - } - - // Dispatch to the captured synchronization context (UI thread) - if (_syncContext is not null) - { - _syncContext.Post(_ => handler.Invoke(this, args), null); - } - else - { - // Fallback: invoke directly if no sync context was captured - handler.Invoke(this, args); - } - } - - /// Handles property change notifications. - /// The args value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void OnPropertyChanged(PropertyChangedEventArgs args) => - PropertyChanged?.Invoke(this, args); - - /// Ensures state for the EnsureEventProcessorStarted operation. - private void EnsureEventProcessorStarted() - { - if (Volatile.Read(ref _eventProcessorStarted) != 0) - { - return; - } - - var gate = GetOrCreateEventGate(); - lock (gate) - { - if (_eventProcessorStarted != 0) - { - return; - } - - _eventChannel = Channel.CreateUnbounded>( - new UnboundedChannelOptions { SingleReader = true, SingleWriter = false, AllowSynchronousContinuations = false }); - _pipeline = new(); - _cts = new(); - Volatile.Write(ref _eventProcessorStarted, 1); - _ = Task.Factory.StartNew(ProcessEventsAsync, _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); - } - } - - /// Creates a pooled batch copy and transfers ownership to . - /// The cache action to emit. - /// The source items to copy into a pooled batch. - /// The number of elements to copy. - private void EmitCopiedBatch(CacheAction action, TItem[] items, int count) - { - var batch = (PooledBatch?)CreateBatch(items, count); - try - { - Emit(action, default, batch); - batch = null; - } - finally - { - batch?.Dispose(); - } - } - - /// Wraps an already-owned array in a batch and transfers ownership to . - /// The cache action to emit. - /// The owned items array. - /// The number of valid elements in . - private void EmitOwnedBatch(CacheAction action, TItem[] items, int count) - { - PooledBatch? batch = new(items, count, ReturnToPool: false); - try - { - Emit(action, default, batch); - batch = null; - } - finally - { - batch?.Dispose(); - } - } - - /// Copies items from a list into a batch and emits the specified batch notification. - /// The cache action to emit. - /// The source list containing items to emit. - /// The number of elements from the start of to emit. - private void EmitListBatch(CacheAction action, IList items, int count) - { - var copy = new TItem[count]; - for (var i = 0; i < count; i++) - { - copy[i] = items[i]; - } - - EmitOwnedBatch(action, copy, count); - } -} diff --git a/src/ReactiveList/Collections/QuaternaryDictionary.cs b/src/ReactiveList/Collections/QuaternaryDictionary.cs index 8e8ad521..2a15e73f 100644 --- a/src/ReactiveList/Collections/QuaternaryDictionary.cs +++ b/src/ReactiveList/Collections/QuaternaryDictionary.cs @@ -13,16 +13,23 @@ namespace ReactiveList.Collections; /// /// The type of keys in the dictionary. Must be non-nullable. /// The type of values stored in the dictionary. -[System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] +/// Items are partitioned across four shards, each guarded by its own reader-writer lock. Operations that touch several +/// shards take the locks in ascending shard order. Change notifications are queued while the shard lock is still held, so +/// observers see changes in the order they happened, and are delivered by a single background reader. After +/// every operation that reads or writes items throws . Enumeration, , +/// and work on a point-in-time copy, so a consumer can call back into the dictionary +/// while enumerating. The callbacks given to run while every shard is locked and must not call back into +/// the dictionary. +[System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] [SkipLocalsInit] -public class QuaternaryDictionary : QuaternaryBase, TValue>, IQuaternaryDictionary +public sealed class QuaternaryDictionary : IQuaternaryDictionary, IVersionedSnapshotSource>, INotifyPropertyChanged, IReactiveSourceWithOptions where TKey : notnull { /// The default view throttle interval in milliseconds. private const int DefaultThrottleMs = 50; - /// Initial capacity used for buffers that collect removed keys. - private const int InitialRemovalBufferSize = 64; + /// Initial capacity used for buffers that collect removed entries. + private const int InitialRemovalBufferSize = 16; /// Multiplier applied when a removal buffer grows. private const int CapacityGrowthFactor = 2; @@ -30,33 +37,98 @@ public class QuaternaryDictionary : QuaternaryBaseLargest buffer allocated on the stack. private const int StackAllocationThreshold = 1024; + /// The first shard, held in its own field so needs no array access. + private readonly QuadDictionary _first; + + /// The second shard. + private readonly QuadDictionary _second; + + /// The third shard. + private readonly QuadDictionary _third; + + /// The fourth shard. + private readonly QuadDictionary _fourth; + + /// The typed shard containers. + private readonly QuadDictionary[] _quads; + + /// The shared collection state. + private readonly QuaternaryState, TValue> _state; + + /// The shard locks, cached from the state to save an indirection on hot paths. + private readonly ReaderWriterLockSlim[] _locks; + + /// Initializes a new instance of the class. + /// This constructor captures the current synchronization context, which is typically associated + /// with the UI thread in WPF or Windows Forms applications. Legacy collection-changed handlers are raised on it. + public QuaternaryDictionary() + { + _first = []; + _second = []; + _third = []; + _fourth = []; + _quads = [_first, _second, _third, _fourth]; + _state = QuaternaryCore.CreateState, TValue>([_first, _second, _third, _fourth], nameof(QuaternaryDictionary<,>)); + _locks = _state.Locks; + } + + /// Occurs when the collection changes. + /// An exception thrown by a handler is isolated: later notifications are still delivered. + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add => QuaternaryEvents.AddCollectionChangedHandler(_state, this, value); + + remove => QuaternaryEvents.RemoveCollectionChangedHandler(_state, value); + } + + /// + public event PropertyChangedEventHandler? PropertyChanged; + + /// Gets the total number of entries contained in all shards. + /// Each shard keeps its own count, so the value is exact only while no writer is running. + public int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _first.VolatileCount + _second.VolatileCount + _third.VolatileCount + _fourth.VolatileCount; + } + + /// Gets a value indicating whether the collection is read-only. + public bool IsReadOnly => false; + + /// Gets an observable sequence that emits cache change notifications as they occur. + /// + /// This is the primary observable for change notifications. It provides all change information + /// including single entry changes and batch operations. An observer that throws from OnNext is unsubscribed and + /// receives the exception through its own OnError; other observers are unaffected. Subscribing to a disposed + /// collection completes immediately, and disposing the collection completes the stream after queued notifications are delivered. + /// + public IObservable>> Stream => QuaternaryEvents.GetStream(_state); + + /// + public IObservable>> VersionedStream => QuaternaryEvents.GetVersionedStream(_state); + + /// + public ReactiveSourceOptions Options { get; init; } = ReactiveSourceOptions.Default; + + /// Gets a value indicating whether the object has been disposed. + public bool IsDisposed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Volatile.Read(ref _state.Disposed) != 0; + } + + /// Gets the current version number of the collection, which is incremented on each modification. + /// This property can be used for efficient change detection without acquiring locks. Changes made while + /// nobody observes the collection are counted per shard, so the value only ever grows and changes with every modification. + public long Version => QuaternaryCore.Version(_state); + /// Gets a collection containing all keys from the underlying quads. public ICollection Keys => - QuaternaryShardHelpers.CollectFromShardsReadLocked, TKey>( - Locks, - Quads, - Count, - static (shard, list) => shard.CopyKeysTo(list)); + CollectLocked(static (shard, list) => shard.CopyKeysTo(list)); /// Gets a collection containing all values from the underlying quads. public ICollection Values => - QuaternaryShardHelpers.CollectFromShardsReadLocked, TValue>( - Locks, - Quads, - Count, - static (shard, list) => shard.CopyValuesTo(list)); - - /// - protected override IReadOnlyList>> BaseQuads => Quads; - - /// Gets the typed shard containers used by the dictionary implementation. - private QuadDictionary[] Quads { get; } = - [ - [], - [], - [], - [] - ]; + CollectLocked(static (shard, list) => shard.CopyValuesTo(list)); /// Gets or sets the value associated with the specified key. /// The key whose value to get or set. @@ -99,29 +171,28 @@ public bool TryAdd(TKey key, TValue value) { var idx = GetShard(key); var added = false; - Locks[idx].EnterWriteLock(); + var notify = false; + Exception? failure = null; + _locks[idx].EnterWriteLock(); try { - if (Quads[idx].TryAdd(key, value)) + QuaternaryCore.ThrowIfDisposed(_state); + if (_quads[idx].TryAdd(key, value)) { - if (!Indices.IsEmpty) - { - NotifyIndicesAdded(value); - } - - AddToCount(1); + // A throwing key selector must not stop the change from being committed and announced. + failure = QuaternaryCore.IndexAdded(_state, value); + QuaternaryCore.PublishLocked(_state, idx, CacheAction.Added, new(key, value)); added = true; + notify = _state.DeferralDepth == 0; } } finally { - Locks[idx].ExitWriteLock(); + _locks[idx].ExitWriteLock(); } - if (added) - { - Emit(CacheAction.Added, new(key, value)); - } + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); + QuaternaryCore.RethrowIfFailed(failure); return added; } @@ -133,47 +204,39 @@ public bool TryAdd(TKey key, TValue value) public void AddOrUpdate(TKey key, TValue value) { var idx = GetShard(key); - var action = CacheAction.Updated; - Locks[idx].EnterWriteLock(); + bool notify; + Exception? failure; + _locks[idx].EnterWriteLock(); try { - var dict = Quads[idx]; - - // Use direct ref access - avoids double lookup - ref var valueRef = ref dict.GetValueRefOrAddDefault(key, out var exists); - var hasIndices = !Indices.IsEmpty; + QuaternaryCore.ThrowIfDisposed(_state); + // Direct ref access avoids a second lookup. The value is stored before the indexes run, so a throwing key + // selector cannot leave the entry, the count or the notification behind. + ref var valueRef = ref _quads[idx].GetValueRefOrAddDefault(key, out var exists); if (exists) { - if (hasIndices) - { - NotifyIndicesRemoved(valueRef!); - } - + var previous = valueRef!; valueRef = value; - if (hasIndices) - { - NotifyIndicesAdded(value); - } + failure = QuaternaryCore.IndexReplaced(_state, previous, value); + QuaternaryCore.PublishLocked(_state, idx, CacheAction.Updated, new(key, value), new(key, previous)); } else { valueRef = value; - if (hasIndices) - { - NotifyIndicesAdded(value); - } - - AddToCount(1); - action = CacheAction.Added; + failure = QuaternaryCore.IndexAdded(_state, value); + QuaternaryCore.PublishLocked(_state, idx, CacheAction.Added, new(key, value)); } + + notify = _state.DeferralDepth == 0; } finally { - Locks[idx].ExitWriteLock(); + _locks[idx].ExitWriteLock(); } - Emit(action, new(key, value)); + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); + QuaternaryCore.RethrowIfFailed(failure); } /// Removes the value with the specified key from the collection. @@ -183,32 +246,28 @@ public void AddOrUpdate(TKey key, TValue value) public bool Remove(TKey key) { var idx = GetShard(key); - TValue? removedValue = default; var removed = false; - Locks[idx].EnterWriteLock(); + var notify = false; + Exception? failure = null; + _locks[idx].EnterWriteLock(); try { - if (Quads[idx].Remove(key, out var val)) + QuaternaryCore.ThrowIfDisposed(_state); + if (_quads[idx].Remove(key, out var val)) { - if (!Indices.IsEmpty) - { - NotifyIndicesRemoved(val); - } - - AddToCount(-1); - removedValue = val; + failure = QuaternaryCore.IndexRemoved(_state, val); + QuaternaryCore.PublishLocked(_state, idx, CacheAction.Removed, new(key, val)); removed = true; + notify = _state.DeferralDepth == 0; } } finally { - Locks[idx].ExitWriteLock(); + _locks[idx].ExitWriteLock(); } - if (removed) - { - Emit(CacheAction.Removed, new(key, removedValue!)); - } + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); + QuaternaryCore.RethrowIfFailed(failure); return removed; } @@ -216,7 +275,59 @@ public bool Remove(TKey key) /// Removes the specified key/value pair from the collection. /// The key/value pair to remove. /// true if removed; otherwise, false. - public bool Remove(KeyValuePair item) => Contains(item) && Remove(item.Key); + /// The pair is removed only when the stored value equals 's value; the check and removal are atomic. + public bool Remove(KeyValuePair item) + { + var idx = GetShard(item.Key); + var removed = false; + var notify = false; + Exception? failure = null; + _locks[idx].EnterWriteLock(); + try + { + QuaternaryCore.ThrowIfDisposed(_state); + if (_quads[idx].TryGetValue(item.Key, out var current) + && EqualityComparer.Default.Equals(current, item.Value) + && _quads[idx].Remove(item.Key, out var val)) + { + failure = QuaternaryCore.IndexRemoved(_state, val); + QuaternaryCore.PublishLocked(_state, idx, CacheAction.Removed, new(item.Key, val)); + removed = true; + notify = _state.DeferralDepth == 0; + } + } + finally + { + _locks[idx].ExitWriteLock(); + } + + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); + QuaternaryCore.RethrowIfFailed(failure); + + return removed; + } + + /// Removes all items from the cache. + /// The collection is disposed. + public void Clear() + { + var notify = QuaternaryCore.Clear(_state); + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); + } + + /// Defers change notifications until the last active deferral is disposed. + /// The token that releases this deferral. + /// The dictionary is disposed. + /// Writes are immediately visible to readers. If the dictionary changed, it publishes one reset when notifications resume. + /// Open and release deferrals outside callbacks that run under a shard lock. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NotificationDeferral DeferNotifications() => QuaternaryDeferrals.Begin(_state, ResumeNotifications); + + /// Releases all resources used by the current instance. + /// Disposal is idempotent and safe to call from several threads. The shards are released under their write locks, + /// so an operation already running finishes first and later operations throw . + /// The notification stream completes after the notifications already queued are delivered. + public void Dispose() => _ = QuaternaryCore.Dispose(_state); /// Attempts to retrieve the value associated with the specified key. /// The key whose value to retrieve. @@ -230,32 +341,39 @@ public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) #endif { var idx = GetShard(key); - Locks[idx].EnterReadLock(); + _locks[idx].EnterReadLock(); try { - var found = Quads[idx].TryGetValue(key, out var result); + QuaternaryCore.ThrowIfDisposed(_state); + var found = _quads[idx].TryGetValue(key, out var result); value = result!; return found; } finally { - Locks[idx].ExitReadLock(); + _locks[idx].ExitReadLock(); } } /// Adds a collection of key/value pairs to the cache in a single batch operation. /// The collection of key/value pairs to add. + /// is . + /// An existing key has its value replaced. When a key repeats, the last occurrence wins. public void AddRange(IEnumerable> pairs) { + ArgumentExceptionHelper.ThrowIfNull(pairs); + if (pairs is KeyValuePair[] array) { AddRangeCore(array); return; } - if (pairs is IList> list) + if (pairs is ICollection> sized) { - AddRangeCore(list); + var copy = new KeyValuePair[sized.Count]; + sized.CopyTo(copy, 0); + AddRangeCore(copy); return; } @@ -264,30 +382,38 @@ public void AddRange(IEnumerable> pairs) /// Adds a secondary index for values using the specified key selector function. /// The type of the index key. - /// The unique name of the index to add. + /// The unique name of the index to add. /// A function that extracts the index key from a value. - public void AddValueIndex(string name, Func keySelector) + /// or is . + /// The index is built and registered while every shard is write-locked, so no entry is missed. An existing + /// index with the same name is replaced. If throws while the index is built, the index is not registered. + /// If it throws later, during a mutation, the mutation is still committed and announced, the index does not hold that value, + /// and the exception propagates to the caller after the change is complete. + public void AddValueIndex(string indexName, Func keySelector) where TIndexKey : notnull { - var index = new SecondaryIndex(keySelector); + ArgumentExceptionHelper.ThrowIfNull(indexName); + ArgumentExceptionHelper.ThrowIfNull(keySelector); - for (var i = 0; i < ShardCount; i++) + var index = new SecondaryIndex(keySelector); + QuaternaryShardHelpers.EnterAllWriteLocks(_locks); + try { - Locks[i].EnterReadLock(); - try + QuaternaryCore.ThrowIfDisposed(_state); + for (var i = 0; i < QuaternaryCore.FixedShardCount; i++) { - foreach (var val in Quads[i].Values) + foreach (var entry in _quads[i]) { - index.OnAdded(val); + index.OnAdded(entry.Value); } } - finally - { - Locks[i].ExitReadLock(); - } - } - Indices[name] = index; + QuaternaryCore.RegisterIndex(_state, indexName, index); + } + finally + { + QuaternaryShardHelpers.ExitAllWriteLocks(_locks); + } } /// Retrieves all values that match the specified key in the given secondary value index. @@ -295,9 +421,15 @@ public void AddValueIndex(string name, Func keySel /// The name of the secondary index to query. /// The key value to search for within the specified index. /// An enumerable collection of values that match the specified key. + /// is . public IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) - where TIndexKey : notnull => - Indices.TryGetValue(indexName, out var idx) && idx is SecondaryIndex typedIdx ? typedIdx.Lookup(key) : []; + where TIndexKey : notnull + { + ArgumentExceptionHelper.ThrowIfNull(indexName); + QuaternaryCore.ThrowIfDisposed(_state); + + return QuaternaryCore.TryGetIndex(_state, indexName, out var idx) && idx is SecondaryIndex typedIdx ? typedIdx.Lookup(key) : []; + } /// Creates a reactive view filtered by a secondary index key. /// The type of the key used in the secondary index. @@ -327,7 +459,7 @@ public SecondaryIndexReactiveView CreateViewBySecondaryIndex - !Indices.TryGetValue(indexName, out var idx) || idx is not SecondaryIndex + !QuaternaryCore.TryGetIndex(_state, indexName, out var idx) || idx is not SecondaryIndex ? throw new InvalidOperationException($"Secondary index '{indexName}' does not exist or has incompatible type.") : SecondaryIndexReactiveView.Create( this, @@ -344,7 +476,8 @@ public SecondaryIndexReactiveView CreateViewBySecondaryIndex if the value's indexed property matches the specified key; otherwise, . public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull => - Indices.TryGetValue(indexName, out var idx) && idx.MatchesKey(value, key); + QuaternaryCore.TryGetIndex(_state, indexName, out var idx) + && (idx is SecondaryIndex typedIdx ? typedIdx.MatchesTypedKey(value, key) : idx.MatchesKey(value, key)); /// Determines whether the dictionary contains the specified key and value pair. /// The key/value pair to locate. @@ -360,104 +493,145 @@ public bool ValueMatchesSecondaryIndex(string indexName, TValue value /// Removes all entries with keys in the specified collection from the dictionary. /// The collection of keys to remove. + /// is . public void RemoveKeys(IEnumerable keys) { - ThrowHelper.ThrowIfNull(keys); + ArgumentExceptionHelper.ThrowIfNull(keys); - // Fast path for arrays if (keys is TKey[] array) { RemoveKeysCore(array); return; } - // Fast path for IList - if (keys is IList list) + if (keys is ICollection sized) { - RemoveKeysCore(list); + var copy = new TKey[sized.Count]; + sized.CopyTo(copy, 0); + RemoveKeysCore(copy); return; } - // Slow path: materialize RemoveKeysCore([.. keys]); } /// Removes all entries that match the specified predicate from the dictionary. /// A function that returns true for entries that should be removed. /// The number of entries removed from the dictionary. + /// is . + /// The predicate runs on a point-in-time copy of each shard outside the locks, so it may read the dictionary. + /// An entry whose value changed after the copy was taken is kept. public int RemoveMany(Func, bool> predicate) { - ThrowHelper.ThrowIfNull(predicate); - - var totalRemoved = 0; - var keysBuffer = ArrayPool.Shared.Rent(InitialRemovalBufferSize); + ArgumentExceptionHelper.ThrowIfNull(predicate); + KeyValuePair[]? matches = null; + var matchCount = 0; try { - for (var i = 0; i < ShardCount; i++) + for (var shard = 0; shard < QuaternaryCore.FixedShardCount; shard++) { - totalRemoved += RemoveManyFromShard(i, predicate, ref keysBuffer); + CollectMatches(shard, predicate, ref matches, ref matchCount); } - if (totalRemoved > 0) - { - AddToCount(-totalRemoved); - Emit(CacheAction.BatchOperation, default); - } + return matchCount == 0 ? 0 : RemoveMatchedEntries(matches!, matchCount); } finally { - ArrayPool.Shared.Return(keysBuffer, clearArray: ArrayPoolClearHelper.IsReferenceOrContainsReferences()); + if (matches is not null) + { + ArrayPool>.Shared.Return(matches, clearArray: ArrayPoolClearHelper.IsReferenceOrContainsReferences>()); + } } - - return totalRemoved; } /// Performs a batch edit operation on the dictionary, ensuring only a single change notification is emitted. /// An action that receives the dictionary interface to perform modifications. + /// is . + /// The action runs while every shard is write-locked, so it must not call back into the dictionary. If it throws, + /// the edits made so far stay applied, the count and indexes are updated, and the notification is still emitted. public void Edit(Action> editAction) { - ThrowHelper.ThrowIfNull(editAction); + ArgumentExceptionHelper.ThrowIfNull(editAction); - QuaternaryShardHelpers.EnterAllWriteLocks(Locks); + var notify = false; try { - var wrapper = new QuaternaryDictEditWrapper(this); - editAction(wrapper); - SetCount(GetCountUnsafe()); + QuaternaryShardHelpers.EnterAllWriteLocks(_locks); + try + { + QuaternaryCore.ThrowIfDisposed(_state); + notify = _state.DeferralDepth == 0; + try + { + editAction(new QuaternaryDictEditWrapper(this)); + } + finally + { + QuaternaryCore.PublishMarkerLocked(_state, CacheAction.BatchOperation); + } + } + finally + { + QuaternaryShardHelpers.ExitAllWriteLocks(_locks); + } } finally { - QuaternaryShardHelpers.ExitAllWriteLocks(Locks); + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); } - - // Emit single batch notification after all changes - Emit(CacheAction.BatchOperation, default); } /// Copies the elements of the collection to an array. /// The destination array. /// The starting index in the array. /// Thrown when array is null. + /// is negative. + /// The destination does not have room for every element. public void CopyTo(KeyValuePair[] array, int arrayIndex) { - ThrowHelper.ThrowIfNull(array); + ArgumentExceptionHelper.ThrowIfNull(array); + ArgumentOutOfRangeExceptionHelper.ThrowIfNegative(arrayIndex); - for (var i = 0; i < ShardCount; i++) + QuaternaryShardHelpers.EnterAllReadLocks(_locks); + try { - Locks[i].EnterReadLock(); - try + QuaternaryCore.ThrowIfDisposed(_state); + if (array.Length - arrayIndex < QuaternaryCore.SumShardCounts(_state)) { - foreach (var kvp in Quads[i]) - { - array[arrayIndex] = kvp; - arrayIndex++; - } - } - finally - { - Locks[i].ExitReadLock(); + throw new ArgumentException("The destination array is too small.", nameof(array)); } + + FillLocked(array, arrayIndex); + } + finally + { + QuaternaryShardHelpers.ExitAllReadLocks(_locks); + } + } + + /// Returns an array containing all entries in the dictionary. + /// An array that contains all entries. The array is empty if the dictionary contains no entries. + /// The collection is disposed. + public KeyValuePair[] ToArray() + { + QuaternaryCore.ThrowIfDisposed(_state); + return Count == 0 ? [] : CopyVersioned(out _); + } + + /// + public KeyValuePair[] CopyVersioned(out long version) + { + QuaternaryShardHelpers.EnterAllReadLocks(_locks); + try + { + QuaternaryCore.ThrowIfDisposed(_state); + version = Interlocked.Read(ref _state.Version); + return CopyLocked(); + } + finally + { + QuaternaryShardHelpers.ExitAllReadLocks(_locks); } } @@ -467,27 +641,31 @@ public void CopyTo(KeyValuePair[] array, int arrayIndex) [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) => TryGetValue(key, out _); - /// Returns an enumerator that iterates through the collection. + /// Returns an enumerator over a point-in-time copy of the dictionary. /// An enumerator for the collection. - public override IEnumerator> GetEnumerator() + /// No lock is held while the enumerator is in use. Dispose the enumerator to return its buffer to the pool. + public IEnumerator> GetEnumerator() { - for (var i = 0; i < ShardCount; i++) + QuaternaryShardHelpers.EnterAllReadLocks(_locks); + try { - Locks[i].EnterReadLock(); - try - { - foreach (var kvp in Quads[i]) - { - yield return kvp; - } - } - finally - { - Locks[i].ExitReadLock(); - } + QuaternaryCore.ThrowIfDisposed(_state); + var count = QuaternaryCore.SumShardCounts(_state); + var buffer = ArrayPool>.Shared.Rent(count); + FillLocked(buffer, 0); + return new PooledSnapshotEnumerator>(buffer, count); + } + finally + { + QuaternaryShardHelpers.ExitAllReadLocks(_locks); } } + /// Returns an enumerator that iterates through the collection. + /// An object that can be used to iterate through the collection. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + /// Calculates the shard index for the specified key. /// The key for which to determine the shard index. Must not be null. /// The zero-based index of the shard to which the key is assigned. @@ -500,146 +678,203 @@ public override IEnumerator> GetEnumerator() [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int GetEntryShard(KeyValuePair entry) => ShardHash.GetShardIndex4(entry.Key); - /// Collects keys selected by a predicate into a reusable pooled buffer. - /// The dictionary to scan. - /// The predicate selecting entries to remove. - /// The reusable pooled key buffer. - /// The number of collected keys. - private static int CollectMatchingKeys( - QuadDictionary dictionary, - Func, bool> predicate, - ref TKey[] keysBuffer) + /// Copies the dictionary while all shard locks are held. + /// The entries in shard order. + private KeyValuePair[] CopyLocked() { - var keysCount = 0; - foreach (var item in dictionary) + var total = QuaternaryCore.SumShardCounts(_state); + if (total == 0) { - if (!predicate(item)) - { - continue; - } + return []; + } - if (keysCount >= keysBuffer.Length) - { - QuaternaryShardHelpers.GrowPooledBuffer(ref keysBuffer, keysCount, CapacityGrowthFactor); - } + var result = new KeyValuePair[total]; + FillLocked(result, 0); + return result; + } + + /// Releases the token and reports any deferred property changes outside the shard locks. + /// The shared token state. + private void ResumeNotifications(NotificationDeferralState release) + { + var notify = QuaternaryDeferrals.End(_state, release, CopyLocked); + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); + } - keysBuffer[keysCount] = item.Key; - keysCount++; + /// Collects a projection of every shard while holding all read locks. + /// The projected element type. + /// Copies projected items from one shard into the destination list. + /// A list holding the projection of every entry. + private List CollectLocked(Action, List> copyShard) + { + QuaternaryShardHelpers.EnterAllReadLocks(_locks); + try + { + QuaternaryCore.ThrowIfDisposed(_state); + return QuaternaryShardHelpers.CollectFromShardsUnsafe(_quads, QuaternaryCore.SumShardCounts(_state), copyShard); + } + finally + { + QuaternaryShardHelpers.ExitAllReadLocks(_locks); } + } - return keysCount; + /// Copies every entry into ; the caller holds all read locks. + /// The array to fill. + /// The index of the first slot to write. + private void FillLocked(KeyValuePair[] destination, int offset) + { + for (var i = 0; i < QuaternaryCore.FixedShardCount; i++) + { + foreach (var entry in _quads[i]) + { + destination[offset] = entry; + offset++; + } + } } - /// Removes matching entries from one shard while its write lock is held. + /// Adds the entries of one shard that match a predicate, evaluated outside the lock, to the pooled match buffer. /// The shard to process. /// The predicate selecting entries to remove. - /// The reusable pooled key buffer. - /// The number of removed entries. - private int RemoveManyFromShard( + /// The pooled buffer of matches, rented when the first entry matches. + /// The number of valid entries in . + private void CollectMatches( int shardIndex, Func, bool> predicate, - ref TKey[] keysBuffer) + ref KeyValuePair[]? matches, + ref int matchCount) { - Locks[shardIndex].EnterWriteLock(); + var copy = RentShardCopy(shardIndex, out var copied); try { - var dictionary = Quads[shardIndex]; - var keysCount = CollectMatchingKeys(dictionary, predicate, ref keysBuffer); - return RemoveCollectedKeys(dictionary, keysBuffer, keysCount); + for (var i = 0; i < copied; i++) + { + if (predicate(copy[i])) + { + QuaternaryShardHelpers.AppendPooled(ref matches, ref matchCount, copy[i], InitialRemovalBufferSize, CapacityGrowthFactor); + } + } } finally { - Locks[shardIndex].ExitWriteLock(); + ArrayPool>.Shared.Return(copy, clearArray: ArrayPoolClearHelper.IsReferenceOrContainsReferences>()); } } - /// Removes keys previously collected for one shard. - /// The dictionary to update. - /// The buffer containing keys. - /// The number of valid keys in the buffer. - /// The number of entries removed. - private int RemoveCollectedKeys(QuadDictionary dictionary, TKey[] keysBuffer, int keysCount) + /// Copies one shard into a rented array under its read lock. + /// The shard to copy. + /// Receives the number of entries copied. + /// A rented array the caller must return. + private KeyValuePair[] RentShardCopy(int shardIndex, out int count) { - var hasIndices = !Indices.IsEmpty; - var removed = 0; - for (var i = 0; i < keysCount; i++) + _locks[shardIndex].EnterReadLock(); + try { - if (!dictionary.Remove(keysBuffer[i], out var value)) + QuaternaryCore.ThrowIfDisposed(_state); + var quad = _quads[shardIndex]; + count = quad.Count; + var buffer = ArrayPool>.Shared.Rent(count); + var position = 0; + foreach (var entry in quad) { - continue; + buffer[position] = entry; + position++; } - if (hasIndices) - { - NotifyIndicesRemoved(value); - } - - removed++; + return buffer; } - - return removed; - } - - /// - /// Adds the specified key/value pairs to the collection, distributing them across internal shards for optimized - /// storage and concurrency. - /// - /// An array of key/value pairs to add to the collection. Each key must be non-null and conform to the requirements - /// of the underlying dictionary. - /// This method batches additions for efficiency and may perform operations in parallel if the - /// number of items exceeds a predefined threshold. If a key already exists, its value is overwritten. Index - /// notifications are triggered for each added value if indices are present. - private void AddRangeCore(KeyValuePair[] items) - { - var count = items.Length; - if (count == 0) + finally { - return; + _locks[shardIndex].ExitReadLock(); } + } - var rentedShardIndexes = (int[]?)null; - var shardIndexes = count <= StackAllocationThreshold - ? stackalloc int[count] - : (rentedShardIndexes = ArrayPool.Shared.Rent(count)).AsSpan(0, count); - + /// Removes the matched entries whose values are unchanged and publishes one notification for all of them. + /// The entries chosen by the predicate. + /// The number of valid entries in . + /// The number of removed entries. + private int RemoveMatchedEntries(KeyValuePair[] matches, int matchCount) + { + var removed = 0; + var notify = false; + Exception? failure = null; + QuaternaryShardHelpers.EnterAllWriteLocks(_locks); try { - Span shardCounts = stackalloc int[ShardCount]; - var itemsSpan = items.AsSpan(); - _ = QuaternaryShardHelpers.PartitionSpan(itemsSpan, shardIndexes, shardCounts, GetEntryShard); - - QuaternaryShardHelpers.EnterAllWriteLocks(Locks); + QuaternaryCore.ThrowIfDisposed(_state); + var removedEntries = QuaternaryCore.HasChangeObservers(_state) ? new KeyValuePair[matchCount] : null; try { - EnsureShardCapacities(shardCounts); - AddToCount(AddPreparedItems(itemsSpan, shardIndexes, !Indices.IsEmpty)); + for (var i = 0; i < matchCount; i++) + { + var quad = _quads[GetShard(matches[i].Key)]; + if (!quad.TryGetValue(matches[i].Key, out var current) + || !EqualityComparer.Default.Equals(current, matches[i].Value) + || !quad.Remove(matches[i].Key, out var value)) + { + continue; + } + + if (removedEntries is not null) + { + removedEntries[removed] = matches[i]; + } + + removed++; + var indexFailure = QuaternaryCore.IndexRemoved(_state, value); + failure ??= indexFailure; + } } finally { - QuaternaryShardHelpers.ExitAllWriteLocks(Locks); + // Key and value equality run user code, so the loop can stop part-way with entries already removed. + PublishRemovedEntries(0, removedEntries, removed); + notify = removed > 0 && _state.DeferralDepth == 0; } } finally { - if (rentedShardIndexes is not null) - { - ArrayPool.Shared.Return(rentedShardIndexes); - } + QuaternaryShardHelpers.ExitAllWriteLocks(_locks); + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); + } + + QuaternaryCore.RethrowIfFailed(failure); + return removed; + } + + /// Publishes the removed entries; call while the shard lock is held. + /// The shard whose write lock the caller holds. + /// The removed entries, or when nobody was listening. + /// The number of removed entries. + private void PublishRemovedEntries(int shard, KeyValuePair[]? removedEntries, int removed) + { + if (removed == 0) + { + return; } - EmitBatchAddedDirect(items, count); + if (removedEntries is null) + { + QuaternaryCore.AdvanceVersion(_state, shard); + return; + } + + QuaternaryCore.PublishOwnedBatchLocked(_state, shard, CacheAction.BatchRemoved, removedEntries, removed); } - /// Adds a collection of key/value pairs to the underlying data structure, distributing them across shards as appropriate. - /// The list of key/value pairs to add. Cannot be null. Each key is assigned to a shard based on its value. - private void AddRangeCore(IList> items) + /// Adds or updates the specified entries across the shards and publishes one notification. + /// The entries to store. + private void AddRangeCore(KeyValuePair[] items) { - var count = items.Count; + var count = items.Length; if (count == 0) { return; } + bool notify; + Exception? failure = null; var rentedShardIndexes = (int[]?)null; var shardIndexes = count <= StackAllocationThreshold ? stackalloc int[count] @@ -647,18 +882,22 @@ private void AddRangeCore(IList> items) try { - Span shardCounts = stackalloc int[ShardCount]; - _ = QuaternaryShardHelpers.PartitionList(items, count, shardIndexes, shardCounts, GetEntryShard); + Span shardCounts = stackalloc int[QuaternaryCore.FixedShardCount]; + var itemsSpan = items.AsSpan(); + _ = QuaternaryShardHelpers.PartitionSpan(itemsSpan, shardIndexes, shardCounts, GetEntryShard); - QuaternaryShardHelpers.EnterAllWriteLocks(Locks); + QuaternaryShardHelpers.EnterAllWriteLocks(_locks); try { + QuaternaryCore.ThrowIfDisposed(_state); EnsureShardCapacities(shardCounts); - AddToCount(AddPreparedItems(items, shardIndexes, !Indices.IsEmpty)); + var added = AddPreparedItems(itemsSpan, shardIndexes, ref failure); + QuaternaryCore.PublishBatchLocked(_state, 0, CacheAction.BatchAdded, itemsSpan, includesReplacements: added != count); + notify = _state.DeferralDepth == 0; } finally { - QuaternaryShardHelpers.ExitAllWriteLocks(Locks); + QuaternaryShardHelpers.ExitAllWriteLocks(_locks); } } finally @@ -669,58 +908,38 @@ private void AddRangeCore(IList> items) } } - EmitBatchAddedFromList(items, count); + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); + QuaternaryCore.RethrowIfFailed(failure); } /// Ensures each shard can accept its prepared additions without resizing. /// The number of additions prepared for each shard. private void EnsureShardCapacities(ReadOnlySpan shardCounts) { - for (var i = 0; i < ShardCount; i++) + for (var i = 0; i < QuaternaryCore.FixedShardCount; i++) { if (shardCounts[i] == 0) { continue; } - var dictionary = Quads[i]; + var dictionary = _quads[i]; dictionary.EnsureCapacity(dictionary.Count + shardCounts[i]); } } - /// Adds prepared array items directly to their shards. + /// Adds prepared items directly to their shards. /// The items to add. /// The precomputed shard for each item. - /// Whether secondary indices need updates. + /// Records the first exception a key selector threw while the indexes were updated. /// The number of newly added keys. - private int AddPreparedItems( - ReadOnlySpan> items, - ReadOnlySpan shardIndexes, - bool hasIndices) + private int AddPreparedItems(ReadOnlySpan> items, ReadOnlySpan shardIndexes, ref Exception? failure) { var added = 0; for (var i = 0; i < items.Length; i++) { - added += AddOrUpdatePreparedItem(items[i], shardIndexes[i], hasIndices); - } - - return added; - } - - /// Adds prepared list items directly to their shards. - /// The items to add. - /// The precomputed shard for each item. - /// Whether secondary indices need updates. - /// The number of newly added keys. - private int AddPreparedItems( - IList> items, - ReadOnlySpan shardIndexes, - bool hasIndices) - { - var added = 0; - for (var i = 0; i < shardIndexes.Length; i++) - { - added += AddOrUpdatePreparedItem(items[i], shardIndexes[i], hasIndices); + added += AddOrUpdatePreparedItem(items[i], shardIndexes[i], out var indexFailure); + failure ??= indexFailure; } return added; @@ -729,130 +948,73 @@ private int AddPreparedItems( /// Adds or updates one item after its shard has been selected and locked. /// The key/value pair to store. /// The precomputed shard index. - /// Whether secondary indices need updates. + /// Receives the exception a key selector threw while the indexes were updated, or . /// One for a new key; otherwise, zero. + /// The value is stored before the indexes run, so a throwing key selector cannot leave the entry half written. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private int AddOrUpdatePreparedItem(KeyValuePair item, int shardIndex, bool hasIndices) + private int AddOrUpdatePreparedItem(KeyValuePair item, int shardIndex, out Exception? failure) { - ref var value = ref Quads[shardIndex].GetValueRefOrAddDefault(item.Key, out var exists); - if (hasIndices && exists) - { - NotifyIndicesRemoved(value!); - } - + ref var value = ref _quads[shardIndex].GetValueRefOrAddDefault(item.Key, out var exists); + var previous = value; value = item.Value; - if (hasIndices) - { - NotifyIndicesAdded(item.Value); - } - + failure = exists + ? QuaternaryCore.IndexReplaced(_state, previous!, item.Value) + : QuaternaryCore.IndexAdded(_state, item.Value); return exists ? 0 : 1; } - /// Removes one key while all shard write locks are held. - /// The key to remove. - /// Whether secondary indices need updates. - /// One when the key existed and was removed; otherwise, zero. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private int TryRemoveKeyUnsafe(TKey key, bool hasIndices) - { - var shardIdx = GetShard(key); - if (!Quads[shardIdx].Remove(key, out var val)) - { - return 0; - } - - if (hasIndices) - { - NotifyIndicesRemoved(val); - } - - return 1; - } - - /// Applies a batch count delta and emits a batch notification when at least one key was removed. - /// The number of removed entries. - private void FinalizeRemovedBatch(int removed) - { - if (removed <= 0) - { - return; - } - - AddToCount(-removed); - Emit(CacheAction.BatchOperation, default); - } - - /// Removes the specified keys from the underlying data store, updating all relevant shards and indices as necessary. - /// An array of keys to remove from the data store. Cannot be null. If the array is empty, no action is taken. + /// Removes the specified keys, updating the count, indexes and notifications under all shard locks. + /// The keys to remove. Keys that do not exist are ignored. private void RemoveKeysCore(TKey[] keys) { - var count = keys.Length; - if (count == 0) + if (keys.Length == 0) { return; } - var keysSpan = keys.AsSpan(); var removed = 0; - - QuaternaryShardHelpers.EnterAllWriteLocks(Locks); + var notify = false; + Exception? failure = null; + QuaternaryShardHelpers.EnterAllWriteLocks(_locks); try { - var hasIndices = !Indices.IsEmpty; - for (var i = 0; i < count; i++) + QuaternaryCore.ThrowIfDisposed(_state); + + // The buffer is only built when someone is listening; a subscriber arriving mid-removal misses this event. + var removedEntries = QuaternaryCore.HasChangeObservers(_state) ? new KeyValuePair[keys.Length] : null; + try { - removed += TryRemoveKeyUnsafe(keysSpan[i], hasIndices); + for (var i = 0; i < keys.Length; i++) + { + if (!_quads[GetShard(keys[i])].Remove(keys[i], out var val)) + { + continue; + } + + if (removedEntries is not null) + { + removedEntries[removed] = new(keys[i], val); + } + + removed++; + var indexFailure = QuaternaryCore.IndexRemoved(_state, val); + failure ??= indexFailure; + } } - } - finally - { - QuaternaryShardHelpers.ExitAllWriteLocks(Locks); - } - - FinalizeRemovedBatch(removed); - } - - /// Removes the specified keys from the underlying data store, updating any associated indices as needed. - /// A list of keys to remove from the data store. Cannot be null. Keys that do not exist are ignored. - private void RemoveKeysCore(IList keys) - { - var count = keys.Count; - if (count == 0) - { - return; - } - - var removed = 0; - - QuaternaryShardHelpers.EnterAllWriteLocks(Locks); - try - { - var hasIndices = !Indices.IsEmpty; - for (var i = 0; i < count; i++) + finally { - removed += TryRemoveKeyUnsafe(keys[i], hasIndices); + // Hashing a key runs user code, so the loop can stop part-way with entries already removed. + PublishRemovedEntries(0, removedEntries, removed); + notify = removed > 0 && _state.DeferralDepth == 0; } } finally { - QuaternaryShardHelpers.ExitAllWriteLocks(Locks); - } - - FinalizeRemovedBatch(removed); - } - - /// Gets data for the GetCountUnsafe operation. - /// The current item count without acquiring locks. - private int GetCountUnsafe() - { - var count = 0; - for (var i = 0; i < ShardCount; i++) - { - count += Quads[i].Count; + QuaternaryShardHelpers.ExitAllWriteLocks(_locks); + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); } - return count; + QuaternaryCore.RethrowIfFailed(failure); } /// Internal wrapper for Edit operations that bypasses locking and notifications. @@ -862,40 +1024,25 @@ private sealed class QuaternaryDictEditWrapper : IDictionary private readonly QuaternaryDictionary _parent; /// Initializes a new instance of the class. - /// The parent value. + /// The dictionary being edited. internal QuaternaryDictEditWrapper(QuaternaryDictionary parent) => _parent = parent; - /// Gets a collection containing all keys in the dictionary. - /// The returned collection reflects the current set of keys in the dictionary at the - /// time of the call. The order of the keys in the collection is not guaranteed. Modifications to the dictionary - /// after retrieving the collection are not reflected in the returned collection. + /// Gets a copy of all keys in the dictionary. public ICollection Keys => QuaternaryShardHelpers.CollectFromShardsUnsafe, TKey>( - _parent.Quads, + _parent._quads, Count, static (shard, list) => shard.CopyKeysTo(list)); - /// Gets a collection containing all values in the dictionary. + /// Gets a copy of all values in the dictionary. public ICollection Values => QuaternaryShardHelpers.CollectFromShardsUnsafe, TValue>( - _parent.Quads, + _parent._quads, Count, static (shard, list) => shard.CopyValuesTo(list)); /// Gets the total number of elements contained in all shards. - public int Count - { - get - { - var count = 0; - for (var i = 0; i < ShardCount; i++) - { - count += _parent.Quads[i].Count; - } - - return count; - } - } + public int Count => QuaternaryCore.SumShardCounts(_parent._state); /// Gets a value indicating whether the collection is read-only. public bool IsReadOnly => false; @@ -903,158 +1050,111 @@ public int Count /// Gets or sets the value associated with the specified key. /// The key whose value to get or set. /// The value associated with the specified key. - /// Setting a value for an existing key may trigger index updates. Getting a value for a - /// key that does not exist will throw a KeyNotFoundException. public TValue this[TKey key] { - get - { - var idx = GetShard(key); - return _parent.Quads[idx][key]; - } + get => _parent._quads[GetShard(key)][key]; set { - var idx = GetShard(key); - var dict = _parent.Quads[idx]; - if (dict.TryGetValue(key, out var oldVal)) - { - _parent.NotifyIndicesRemoved(oldVal); - } + _ = _parent.AddOrUpdatePreparedItem(new(key, value), GetShard(key), out var failure); - dict[key] = value; - _parent.NotifyIndicesAdded(value); + // The edit still commits and announces what it changed when the exception leaves the action. + QuaternaryCore.RethrowIfFailed(failure); } } /// Adds the specified key and value to the collection. - /// The key associated with the value to add. Cannot be null. + /// The key associated with the value to add. /// The value to add to the collection. public void Add(TKey key, TValue value) { - var idx = GetShard(key); - _parent.Quads[idx].Add(key, value); - _parent.NotifyIndicesAdded(value); + _parent._quads[GetShard(key)].Add(key, value); + QuaternaryCore.RethrowIfFailed(QuaternaryCore.IndexAdded(_parent._state, value)); } /// Adds the specified key/value pair to the collection. - /// The key/value pair to add to the collection. The key must not already exist in the collection. + /// The key/value pair to add to the collection. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(KeyValuePair item) => Add(item.Key, item.Value); /// Determines whether the dictionary contains an element with the specified key. - /// The key to locate in the dictionary. Cannot be null. - /// if the dictionary contains an element with the specified key; otherwise, . - public bool ContainsKey(TKey key) - { - var idx = GetShard(key); - return _parent.Quads[idx].ContainsKey(key); - } + /// The key to locate in the dictionary. + /// if the key exists; otherwise, . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) => _parent._quads[GetShard(key)].ContainsKey(key); /// Removes the value with the specified key from the collection. /// The key of the element to remove. /// true if the element is successfully found and removed; otherwise, false. public bool Remove(TKey key) { - var idx = GetShard(key); - if (!_parent.Quads[idx].Remove(key, out var val)) + if (!_parent._quads[GetShard(key)].Remove(key, out var val)) { return false; } - _parent.NotifyIndicesRemoved(val); + QuaternaryCore.RethrowIfFailed(QuaternaryCore.IndexRemoved(_parent._state, val)); return true; } - /// Removes the first occurrence of the specified key/value pair from the collection. - /// The key/value pair to remove from the collection. The pair is removed only if both the key and value match - /// an entry in the collection. + /// Removes the specified key/value pair when both match. + /// The key/value pair to remove from the collection. /// true if the key/value pair was found and removed; otherwise, false. public bool Remove(KeyValuePair item) => Contains(item) && Remove(item.Key); /// Attempts to retrieve the value associated with the specified key. /// The key whose value to retrieve. - /// When this method returns, contains the value associated with the specified key, if the key is found; - /// otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized. - /// true if the object that implements the method contains an element with the specified key; otherwise, false. + /// When this method returns, contains the value associated with the specified key, if found. + /// true if the dictionary contains an element with the specified key; otherwise, false. #if NETFRAMEWORK public bool TryGetValue(TKey key, out TValue value) #else public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) #endif { - var idx = GetShard(key); - var found = _parent.Quads[idx].TryGetValue(key, out var result); + var found = _parent._quads[GetShard(key)].TryGetValue(key, out var result); value = result!; return found; } - /// Removes all items from the collection, resetting it to an empty state. - /// This method clears all data from the collection, including any associated indices. - /// After calling this method, the collection will contain no items and all indices will be empty. This - /// operation is not reversible. + /// Removes all items from the collection, including all associated indexes. public void Clear() { - for (var i = 0; i < ShardCount; i++) + for (var i = 0; i < QuaternaryCore.FixedShardCount; i++) { - _parent.Quads[i].Clear(); + _parent._quads[i].Clear(); } - if (_parent.Indices.IsEmpty) - { - return; - } - - foreach (var pair in _parent.Indices) - { - pair.Value.Clear(); - } + QuaternaryCore.ClearIndices(_parent._state); } /// Determines whether the dictionary contains the specified key and value pair. - /// The key and value pair to locate in the dictionary. The key is used to locate the entry, and the value is - /// compared to the value associated with the key. + /// The key and value pair to locate; the value is compared with the default equality comparer. /// true if the dictionary contains an element with the specified key and value; otherwise, false. - /// The value comparison uses the default equality comparer for the value type. If the - /// key is not found, the method returns false. public bool Contains(KeyValuePair item) => TryGetValue(item.Key, out var v) && EqualityComparer.Default.Equals(v, item.Value); /// Copies the elements of the collection to the specified array, starting at the given array index. - /// The one-dimensional array of key/value pairs that is the destination of the elements copied from the - /// collection. The array must have zero-based indexing. + /// The destination array. /// The zero-based index in the destination array at which copying begins. - /// The destination array must be large enough to contain all the elements of the - /// collection, starting at the specified index. The order of the copied elements matches the enumeration order - /// of the collection. public void CopyTo(KeyValuePair[] array, int arrayIndex) { - for (var i = 0; i < ShardCount; i++) - { - foreach (var kvp in _parent.Quads[i]) - { - array[arrayIndex] = kvp; - arrayIndex++; - } - } + ArgumentExceptionHelper.ThrowIfNull(array); + + _parent.FillLocked(array, arrayIndex); } - /// Returns an enumerator that iterates through the collection of key/value pairs in the dictionary. - /// An enumerator for the collection of key/value pairs contained in the dictionary. + /// Returns an enumerator over a copy of the key/value pairs in the dictionary. + /// An enumerator for the copied key/value pairs. public IEnumerator> GetEnumerator() { - for (var i = 0; i < ShardCount; i++) - { - foreach (var kvp in _parent.Quads[i]) - { - yield return kvp; - } - } + var copy = new KeyValuePair[Count]; + _parent.FillLocked(copy, 0); + return ((IEnumerable>)copy).GetEnumerator(); } /// Returns an enumerator that iterates through the collection. - /// An enumerator that can be used to iterate through the collection. + /// An object that can be used to iterate through the collection. [MethodImpl(MethodImplOptions.AggressiveInlining)] IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } diff --git a/src/ReactiveList/Collections/QuaternaryList.cs b/src/ReactiveList/Collections/QuaternaryList.cs index efd7a5fd..51f45d4a 100644 --- a/src/ReactiveList/Collections/QuaternaryList.cs +++ b/src/ReactiveList/Collections/QuaternaryList.cs @@ -13,14 +13,19 @@ namespace ReactiveList.Collections; /// /// The type of elements stored in the list. Must be non-nullable. /// QuaternaryList{T} is optimized for scenarios involving frequent additions, removals, and batch -/// operations on large datasets. Internally, items are distributed across four shards to reduce contention and improve -/// parallelism. The collection is not read-only and supports dynamic growth. Secondary indices can be added to enable -/// efficient lookups by arbitrary keys, which is useful for advanced querying scenarios. All public methods are -/// thread-safe. Direct index-based operations (such as Insert, RemoveAt, or setting by index) are not supported and -/// will throw exceptions; use Add, Remove, or batch methods instead. -[System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] +/// operations on large datasets. Internally, items are distributed across four shards, each guarded by its own reader-writer +/// lock, to reduce contention and improve parallelism. Operations that touch several shards take the locks in ascending shard +/// order. Change notifications are queued while the shard lock is still held, so observers see changes in the order they +/// happened, and are delivered by a single background reader. After every operation that reads or writes +/// items throws . The collection is not read-only and supports dynamic growth. Secondary +/// indices can be added to enable efficient lookups by arbitrary keys. All public methods are thread-safe. The list may hold +/// equal items more than once; an index returns one entry per copy. Enumeration, ToArray and Snapshot work on a point-in-time +/// copy, so a consumer can call back into the list while enumerating. Direct index-based operations (such as Insert, RemoveAt, +/// or setting by index) are not supported and will throw exceptions; use Add, Remove, or batch methods instead. The callbacks +/// given to Edit run while every shard is locked and must not call back into the list. +[System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] [SkipLocalsInit] -public class QuaternaryList : QuaternaryBase, IQuaternaryList +public sealed class QuaternaryList : IQuaternaryList, IVersionedSnapshotSource, INotifyPropertyChanged, IReactiveSourceWithOptions where T : notnull { /// Initial capacity used for buffers that collect removed items. @@ -32,23 +37,90 @@ public class QuaternaryList : QuaternaryBase, IQuaternaryList /// Largest buffer allocated on the stack. private const int StackAllocationThreshold = 1024; - /// The zero-based index of the third shard. - private const int ThirdShardIndex = 2; + /// The first shard, held in its own field so needs no array access. + private readonly QuadList _first; - /// The zero-based index of the fourth shard. - private const int FourthShardIndex = 3; + /// The second shard. + private readonly QuadList _second; + + /// The third shard. + private readonly QuadList _third; + + /// The fourth shard. + private readonly QuadList _fourth; + + /// The typed shard containers. + private readonly QuadList[] _quads; + + /// The shared collection state. + private readonly QuaternaryState _state; + + /// The shard locks, cached from the state to save an indirection on hot paths. + private readonly ReaderWriterLockSlim[] _locks; + + /// Initializes a new instance of the class. + /// This constructor captures the current synchronization context, which is typically associated + /// with the UI thread in WPF or Windows Forms applications. Legacy collection-changed handlers are raised on it. + public QuaternaryList() + { + _first = []; + _second = []; + _third = []; + _fourth = []; + _quads = [_first, _second, _third, _fourth]; + _state = QuaternaryCore.CreateState([_first, _second, _third, _fourth], nameof(QuaternaryList<>)); + _locks = _state.Locks; + } + + /// Occurs when the collection changes. + /// An exception thrown by a handler is isolated: later notifications are still delivered. + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add => QuaternaryEvents.AddCollectionChangedHandler(_state, this, value); + + remove => QuaternaryEvents.RemoveCollectionChangedHandler(_state, value); + } /// - protected override IReadOnlyList> BaseQuads => Quads; + public event PropertyChangedEventHandler? PropertyChanged; + + /// Gets the total number of items contained in all shards. + /// Each shard keeps its own count, so the value is exact only while no writer is running. + public int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _first.VolatileCount + _second.VolatileCount + _third.VolatileCount + _fourth.VolatileCount; + } + + /// Gets a value indicating whether the collection is read-only. + public bool IsReadOnly => false; + + /// Gets an observable sequence that emits cache change notifications as they occur. + /// + /// This is the primary observable for change notifications. It provides all change information + /// including single item changes and batch operations. An observer that throws from OnNext is unsubscribed and + /// receives the exception through its own OnError; other observers are unaffected. Subscribing to a disposed + /// collection completes immediately, and disposing the collection completes the stream after queued notifications are delivered. + /// + public IObservable> Stream => QuaternaryEvents.GetStream(_state); + + /// + public IObservable> VersionedStream => QuaternaryEvents.GetVersionedStream(_state); + + /// + public ReactiveSourceOptions Options { get; init; } = ReactiveSourceOptions.Default; + + /// Gets a value indicating whether the object has been disposed. + public bool IsDisposed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Volatile.Read(ref _state.Disposed) != 0; + } - /// Gets the typed shard containers used by the list implementation. - private QuadList[] Quads { get; } = - [ - [], - [], - [], - [] - ]; + /// Gets the current version number of the collection, which is incremented on each modification. + /// This property can be used for efficient change detection without acquiring locks. Changes made while + /// nobody observes the collection are counted per shard, so the value only ever grows and changes with every modification. + public long Version => QuaternaryCore.Version(_state); /// Gets or sets the element at the specified index. /// The zero-based index of the element. @@ -66,22 +138,27 @@ public T this[int index] public void Add(T item) { var idx = GetShardIndex(item); - Locks[idx].EnterWriteLock(); + var shardLock = _locks[idx]; + bool notify; + Exception? failure; + shardLock.EnterWriteLock(); try { - Quads[idx].Add(item); - AddToCount(1); - if (!Indices.IsEmpty) - { - NotifyIndicesAdded(item); - } + QuaternaryCore.ThrowIfDisposed(_state); + _quads[idx].Add(item); + + // A throwing key selector must not stop the change from being committed and announced. + failure = QuaternaryCore.IndexAdded(_state, item); + QuaternaryCore.PublishLocked(_state, idx, CacheAction.Added, item); + notify = _state.DeferralDepth == 0; } finally { - Locks[idx].ExitWriteLock(); + shardLock.ExitWriteLock(); } - Emit(CacheAction.Added, item); + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); + QuaternaryCore.RethrowIfFailed(failure); } /// Removes the specified item from the collection. @@ -91,234 +168,229 @@ public void Add(T item) public bool Remove(T item) { var idx = GetShardIndex(item); + var shardLock = _locks[idx]; bool removed; - Locks[idx].EnterWriteLock(); + var notify = false; + Exception? failure = null; + shardLock.EnterWriteLock(); try { - removed = Quads[idx].Remove(item); + QuaternaryCore.ThrowIfDisposed(_state); + removed = _quads[idx].Remove(item); if (removed) { - AddToCount(-1); - if (!Indices.IsEmpty) - { - NotifyIndicesRemoved(item); - } + failure = QuaternaryCore.IndexRemoved(_state, item); + QuaternaryCore.PublishLocked(_state, idx, CacheAction.Removed, item); + notify = _state.DeferralDepth == 0; } } finally { - Locks[idx].ExitWriteLock(); + shardLock.ExitWriteLock(); } - if (removed) - { - Emit(CacheAction.Removed, item); - } + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); + QuaternaryCore.RethrowIfFailed(failure); return removed; } + /// Removes all items from the cache. + /// The collection is disposed. + public void Clear() + { + var notify = QuaternaryCore.Clear(_state); + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); + } + + /// Defers change notifications until the last active deferral is disposed. + /// The token that releases this deferral. + /// The list is disposed. + /// Writes are immediately visible to readers. If the list changed, it publishes one reset when notifications resume. + /// Open and release deferrals outside callbacks that run under a shard lock. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NotificationDeferral DeferNotifications() => QuaternaryDeferrals.Begin(_state, ResumeNotifications); + + /// Releases all resources used by the current instance. + /// Disposal is idempotent and safe to call from several threads. The shards are released under their write locks, + /// so an operation already running finishes first and later operations throw . + /// The notification stream completes after the notifications already queued are delivered. + public void Dispose() => _ = QuaternaryCore.Dispose(_state); + /// Adds the elements of the specified collection to the current set. /// The collection of elements to add. + /// is . public void AddRange(IEnumerable collection) { - // Fast path for arrays - if (collection is T[] array) - { - AddRangeCore(array); - return; - } + ArgumentExceptionHelper.ThrowIfNull(collection); - // Fast path for IList - if (collection is IList list) + // Adding nothing must not pay for the batch machinery's stack frame. + var items = ListCompat.AsSpanOrCopy(collection); + if (items.IsEmpty) { - AddRangeCore(list); return; } - // Slow path: materialize - AddRangeCore([.. collection]); + AddCore(items, replace: false); } /// Removes all elements in the specified collection from the current set. /// The collection of elements to remove. + /// is . + /// An item that appears n times in removes up to n equal copies from the list. public void RemoveRange(IEnumerable collection) { - // Fast path for arrays - if (collection is T[] array) - { - RemoveRangeCore(array); - return; - } + ArgumentExceptionHelper.ThrowIfNull(collection); - // Fast path for IList - if (collection is IList list) - { - RemoveRangeCore(list); - return; - } - - // Slow path: materialize - RemoveRangeCore([.. collection]); + _ = RemoveRangeCore(ListCompat.AsSpanOrCopy(collection)); } /// Removes all elements that match the specified predicate from the collection. /// A function that returns true for elements that should be removed. /// The number of elements removed from the collection. + /// is . + /// The predicate runs on a point-in-time copy outside the locks, so it may read the list. Items added + /// after the copy was taken are not considered. public int RemoveMany(Func predicate) { - ThrowHelper.ThrowIfNull(predicate); - - var totalRemoved = 0; - - // Use pooled buffer for removed items - var removedBuffer = ArrayPool.Shared.Rent(InitialRemovalBufferSize); - var removedCount = 0; + ArgumentExceptionHelper.ThrowIfNull(predicate); + var snapshot = RentSnapshot(out var snapshotCount); + T[]? matches = null; + var matchCount = 0; try { - for (var i = 0; i < ShardCount; i++) + for (var i = 0; i < snapshotCount; i++) { - Locks[i].EnterWriteLock(); - try + if (predicate(snapshot[i])) { - var quad = Quads[i]; - for (var j = quad.Count - 1; j >= 0; j--) - { - var item = quad[j]; - if (!predicate(item)) - { - continue; - } - - quad.RemoveAt(j); - AddToCount(-1); - NotifyIndicesRemoved(item); - - // Grow buffer if needed - if (removedCount >= removedBuffer.Length) - { - QuaternaryShardHelpers.GrowPooledBuffer(ref removedBuffer, removedCount, CapacityGrowthFactor); - } - - removedBuffer[removedCount] = item; - removedCount++; - totalRemoved++; - } - } - finally - { - Locks[i].ExitWriteLock(); + QuaternaryShardHelpers.AppendPooled(ref matches, ref matchCount, snapshot[i], InitialRemovalBufferSize, CapacityGrowthFactor); } } - if (totalRemoved > 0) - { - EmitBatchRemoved(removedBuffer, removedCount); - } + return matchCount == 0 ? 0 : RemoveRangeCore(matches.AsSpan(0, matchCount)); } finally { - ArrayPool.Shared.Return(removedBuffer, clearArray: ArrayPoolClearHelper.IsReferenceOrContainsReferences()); + ArrayPool.Shared.Return(snapshot, clearArray: ArrayPoolClearHelper.IsReferenceOrContainsReferences()); + if (matches is not null) + { + ArrayPool.Shared.Return(matches, clearArray: ArrayPoolClearHelper.IsReferenceOrContainsReferences()); + } } - - return totalRemoved; } /// Performs a batch edit operation on the collection, ensuring only a single change notification is emitted. /// An action that receives an editable list interface to perform modifications. + /// is . + /// The action runs while every shard is write-locked, so it must not call back into the list. If it throws, + /// the edits made so far stay applied, the count and indexes are updated, and the notification is still emitted. public void Edit(Action> editAction) { - ThrowHelper.ThrowIfNull(editAction); + ArgumentExceptionHelper.ThrowIfNull(editAction); - QuaternaryShardHelpers.EnterAllWriteLocks(Locks); + var notify = false; try { - var wrapper = new QuaternaryEditWrapper(this); - editAction(wrapper); - SetCount(GetCountUnsafe()); + QuaternaryShardHelpers.EnterAllWriteLocks(_locks); + try + { + QuaternaryCore.ThrowIfDisposed(_state); + notify = _state.DeferralDepth == 0; + try + { + editAction(new QuaternaryEditWrapper(this)); + } + finally + { + QuaternaryCore.PublishMarkerLocked(_state, CacheAction.BatchOperation); + } + } + finally + { + QuaternaryShardHelpers.ExitAllWriteLocks(_locks); + } } finally { - QuaternaryShardHelpers.ExitAllWriteLocks(Locks); + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); } - - // Emit single batch notification after all changes - Emit(CacheAction.BatchOperation, default); } /// Replaces all existing items with new items atomically, emitting a single change notification. - /// The new items to replace all existing items with. Cannot be null. + /// The new items to replace all existing items with. Cannot be null. + /// is . /// This operation clears all existing items and adds the new items in a single atomic operation. /// Only one change notification is emitted for the entire operation. All indices are updated accordingly. - public void ReplaceAll(IEnumerable items) + public void ReplaceAll(IEnumerable collection) { - ThrowHelper.ThrowIfNull(items); - - var newItems = (items as T[]) ?? [.. items]; - - QuaternaryShardHelpers.EnterAllWriteLocks(Locks); - try - { - ClearItemsAndIndices(); - AddReplacementItems(newItems); - } - finally - { - QuaternaryShardHelpers.ExitAllWriteLocks(Locks); - } + ArgumentExceptionHelper.ThrowIfNull(collection); - // Emit single batch notification - Emit(CacheAction.BatchOperation, default); + AddCore(ListCompat.AsSpanOrCopy(collection), replace: true); } /// Adds a secondary index to enable efficient lookups based on a specified key selector. - /// The type of the key used for indexing. - /// The unique name of the index to add. + /// The type of the key used for indexing. + /// The unique name of the index to add. /// A function that extracts the key from each item for indexing. - public void AddIndex(string name, Func keySelector) - where TKey : notnull - { - var index = new SecondaryIndex(keySelector); - - // Populate existing data - for (var i = 0; i < ShardCount; i++) + /// or is . + /// The index is built and registered while every shard is write-locked, so no item is missed. An existing + /// index with the same name is replaced. If throws while the index is built, the index is not registered. + /// If it throws later, during a mutation, the mutation is still committed and announced, the index does not hold that item, + /// and the exception propagates to the caller after the change is complete. + public void AddIndex(string indexName, Func keySelector) + where TIndexKey : notnull + { + ArgumentExceptionHelper.ThrowIfNull(indexName); + ArgumentExceptionHelper.ThrowIfNull(keySelector); + + var index = new SecondaryIndex(keySelector); + QuaternaryShardHelpers.EnterAllWriteLocks(_locks); + try { - Locks[i].EnterReadLock(); - try + QuaternaryCore.ThrowIfDisposed(_state); + for (var i = 0; i < QuaternaryCore.FixedShardCount; i++) { - foreach (var item in Quads[i]) + var span = _quads[i].AsSpan(); + for (var j = 0; j < span.Length; j++) { - index.OnAdded(item); + index.OnAdded(span[j]); } } - finally - { - Locks[i].ExitReadLock(); - } - } - Indices[name] = index; + QuaternaryCore.RegisterIndex(_state, indexName, index); + } + finally + { + QuaternaryShardHelpers.ExitAllWriteLocks(_locks); + } } /// Retrieves all entities of type T that match the specified key in the given secondary index. - /// The type of the key used to query the secondary index. + /// The type of the key used to query the secondary index. /// The name of the secondary index to query. /// The key value to search for within the specified index. - /// An enumerable collection of entities that match the specified key. - public IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) - where TKey : notnull => - Indices.TryGetValue(indexName, out var idx) && idx is SecondaryIndex typedIdx ? typedIdx.Lookup(key) : []; + /// An enumerable collection of entities that match the specified key, one entry per stored copy. + /// is . + public IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) + where TIndexKey : notnull + { + ArgumentExceptionHelper.ThrowIfNull(indexName); + QuaternaryCore.ThrowIfDisposed(_state); + + return QuaternaryCore.TryGetIndex(_state, indexName, out var idx) && idx is SecondaryIndex typedIdx ? typedIdx.Lookup(key) : []; + } /// Determines whether the specified item matches the given key in the specified secondary index. - /// The type of the key used in the secondary index. + /// The type of the key used in the secondary index. /// The name of the secondary index to use for matching. /// The item to check. /// The key value to match against. /// if the item's indexed value matches the specified key; otherwise, . - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) - where TKey : notnull => - Indices.TryGetValue(indexName, out var idx) && idx.MatchesKey(item, key); + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) + where TIndexKey : notnull => + QuaternaryCore.TryGetIndex(_state, indexName, out var idx) + && (idx is SecondaryIndex typedIdx ? typedIdx.MatchesTypedKey(item, key) : idx.MatchesKey(item, key)); /// Determines whether the collection contains a specific value. /// The value to locate. @@ -327,152 +399,95 @@ public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) public bool Contains(T item) { var idx = GetShardIndex(item); - Locks[idx].EnterReadLock(); + var shardLock = _locks[idx]; + shardLock.EnterReadLock(); try { - // Use Span for faster iteration without enumerator allocation - var span = Quads[idx].AsSpan(); - var comparer = EqualityComparer.Default; - for (var i = 0; i < span.Length; i++) - { - if (comparer.Equals(span[i], item)) - { - return true; - } - } - - return false; + QuaternaryCore.ThrowIfDisposed(_state); + return _quads[idx].Contains(item); } finally { - Locks[idx].ExitReadLock(); + shardLock.ExitReadLock(); } } /// Copies the elements of the collection to an array. /// The destination array. /// The index at which to start copying. + /// is . + /// is negative. + /// The destination does not have room for every element. public void CopyTo(T[] array, int arrayIndex) { - for (var i = 0; i < ShardCount; i++) + ArgumentExceptionHelper.ThrowIfNull(array); + ArgumentOutOfRangeExceptionHelper.ThrowIfNegative(arrayIndex); + + QuaternaryShardHelpers.EnterAllReadLocks(_locks); + try { - Locks[i].EnterReadLock(); - try + QuaternaryCore.ThrowIfDisposed(_state); + if (array.Length - arrayIndex < QuaternaryCore.SumShardCounts(_state)) { - var sourceSpan = Quads[i].AsSpan(); - var destSpan = array.AsSpan(arrayIndex, sourceSpan.Length); - sourceSpan.CopyTo(destSpan); - arrayIndex += sourceSpan.Length; + throw new ArgumentException("The destination array is too small.", nameof(array)); } - finally + + for (var i = 0; i < QuaternaryCore.FixedShardCount; i++) { - Locks[i].ExitReadLock(); + _quads[i].CopyTo(array, arrayIndex); + arrayIndex += _quads[i].Count; } } + finally + { + QuaternaryShardHelpers.ExitAllReadLocks(_locks); + } } - /// Returns an enumerator that iterates through the collection. - /// An enumerator for the collection. - public override IEnumerator GetEnumerator() + /// Returns an array containing all elements in the collection. + /// An array that contains all elements of the collection. The array is empty if the collection contains no elements. + /// The collection is disposed. + public T[] ToArray() { - for (var i = 0; i < ShardCount; i++) - { - Locks[i].EnterReadLock(); - try - { - foreach (var item in Quads[i]) - { - yield return item; - } - } - finally - { - Locks[i].ExitReadLock(); - } - } + QuaternaryCore.ThrowIfDisposed(_state); + return Count == 0 ? [] : CopyVersioned(out _); } - /// Creates a snapshot of the current items as a read-only list. - /// A read-only list containing the items at the time of the call. The returned list is independent of subsequent - /// changes to the original collection. - public IReadOnlyList Snapshot() + /// + public T[] CopyVersioned(out long version) { - var acquiredCount = 0; + QuaternaryShardHelpers.EnterAllReadLocks(_locks); try { - for (; acquiredCount < ShardCount; acquiredCount++) - { - Locks[acquiredCount].EnterReadLock(); - } - - var total = 0; - for (var i = 0; i < ShardCount; i++) - { - total += Quads[i].Count; - } - - var result = new T[total]; - var offset = 0; - for (var i = 0; i < ShardCount; i++) - { - var quad = Quads[i]; - quad.CopyTo(result, offset); - offset += quad.Count; - } - - return result; + QuaternaryCore.ThrowIfDisposed(_state); + version = Interlocked.Read(ref _state.Version); + return CopyLocked(); } finally { - for (var i = acquiredCount - 1; i >= 0; i--) - { - Locks[i].ExitReadLock(); - } + QuaternaryShardHelpers.ExitAllReadLocks(_locks); } } - /// Adds data for the AddRemoveCount operation. - /// The shardIndex value. - /// The item value. - /// The remove0 value. - /// The remove1 value. - /// The remove2 value. - /// The remove3 value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void AddRemoveCount( - int shardIndex, - T item, - ref Dictionary? remove0, - ref Dictionary? remove1, - ref Dictionary? remove2, - ref Dictionary? remove3) + /// Returns an enumerator over a point-in-time copy of the collection. + /// An enumerator for the collection. + /// No lock is held while the enumerator is in use. Dispose the enumerator to return its buffer to the pool. + public IEnumerator GetEnumerator() { - var counts = shardIndex switch - { - 0 => remove0 ??= [], - 1 => remove1 ??= [], - ThirdShardIndex => remove2 ??= [], - _ => remove3 ??= [], - }; - - counts[item] = counts.TryGetValue(item, out var existing) ? existing + 1 : 1; + var snapshot = RentSnapshot(out var count); + return new PooledSnapshotEnumerator(snapshot, count); } - /// Copies data for the CopyRemoved operation. - /// The source value. - /// The destination value. - /// The offset value. + /// Creates a snapshot of the current items as a read-only list. + /// A read-only list containing the items at the time of the call. The returned list is independent of subsequent + /// changes to the original collection. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void CopyRemoved(List? source, T[] destination, ref int offset) - { - if (source is null) - { - return; - } + public IReadOnlyList Snapshot() => ToArray(); - source.CopyTo(destination, offset); - offset += source.Count; - } + /// Returns an enumerator that iterates through the collection. + /// An object that can be used to iterate through the collection. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// Calculates the shard index for the specified item based on its hash code. /// The item for which to compute the shard index. Can be null. @@ -480,121 +495,49 @@ private static void CopyRemoved(List? source, T[] destination, ref int offset [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int GetShardIndex(T? item) => ShardHash.GetShardIndex4(item); - /// Rents one replacement buffer for each non-empty shard. - /// The number of items assigned to each shard. - /// The shard buffers. - private static T[][] RentReplacementBuckets(ReadOnlySpan bucketCounts) - { - var bucketArrays = new T[ShardCount][]; - for (var i = 0; i < ShardCount; i++) - { - bucketArrays[i] = bucketCounts[i] == 0 ? [] : ArrayPool.Shared.Rent(bucketCounts[i]); - } - - return bucketArrays; - } - - /// Populates rented shard buffers using precomputed write offsets. - /// The replacement items. - /// The destination shard buffers. - /// The next write index for each shard. - private static void PopulateReplacementBuckets(T[] items, T[][] bucketArrays, Span bucketIndexes) + /// Routes each item to its shard and counts the items per shard, without a delegate call per item. + /// The items to route. + /// Receives the shard of each item. + /// Receives the number of items routed to each shard. + private static void PartitionItems(ReadOnlySpan items, Span shardIndexes, Span shardCounts) { + shardCounts.Clear(); for (var i = 0; i < items.Length; i++) { - var item = items[i]; - var shardIndex = GetShardIndex(item); - bucketArrays[shardIndex][bucketIndexes[shardIndex]] = item; - bucketIndexes[shardIndex]++; + var shardIndex = GetShardIndex(items[i]); + shardIndexes[i] = shardIndex; + shardCounts[shardIndex]++; } } - /// Returns every rented replacement buffer to the shared pool. - /// The shard buffers. - /// The active item count in each buffer. - private static void ReturnReplacementBuckets(T[][] bucketArrays, ReadOnlySpan bucketCounts) + /// Copies the list while all shard locks are held. + /// The contents in shard order. + private T[] CopyLocked() { - for (var i = 0; i < ShardCount; i++) + var total = QuaternaryCore.SumShardCounts(_state); + if (total == 0) { - if (bucketCounts[i] != 0) - { - ArrayPool.Shared.Return(bucketArrays[i], clearArray: ArrayPoolClearHelper.IsReferenceOrContainsReferences()); - } + return []; } - } - /// Clears every shard and secondary index while all shard locks are held. - private void ClearItemsAndIndices() - { - for (var i = 0; i < ShardCount; i++) + // Every shard lock is held, so the counts cannot change before the copies fill the array. + var result = ArrayCompat.AllocateForFullOverwrite(total); + var offset = 0; + for (var i = 0; i < QuaternaryCore.FixedShardCount; i++) { - Quads[i].Clear(); + _quads[i].CopyTo(result, offset); + offset += _quads[i].Count; } - SetCount(0); - foreach (var pair in Indices) - { - pair.Value.Clear(); - } + return result; } - /// Adds replacement items from pre-grouped pooled shard buffers. - /// The replacement items. - private void AddReplacementItems(T[] items) + /// Releases the token and reports any deferred property changes outside the shard locks. + /// The shared token state. + private void ResumeNotifications(NotificationDeferralState release) { - if (items.Length == 0) - { - return; - } - - Span bucketCounts = stackalloc int[ShardCount]; - Span bucketIndexes = stackalloc int[ShardCount]; - bucketCounts.Clear(); - bucketIndexes.Clear(); - for (var i = 0; i < items.Length; i++) - { - bucketCounts[GetShardIndex(items[i])]++; - } - - var bucketArrays = RentReplacementBuckets(bucketCounts); - try - { - PopulateReplacementBuckets(items, bucketArrays, bucketIndexes); - AppendReplacementBuckets(bucketArrays, bucketCounts); - } - finally - { - ReturnReplacementBuckets(bucketArrays, bucketCounts); - } - } - - /// Appends grouped replacement buffers to their destination shards. - /// The populated shard buffers. - /// The active item count in each buffer. - private void AppendReplacementBuckets(T[][] bucketArrays, ReadOnlySpan bucketCounts) - { - var hasIndices = !Indices.IsEmpty; - for (var shardIndex = 0; shardIndex < ShardCount; shardIndex++) - { - var bucketCount = bucketCounts[shardIndex]; - if (bucketCount == 0) - { - continue; - } - - var bucket = bucketArrays[shardIndex].AsSpan(0, bucketCount); - Quads[shardIndex].AddRange(bucket); - AddToCount(bucketCount); - if (!hasIndices) - { - continue; - } - - for (var i = 0; i < bucket.Length; i++) - { - NotifyIndicesAdded(bucket[i]); - } - } + var notify = QuaternaryDeferrals.End(_state, release, CopyLocked); + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); } /// Retrieves the element at the specified global index across all shards. @@ -604,88 +547,73 @@ private void AppendReplacementBuckets(T[][] bucketArrays, ReadOnlySpan buck /// Thrown when the specified index is less than 0 or greater than or equal to the total number of elements. private T GetAtGlobalIndex(int index) { - for (var i = 0; i < ShardCount; i++) + // Only the shards up to the one holding the item decide its position, so the read locks are taken in ascending + // order and kept until the item is read, and a lookup in an early shard never touches the later locks. + var held = 0; + try { - Locks[i].EnterReadLock(); - try + while (held < QuaternaryCore.FixedShardCount) { - var quadCount = Quads[i].Count; + _locks[held].EnterReadLock(); + held++; + QuaternaryCore.ThrowIfDisposed(_state); + if (index < 0) + { + break; + } + + var quad = _quads[held - 1]; + var quadCount = quad.Count; if (index < quadCount) { - return Quads[i][index]; + return quad[index]; } index -= quadCount; } - finally - { - Locks[i].ExitReadLock(); - } - } - throw new ArgumentOutOfRangeException(nameof(index)); - } - - /// Adds the specified array of items to the collection, distributing them across internal shards as appropriate. - /// The array of items to add to the collection. Cannot be null. Items are assigned to shards based on their shard - /// index. - /// This method optimizes insertion by batching items and distributing them to shards in parallel - /// when the number of items exceeds a predefined threshold. For smaller batches, insertion is performed - /// sequentially. The method is intended for internal use and does not perform input validation; callers must ensure - /// that the input array is not null. - private void AddRangeCore(T[] items) - { - var count = items.Length; - if (count == 0) + throw new ArgumentOutOfRangeException(nameof(index)); + } + finally { - return; + QuaternaryShardHelpers.ExitReadLocks(_locks, held); } + } - var rentedShardIndexes = (int[]?)null; - var shardIndexes = count <= StackAllocationThreshold - ? stackalloc int[count] - : (rentedShardIndexes = ArrayPool.Shared.Rent(count)).AsSpan(0, count); - + /// Copies every item into a rented array while holding all shard read locks. + /// Receives the number of items copied. + /// A rented array the caller must return to the shared pool. + private T[] RentSnapshot(out int count) + { + QuaternaryShardHelpers.EnterAllReadLocks(_locks); try { - Span shardCounts = stackalloc int[ShardCount]; - var itemsSpan = items.AsSpan(); - _ = QuaternaryShardHelpers.PartitionSpan(itemsSpan, shardIndexes, shardCounts, GetShardIndex); - - QuaternaryShardHelpers.EnterAllWriteLocks(Locks); - try - { - EnsureShardCapacities(shardCounts); - AddPreparedItems(itemsSpan, shardIndexes, !Indices.IsEmpty); - AddToCount(count); - } - finally + QuaternaryCore.ThrowIfDisposed(_state); + count = QuaternaryCore.SumShardCounts(_state); + var buffer = ArrayPool.Shared.Rent(count); + var offset = 0; + for (var i = 0; i < QuaternaryCore.FixedShardCount; i++) { - QuaternaryShardHelpers.ExitAllWriteLocks(Locks); + _quads[i].CopyTo(buffer, offset); + offset += _quads[i].Count; } + + return buffer; } finally { - if (rentedShardIndexes is not null) - { - ArrayPool.Shared.Return(rentedShardIndexes); - } + QuaternaryShardHelpers.ExitAllReadLocks(_locks); } - - EmitBatchAddedDirect(items, count); } - /// Adds the elements of the specified list to the collection, distributing them across internal shards as appropriate. - /// The list of items to add to the collection. Cannot be null. Items are assigned to shards based on their shard - /// index. - private void AddRangeCore(IList items) + /// Adds the items to the shards, optionally replacing the current contents, and publishes one notification. + /// The items to add. + /// Whether the existing items are removed first. + private void AddCore(ReadOnlySpan items, bool replace) { - var count = items.Count; - if (count == 0) - { - return; - } - + var count = items.Length; + bool notify; + Exception? failure = null; var rentedShardIndexes = (int[]?)null; var shardIndexes = count <= StackAllocationThreshold ? stackalloc int[count] @@ -693,19 +621,42 @@ private void AddRangeCore(IList items) try { - Span shardCounts = stackalloc int[ShardCount]; - _ = QuaternaryShardHelpers.PartitionList(items, count, shardIndexes, shardCounts, GetShardIndex); + Span shardCounts = stackalloc int[QuaternaryCore.FixedShardCount]; + PartitionItems(items, shardIndexes, shardCounts); - QuaternaryShardHelpers.EnterAllWriteLocks(Locks); + QuaternaryShardHelpers.EnterAllWriteLocks(_locks); try { + QuaternaryCore.ThrowIfDisposed(_state); + if (replace) + { + ClearShards(); + } + EnsureShardCapacities(shardCounts); - AddPreparedItems(items, shardIndexes, !Indices.IsEmpty); - AddToCount(count); + for (var i = 0; i < count; i++) + { + _quads[shardIndexes[i]].AddAssumeCapacity(items[i]); + + // A throwing key selector must not leave the rest of the batch unstored or the change unannounced. + var indexFailure = QuaternaryCore.IndexAdded(_state, items[i]); + failure ??= indexFailure; + } + + if (replace) + { + QuaternaryCore.PublishMarkerLocked(_state, CacheAction.BatchOperation); + } + else + { + QuaternaryCore.PublishBatchLocked(_state, 0, CacheAction.BatchAdded, items); + } + + notify = _state.DeferralDepth == 0; } finally { - QuaternaryShardHelpers.ExitAllWriteLocks(Locks); + QuaternaryShardHelpers.ExitAllWriteLocks(_locks); } } finally @@ -716,226 +667,186 @@ private void AddRangeCore(IList items) } } - EmitBatchAddedFromList(items, count); + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); + QuaternaryCore.RethrowIfFailed(failure); + } + + /// Clears every shard, the count, and the indexes while all shard locks are held. + private void ClearShards() + { + for (var i = 0; i < QuaternaryCore.FixedShardCount; i++) + { + _quads[i].Clear(); + } + + QuaternaryCore.ClearIndices(_state); } /// Ensures each shard can accept its prepared additions without resizing. /// The number of additions prepared for each shard. private void EnsureShardCapacities(ReadOnlySpan shardCounts) { - for (var i = 0; i < ShardCount; i++) + for (var i = 0; i < QuaternaryCore.FixedShardCount; i++) { if (shardCounts[i] == 0) { continue; } - var quad = Quads[i]; + var quad = _quads[i]; quad.EnsureCapacity(quad.Count + shardCounts[i]); } } - /// Adds prepared array items directly to their shards. - /// The items to add. - /// The precomputed shard for each item. - /// Whether secondary indices need updates. - private void AddPreparedItems(ReadOnlySpan items, ReadOnlySpan shardIndexes, bool hasIndices) - { - for (var i = 0; i < items.Length; i++) - { - AddPreparedItem(items[i], shardIndexes[i], hasIndices); - } - } - - /// Adds prepared list items directly to their shards. - /// The items to add. - /// The precomputed shard for each item. - /// Whether secondary indices need updates. - private void AddPreparedItems(IList items, ReadOnlySpan shardIndexes, bool hasIndices) + /// Removes the specified items from the collection, one shard at a time. + /// The items to remove; an item listed n times removes up to n copies. + /// The number of items removed. + private int RemoveRangeCore(ReadOnlySpan items) { - for (var i = 0; i < shardIndexes.Length; i++) + if (items.IsEmpty) { - AddPreparedItem(items[i], shardIndexes[i], hasIndices); + return 0; } - } - /// Adds one item after its shard has been selected and locked. - /// The item to add. - /// The precomputed shard index. - /// Whether secondary indices need updates. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void AddPreparedItem(T item, int shardIndex, bool hasIndices) - { - Quads[shardIndex].AddAssumeCapacity(item); - if (!hasIndices) + // The counts live in pooled arrays, and only the shards that can hold a requested item are scanned. + var counts = PooledItemCounts.Create(items.Length); + var removed = 0; + var notify = false; + Exception? failure = null; + try { - return; - } - - NotifyIndicesAdded(item); - } + var shardMask = 0; + for (var i = 0; i < items.Length; i++) + { + counts.Add(items[i]); + shardMask |= 1 << GetShardIndex(items[i]); + } - /// Removes the specified items from the collection, processing them in batches for efficiency. - /// An array of items to remove from the collection. The array must not be null, but may be empty. - /// This method distributes removal operations across internal shards and may perform removals in - /// parallel for large input arrays to improve performance. Removal is performed in batch, and any associated - /// indices are updated accordingly. The method is not thread-safe and should be called only when appropriate - /// synchronization is ensured by the caller. - private void RemoveRangeCore(T[] items) - { - var count = items.Length; - if (count == 0) - { - return; + try + { + QuaternaryShardHelpers.EnterAllWriteLocks(_locks); + try + { + QuaternaryCore.ThrowIfDisposed(_state); + var before = QuaternaryCore.SumShardCounts(_state); + try + { + removed = RemoveCountedItemsLocked(ref counts, shardMask, items.Length, out failure); + } + finally + { + // Hashing a stored item runs user code, so a removal can stop part-way and still have changed the list. + notify = QuaternaryCore.SumShardCounts(_state) != before && _state.DeferralDepth == 0; + } + } + finally + { + QuaternaryShardHelpers.ExitAllWriteLocks(_locks); + } + } + finally + { + QuaternaryCore.RaisePropertyChanged(PropertyChanged, this, notify); + } } - - Dictionary? remove0 = null; - Dictionary? remove1 = null; - Dictionary? remove2 = null; - Dictionary? remove3 = null; - var itemsSpan = items.AsSpan(); - - for (var i = 0; i < count; i++) + finally { - var item = itemsSpan[i]; - AddRemoveCount(GetShardIndex(item), item, ref remove0, ref remove1, ref remove2, ref remove3); + counts.Dispose(); } - RemoveFromShards(remove0, remove1, remove2, remove3); + QuaternaryCore.RethrowIfFailed(failure); + return removed; } - /// Removes the specified collection of items from the data structure in a batch operation. - /// The list of items to remove. Cannot be null. Items that are not present in the data structure are ignored. - /// This method performs removals in a sharded and potentially parallelized manner for improved - /// performance with large collections. Removal notifications are triggered for each item that is successfully - /// removed. The operation is thread-safe. - private void RemoveRangeCore(IList items) - { - var count = items.Count; - if (count == 0) + /// Removes the counted items from the shards that can hold them and publishes one notification; the caller holds all write locks. + /// How many copies of each item to remove. + /// A bit for every shard that can hold a requested item. + /// The total number of copies requested. + /// Receives the first exception a key selector threw while the indexes were updated, or . + /// The number of items removed. + /// If user code throws part-way, the items removed so far are still counted, indexed and announced before the exception propagates. + private int RemoveCountedItemsLocked(ref PooledItemCounts counts, int shardMask, int requested, out Exception? failure) + { + failure = null; + var observed = QuaternaryCore.HasChangeObservers(_state); + var before = QuaternaryCore.SumShardCounts(_state); + var buffer = RentRemovalBuffer(observed, Math.Min(requested, before)); + var removed = 0; + try { - return; + for (var shard = 0; shard < QuaternaryCore.FixedShardCount; shard++) + { + if ((shardMask & (1 << shard)) != 0) + { + removed += _quads[shard].RemoveMatching(ref counts, buffer is null ? default : buffer.AsSpan(removed)); + } + } } - - Dictionary? remove0 = null; - Dictionary? remove1 = null; - Dictionary? remove2 = null; - Dictionary? remove3 = null; - - for (var i = 0; i < count; i++) + finally { - var item = items[i]; - AddRemoveCount(GetShardIndex(item), item, ref remove0, ref remove1, ref remove2, ref remove3); + removed = before - QuaternaryCore.SumShardCounts(_state); + if (removed > 0) + { + failure = IndexRemovedItems(buffer, removed); + PublishRemoved(observed ? buffer : null, removed); + } + + if (buffer is not null && !observed) + { + ArrayPool.Shared.Return(buffer, clearArray: ArrayPoolClearHelper.IsReferenceOrContainsReferences()); + } } - RemoveFromShards(remove0, remove1, remove2, remove3); + return removed; } - /// Removes data for the RemoveFromShards operation. - /// The remove0 value. - /// The remove1 value. - /// The remove2 value. - /// The remove3 value. - private void RemoveFromShards( - Dictionary? remove0, - Dictionary? remove1, - Dictionary? remove2, - Dictionary? remove3) + /// Gets the buffer that collects removed items, or when nobody needs them. + /// Whether a subscriber needs the removed items. + /// The largest number of items that can be removed. + /// A plain array for subscribers (published batches are never pooled), a rented array for indexes only, or . + private T[]? RentRemovalBuffer(bool observed, int limit) { - var hasIndices = !Indices.IsEmpty; - var captureRemovedItems = hasIndices || HasChangeObservers(); - var totalRemoved = 0; - - var removed0 = RemoveFromShard(0, remove0, captureRemovedItems, hasIndices, ref totalRemoved); - var removed1 = RemoveFromShard(1, remove1, captureRemovedItems, hasIndices, ref totalRemoved); - var removed2 = RemoveFromShard(ThirdShardIndex, remove2, captureRemovedItems, hasIndices, ref totalRemoved); - var removed3 = RemoveFromShard(FourthShardIndex, remove3, captureRemovedItems, hasIndices, ref totalRemoved); - - if (totalRemoved == 0) + if (observed) { - return; + return new T[limit]; } - AddToCount(-totalRemoved); - EmitRemovedItems(totalRemoved, removed0, removed1, removed2, removed3); + return QuaternaryCore.HasIndexes(_state) ? ArrayPool.Shared.Rent(limit) : null; } - /// Removes data for the RemoveFromShard operation. - /// The shardIndex value. - /// The removeCounts value. - /// The captureRemovedItems value. - /// The hasIndices value. - /// The totalRemoved value. - /// The removed items when they are captured; otherwise, . - private List? RemoveFromShard( - int shardIndex, - Dictionary? removeCounts, - bool captureRemovedItems, - bool hasIndices, - ref int totalRemoved) + /// Notifies the indexes of every removed item. + /// The buffer holding the removed items, or . + /// The number of removed items. + /// The first exception a key selector threw, or ; every item is still removed from the indexes that can key it. + private Exception? IndexRemovedItems(T[]? buffer, int removed) { - if (removeCounts is null) + if (buffer is null || !QuaternaryCore.HasIndexes(_state)) { return null; } - var removedItems = captureRemovedItems ? new List(Math.Min(removeCounts.Count, Quads[shardIndex].Count)) : null; - Locks[shardIndex].EnterWriteLock(); - try - { - totalRemoved += Quads[shardIndex].RemoveMatching(removeCounts, removedItems); - } - finally - { - Locks[shardIndex].ExitWriteLock(); - } - - if (hasIndices && removedItems is not null) + Exception? failure = null; + for (var i = 0; i < removed; i++) { - for (var i = 0; i < removedItems.Count; i++) - { - NotifyIndicesRemoved(removedItems[i]); - } + var indexFailure = QuaternaryCore.IndexRemoved(_state, buffer[i]); + failure ??= indexFailure; } - return removedItems; + return failure; } - /// Performs the EmitRemovedItems operation. - /// The totalRemoved value. - /// The removed0 value. - /// The removed1 value. - /// The removed2 value. - /// The removed3 value. - private void EmitRemovedItems(int totalRemoved, List? removed0, List? removed1, List? removed2, List? removed3) + /// Publishes a removal batch when the buffer is publishable; otherwise only advances the version. + /// A plain array holding the removed items, or when nobody is listening. + /// The number of removed items. + private void PublishRemoved(T[]? publishable, int removed) { - if (!HasChangeObservers()) + if (publishable is null) { - Emit(CacheAction.BatchRemoved, default); + QuaternaryCore.AdvanceVersion(_state, 0); return; } - var removed = new T[totalRemoved]; - var offset = 0; - CopyRemoved(removed0, removed, ref offset); - CopyRemoved(removed1, removed, ref offset); - CopyRemoved(removed2, removed, ref offset); - CopyRemoved(removed3, removed, ref offset); - - EmitOwnedBatchRemoved(removed, removed.Length); - } - - /// Gets data for the GetCountUnsafe operation. - /// The current item count without acquiring locks. - private int GetCountUnsafe() - { - var count = 0; - for (var i = 0; i < ShardCount; i++) - { - count += Quads[i].Count; - } - - return count; + QuaternaryCore.PublishOwnedBatchLocked(_state, 0, CacheAction.BatchRemoved, publishable, removed); } /// Internal wrapper for Edit operations that bypasses locking and notifications. @@ -944,31 +855,12 @@ private sealed class QuaternaryEditWrapper : ICollection /// The list whose shards are edited. private readonly QuaternaryList _parent; - /// Indicates whether secondary indexes must be maintained. - private readonly bool _hasIndices; - /// Initializes a new instance of the class. - /// The parent value. - internal QuaternaryEditWrapper(QuaternaryList parent) - { - _parent = parent; - _hasIndices = !parent.Indices.IsEmpty; - } + /// The list being edited. + internal QuaternaryEditWrapper(QuaternaryList parent) => _parent = parent; /// Gets the total number of items contained in all shards. - public int Count - { - get - { - var count = 0; - for (var i = 0; i < ShardCount; i++) - { - count += _parent.Quads[i].Count; - } - - return count; - } - } + public int Count => QuaternaryCore.SumShardCounts(_parent._state); /// Gets a value indicating whether the collection is read-only. public bool IsReadOnly => false; @@ -978,14 +870,10 @@ public int Count [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T item) { - var idx = GetShardIndex(item); - _parent.Quads[idx].Add(item); - if (!_hasIndices) - { - return; - } + _parent._quads[GetShardIndex(item)].Add(item); - _parent.NotifyIndicesAdded(item); + // The edit still commits and announces what it changed when the exception leaves the action. + QuaternaryCore.RethrowIfFailed(QuaternaryCore.IndexAdded(_parent._state, item)); } /// Removes the specified item from the collection. @@ -993,81 +881,52 @@ public void Add(T item) /// true if the item was successfully removed; otherwise, false. public bool Remove(T item) { - var idx = GetShardIndex(item); - if (!_parent.Quads[idx].Remove(item)) + if (!_parent._quads[GetShardIndex(item)].Remove(item)) { return false; } - if (!_hasIndices) - { - return true; - } - - _parent.NotifyIndicesRemoved(item); + QuaternaryCore.RethrowIfFailed(QuaternaryCore.IndexRemoved(_parent._state, item)); return true; } /// Removes all items from the collection, including all shards and associated indices. - /// After calling this method, the collection will be empty and any indices will also be - /// cleared. This operation affects all shards managed by the parent object. public void Clear() { - for (var i = 0; i < ShardCount; i++) - { - _parent.Quads[i].Clear(); - } - - if (!_hasIndices) + for (var i = 0; i < QuaternaryCore.FixedShardCount; i++) { - return; + _parent._quads[i].Clear(); } - foreach (var pair in _parent.Indices) - { - pair.Value.Clear(); - } + QuaternaryCore.ClearIndices(_parent._state); } /// Determines whether the collection contains a specific value. /// The value to locate in the collection. /// true if the item is found in the collection; otherwise, false. - public bool Contains(T item) - { - var idx = GetShardIndex(item); - return _parent.Quads[idx].Contains(item); - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(T item) => _parent._quads[GetShardIndex(item)].Contains(item); /// Copies the elements of the collection to the specified array, starting at the specified array index. - /// The one-dimensional array that is the destination of the elements copied from the collection. The array must - /// have zero-based indexing. + /// The one-dimensional array that is the destination of the elements copied from the collection. /// The zero-based index in the destination array at which copying begins. - /// The destination array must be large enough to contain all the elements of the - /// collection starting at the specified index. If the array is not large enough, an exception will be - /// thrown. public void CopyTo(T[] array, int arrayIndex) { - for (var i = 0; i < ShardCount; i++) + for (var i = 0; i < QuaternaryCore.FixedShardCount; i++) { - var quad = _parent.Quads[i]; + var quad = _parent._quads[i]; quad.CopyTo(array, arrayIndex); arrayIndex += quad.Count; } } - /// Returns an enumerator that iterates through the collection of items contained in all shards. + /// Returns an enumerator over a copy of the items contained in all shards. /// An enumerator that can be used to iterate through the items in the collection. - /// The enumeration traverses the items in each shard in order, starting from the first - /// shard to the last. The order of items within each shard is preserved. public IEnumerator GetEnumerator() { - for (var i = 0; i < ShardCount; i++) - { - foreach (var item in _parent.Quads[i]) - { - yield return item; - } - } + var copy = new T[Count]; + CopyTo(copy, 0); + return ((IEnumerable)copy).GetEnumerator(); } /// Returns an enumerator that iterates through the collection. diff --git a/src/ReactiveList/Collections/Reactive2DList.cs b/src/ReactiveList/Collections/Reactive2DList.cs index 20d0951d..572c12d6 100644 --- a/src/ReactiveList/Collections/Reactive2DList.cs +++ b/src/ReactiveList/Collections/Reactive2DList.cs @@ -7,70 +7,219 @@ namespace ReactiveList.Reactive.Collections; #else namespace ReactiveList.Collections; #endif + /// /// Represents a two-dimensional reactive list, where each element is itself a reactive list of items of type /// . Provides methods for managing and observing changes to a collection of collections in a /// reactive manner. /// /// The type of elements contained in the inner lists. Must be non-nullable. -/// Use to manage tabular or matrix-like data structures where both rows -/// and individual items can be observed for changes. This class is useful in scenarios where you need to react to -/// modifications at either the outer or inner list level, such as in UI data binding or dynamic data grids. All -/// mutation operations are observable, enabling integration with reactive programming patterns. -public class Reactive2DList : ReactiveList> +/// +/// The outer list is a of rows that this type holds and forwards to, so it behaves like that +/// list for every outer operation, including the versioned snapshot and stream that views use to start without missing a change. +/// Disposing it also disposes every row it holds at that moment. Views read from this list. +/// +[DebuggerDisplay("Rows = {Count}")] +public sealed class Reactive2DList : IReactiveList>, IReactiveSourceWithOptions, IVersionedSnapshotSource> where T : notnull { + /// The outer list of rows. + private readonly ReactiveList> _rows; + + /// Guards the attachment of the event forwarders. + private readonly Lock _gate = new(); + + /// The handlers of ; guarded by for writes. + private NotifyCollectionChangedEventHandler? _collectionChanged; + + /// The handlers of ; guarded by for writes. + private PropertyChangedEventHandler? _propertyChanged; + + /// Non-zero once the list has been disposed. + private int _disposed; + /// Initializes a new instance of the class. - public Reactive2DList() - { - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Reactive2DList() => _rows = []; /// Initializes a new instance of the class with the specified collection of item sequences. /// A collection of sequences, where each inner sequence represents the items for a row in the two-dimensional list. /// Thrown if items is null. - public Reactive2DList(IEnumerable> items) - : base(CreateRows(items)) - { - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Reactive2DList(IEnumerable> items) => _rows = new(CreateRows(items)); /// Initializes a new instance of the class with the specified collection of items. /// The collection of instances to include in the two-dimensional list. Cannot be null. - public Reactive2DList(IEnumerable> items) - : base(items) - { - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Reactive2DList(IEnumerable> items) => _rows = new(items); /// Initializes a new instance of the class with the specified collection of items. /// The collection of items to initialize the list with. Each item will be wrapped in a . /// Thrown if items is null. - public Reactive2DList(IEnumerable items) - : base(CreateSingleItemRows(items)) - { - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Reactive2DList(IEnumerable items) => _rows = new(CreateSingleItemRows(items)); /// Initializes a new instance of the class containing a single row initialized with the specified reactive list. /// The reactive list to use as the initial row of the two-dimensional list. Cannot be null. /// Thrown if is null. - public Reactive2DList(ReactiveList item) - : base([item ?? throw new ArgumentNullException(nameof(item))]) - { - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Reactive2DList(ReactiveList item) => _rows = new([item ?? throw new ArgumentNullException(nameof(item))]); /// Initializes a new instance of the class containing a single item. /// The item to include as the initial element in the list. - public Reactive2DList(T item) - : base(CreateSingleRow(item)) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Reactive2DList(T item) => _rows = new(CreateSingleRow(item)); + + /// + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add + { + lock (_gate) + { + var first = _collectionChanged is null; + _collectionChanged += value; + if (first && _collectionChanged is not null) + { + _rows.CollectionChanged += ForwardCollectionChanged; + } + } + } + + remove + { + lock (_gate) + { + _collectionChanged -= value; + if (_collectionChanged is null) + { + _rows.CollectionChanged -= ForwardCollectionChanged; + } + } + } + } + + /// + public event PropertyChangedEventHandler? PropertyChanged { + add + { + lock (_gate) + { + var first = _propertyChanged is null; + _propertyChanged += value; + if (first && _propertyChanged is not null) + { + _rows.PropertyChanged += ForwardPropertyChanged; + } + } + } + + remove + { + lock (_gate) + { + _propertyChanged -= value; + if (_propertyChanged is null) + { + _rows.PropertyChanged -= ForwardPropertyChanged; + } + } + } } + /// + public IObservable>> Added => _rows.Added; + + /// + public IObservable>> Changed => _rows.Changed; + + /// + public int Count => _rows.Count; + + /// + public IObservable>> CurrentItems => _rows.CurrentItems; + + /// + public bool IsDisposed => _rows.IsDisposed; + + /// + public bool IsFixedSize => _rows.IsFixedSize; + + /// + public bool IsReadOnly => _rows.IsReadOnly; + + /// + public bool IsSynchronized => _rows.IsSynchronized; + + /// + public ReactiveSourceOptions Options { get; init; } = ReactiveSourceOptions.Default; + + /// + public ReadOnlyObservableCollection> Items => _rows.Items; + + /// + public ReadOnlyObservableCollection> ItemsAdded => _rows.ItemsAdded; + + /// + public ReadOnlyObservableCollection> ItemsChanged => _rows.ItemsChanged; + + /// + public ReadOnlyObservableCollection> ItemsRemoved => _rows.ItemsRemoved; + + /// + public IObservable>> Removed => _rows.Removed; + + /// + public IObservable>> Stream => _rows.Stream; + + /// + public object SyncRoot => _rows.SyncRoot; + + /// + public long Version => _rows.Version; + + /// + public IObservable>> VersionedStream => _rows.VersionedStream; + + /// + object? IList.this[int index] + { + get => ((IList)_rows)[index]; + set => ((IList)_rows)[index] = value; + } + + /// + public ReactiveList this[int index] + { + get => _rows[index]; + set => _rows[index] = value; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList item) => _rows.Add(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Add(object? value) => _rows.Add(value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddRange(IEnumerable> items) => _rows.AddRange(items); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddRange(ReadOnlySpan> items) => _rows.AddRange(items); + /// Adds a collection of sequences to the current collection, appending each inner sequence as a separate item. /// A collection of sequences to add. Each inner sequence is added as a single item. Cannot be null. /// Thrown if is null. public void AddRange(IEnumerable> items) { - ThrowHelper.ThrowIfNull(items); + ArgumentExceptionHelper.ThrowIfNull(items); - base.AddRange(CreateRows(items)); + _rows.AddRange(CreateRows(items)); } /// Adds the elements of the specified collection to the current collection. @@ -78,9 +227,9 @@ public void AddRange(IEnumerable> items) /// Thrown if is null. public void AddRange(IEnumerable items) { - ThrowHelper.ThrowIfNull(items); + ArgumentExceptionHelper.ThrowIfNull(items); - base.AddRange(CreateSingleItemRows(items)); + _rows.AddRange(CreateSingleItemRows(items)); } /// Adds the specified items to the inner collection at the given outer index. @@ -92,14 +241,9 @@ public void AddRange(IEnumerable items) /// collections. public void AddToInner(int outerIndex, IEnumerable items) { - ThrowHelper.ThrowIfNull(items); + ArgumentExceptionHelper.ThrowIfNull(items); - if (outerIndex < 0 || outerIndex >= Count) - { - throw new ArgumentOutOfRangeException(nameof(outerIndex)); - } - - this[outerIndex].AddRange(items); + GetRow(outerIndex).AddRange(items); } /// Adds the specified item to the inner collection at the given outer index. @@ -109,15 +253,28 @@ public void AddToInner(int outerIndex, IEnumerable items) /// Thrown when is less than 0 or greater than or equal to the number of outer /// collections. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void AddToInner(int outerIndex, T item) - { - if (outerIndex < 0 || outerIndex >= Count) - { - throw new ArgumentOutOfRangeException(nameof(outerIndex)); - } + public void AddToInner(int outerIndex, T item) => GetRow(outerIndex).Add(item); - this[outerIndex].Add(item); - } + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyMemory> AsMemory() => _rows.AsMemory(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan> AsSpan() => _rows.AsSpan(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() => _rows.Clear(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() => _rows.ClearWithoutDeallocation(); + + /// + /// Whether to notify observers. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) => _rows.ClearWithoutDeallocation(notifyChange); /// Removes all elements from the inner collection at the specified outer index. /// The zero-based index of the outer collection whose inner collection will be cleared. Must be greater than or @@ -125,28 +282,86 @@ public void AddToInner(int outerIndex, T item) /// Thrown when outerIndex is less than 0 or greater than or equal to Count. public void ClearInner(int outerIndex) { - if (outerIndex < 0 || outerIndex >= Count) + var row = GetRow(outerIndex); + row.Clear(); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList item) => _rows.Contains(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) => _rows.Contains(value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void CopyTo(Span> destination) => _rows.CopyTo(destination); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList[] array, int arrayIndex) => _rows.CopyTo(array, arrayIndex); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void CopyTo(Array array, int index) => _rows.CopyTo(array, index); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReactiveList[] CopyVersioned(out long version) => _rows.CopyVersioned(out version); + + /// Defers notifications about changes to the rows, not changes inside each row. + /// The token that releases this deferral. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public NotificationDeferral DeferNotifications() => _rows.DeferNotifications(); + + /// Disposes every row and then the outer list; calling it more than once, or from several threads, is safe. + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) { - throw new ArgumentOutOfRangeException(nameof(outerIndex)); + return; + } + + // Rows are disposed before the outer list; disposing a row twice is harmless. + foreach (var innerList in _rows.ToArray()) + { + innerList.Dispose(); } - this[outerIndex].Clear(); + _rows.Dispose(); } + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Edit(Action>> editAction) => _rows.Edit(editAction); + /// Returns a flattened sequence containing all items from each inner collection in the order they appear. /// An that enumerates all items from the inner collections. The sequence is empty if /// there are no items. public IEnumerable Flatten() { - foreach (var innerList in Items) + // The row snapshot is shared and immutable, so reading it needs no copy and no lock. + var rows = _rows.AsSpan(); + var total = 0; + for (var i = 0; i < rows.Length; i++) { - foreach (var item in innerList.Items) - { - yield return item; - } + total += rows[i].Count; } + + var result = new List(total); + for (var i = 0; i < rows.Length; i++) + { + ListCompat.AddRange(result, rows[i].AsSpan()); + } + + return result; } + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator> GetEnumerator() => _rows.GetEnumerator(); + /// Retrieves the element at the specified inner index within the list located at the specified outer index. /// The zero-based index of the outer list from which to retrieve the inner list. Must be greater than or equal to 0 /// and less than the total number of outer lists. @@ -159,54 +374,93 @@ public IEnumerable Flatten() [MethodImpl(MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { - if (outerIndex < 0 || outerIndex >= Count) + var innerList = GetRow(outerIndex); + try { - throw new ArgumentOutOfRangeException(nameof(outerIndex)); + return innerList[innerIndex]; } - - var innerList = this[outerIndex]; - if (innerIndex < 0 || innerIndex >= innerList.Count) + catch (ArgumentOutOfRangeException) { throw new ArgumentOutOfRangeException(nameof(innerIndex)); } - - return innerList[innerIndex]; } + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList item) => _rows.IndexOf(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) => _rows.IndexOf(value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList item) => _rows.Insert(index, item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) => _rows.Insert(index, value); + /// Inserts an item into the collection at the specified index. /// The zero-based index at which the item should be inserted. /// The item to insert into the collection. Cannot be null. /// Thrown if is null. public void Insert(int index, T item) { - ThrowHelper.ThrowIfNull(item); + ArgumentExceptionHelper.ThrowIfNull(item); - base.Insert(index, [with(item)]); + ReactiveList row = new(item); + _rows.Insert(index, row); } /// Inserts the specified collection of items into the inner list at the given position within the outer list. - /// The zero-based index in the outer list at which to insert the items. + /// The zero-based index in the outer list of the row to insert into. /// The collection of items to insert. Cannot be null. /// The zero-based index in the inner list at which to begin inserting the items. /// Thrown if is null. - public void Insert(int index, IEnumerable items, int innerIndex) + public void Insert(int outerIndex, IEnumerable items, int innerIndex) { - ThrowHelper.ThrowIfNull(items); + ArgumentExceptionHelper.ThrowIfNull(items); - this[index].InsertRange(innerIndex, items); + GetRow(outerIndex).InsertRange(innerIndex, items); } + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, IEnumerable> items) => _rows.InsertRange(index, items); + /// Inserts the elements of a collection into the list at the specified index as a new row. /// The zero-based index at which the new row should be inserted. /// The collection of elements to insert as a row. Cannot be null. /// Thrown if is null. public void InsertRange(int index, IEnumerable items) { - ThrowHelper.ThrowIfNull(items); + ArgumentExceptionHelper.ThrowIfNull(items); - base.Insert(index, [.. items]); + ReactiveList row = new(items); + _rows.Insert(index, row); } + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) => _rows.Move(oldIndex, newIndex); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList item) => _rows.Remove(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Remove(IEnumerable> items) => _rows.Remove(items); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) => _rows.Remove(value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) => _rows.RemoveAt(index); + /// Removes the element at the specified index from the inner collection at the given outer index. /// The zero-based index of the outer collection containing the inner collection from which to remove the element. /// Must be greater than or equal to 0 and less than the total number of outer collections. @@ -215,14 +469,22 @@ public void InsertRange(int index, IEnumerable items) /// collections. public void RemoveFromInner(int outerIndex, int innerIndex) { - if (outerIndex < 0 || outerIndex >= Count) - { - throw new ArgumentOutOfRangeException(nameof(outerIndex)); - } - - this[outerIndex].RemoveAt(innerIndex); + var row = GetRow(outerIndex); + row.RemoveAt(innerIndex); } + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int RemoveMany(Func, bool> predicate) => _rows.RemoveMany(predicate); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) => _rows.RemoveRange(index, count); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(IEnumerable> items) => _rows.ReplaceAll(items); + /// Sets the element at the specified inner index within the inner list at the given outer index. /// The zero-based index of the outer list that contains the inner list to modify. Must be greater than or equal to /// 0 and less than the total number of outer lists. @@ -234,47 +496,46 @@ public void RemoveFromInner(int outerIndex, int innerIndex) /// specified inner list. public void SetItem(int outerIndex, int innerIndex, T value) { - if (outerIndex < 0 || outerIndex >= Count) + var innerList = GetRow(outerIndex); + try { - throw new ArgumentOutOfRangeException(nameof(outerIndex)); + innerList[innerIndex] = value; } - - var innerList = this[outerIndex]; - if (innerIndex < 0 || innerIndex >= innerList.Count) + catch (ArgumentOutOfRangeException) { throw new ArgumentOutOfRangeException(nameof(innerIndex)); } - - innerList[innerIndex] = value; } + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IDisposable Subscribe(IObserver>> observer) => _rows.Subscribe(observer); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReactiveList[] ToArray() => _rows.ToArray(); + /// Calculates the total number of items contained in all inner lists. /// The sum of the counts of all inner lists. Returns 0 if there are no items. public int TotalCount() { + var rows = _rows.AsSpan(); var count = 0; - for (var i = 0; i < Items.Count; i++) + for (var i = 0; i < rows.Length; i++) { - count += Items[i].Count; + count += rows[i].Count; } return count; } /// - protected override void Dispose(bool disposing) - { - if (disposing) - { - // Dispose all inner lists before disposing base - foreach (var innerList in Items) - { - innerList.Dispose(); - } - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList item, ReactiveList newValue) => _rows.Update(item, newValue); - base.Dispose(disposing); - } + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// Creates a single-row array containing the specified item. /// The item to include in the initial row. @@ -305,32 +566,12 @@ private static ReactiveList[] MaterializeRows( IEnumerable items, Func> rowFactory) { - ThrowHelper.ThrowIfNull(items); - - if (items is ICollection collection) - { - var rows = new ReactiveList[collection.Count]; - var index = 0; - try - { - foreach (var item in collection) - { - rows[index] = rowFactory(item); - index++; - } - - return rows; - } - catch - { - DisposeCreatedRows(rows, index); - throw; - } - } + ArgumentExceptionHelper.ThrowIfNull(items); - var result = items is IReadOnlyCollection readOnlyCollection - ? new List>(readOnlyCollection.Count) + var result = items is ICollection collection + ? new List>(collection.Count) : []; + var completed = false; try { foreach (var item in items) @@ -338,27 +579,53 @@ private static ReactiveList[] MaterializeRows( result.Add(rowFactory(item)); } + completed = true; return result.ToArray(); } - catch + finally { - for (var i = 0; i < result.Count; i++) + if (!completed) { - result[i].Dispose(); + DisposeCreatedRows(result); } - - throw; } } - /// Disposes the first rows in an array after an initialization failure. - /// The partially populated row array. - /// The number of initialized rows. - private static void DisposeCreatedRows(ReactiveList[] rows, int count) + /// Disposes the rows created before an initialization failure. + /// The rows created so far. + private static void DisposeCreatedRows(List> rows) { - for (var i = 0; i < count; i++) + for (var i = 0; i < rows.Count; i++) { rows[i].Dispose(); } } + + /// Gets the row at an index, reporting the outer index when it is out of range. + /// The row index. + /// The row. + /// Thrown when is outside the list. + private ReactiveList GetRow(int outerIndex) + { + try + { + return _rows[outerIndex]; + } + catch (ArgumentOutOfRangeException) + { + throw new ArgumentOutOfRangeException(nameof(outerIndex)); + } + } + + /// Raises with this list as the sender. + /// The outer list that raised the event. + /// The event arguments. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ForwardCollectionChanged(object? sender, NotifyCollectionChangedEventArgs args) => Volatile.Read(ref _collectionChanged)?.Invoke(this, args); + + /// Raises with this list as the sender. + /// The outer list that raised the event. + /// The event arguments. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ForwardPropertyChanged(object? sender, PropertyChangedEventArgs args) => Volatile.Read(ref _propertyChanged)?.Invoke(this, args); } diff --git a/src/ReactiveList/Collections/ReactiveList.Deferrals.cs b/src/ReactiveList/Collections/ReactiveList.Deferrals.cs new file mode 100644 index 00000000..d12810d9 --- /dev/null +++ b/src/ReactiveList/Collections/ReactiveList.Deferrals.cs @@ -0,0 +1,112 @@ +// 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.Collections; +#else +namespace ReactiveList.Collections; +#endif + +/// Collection-wide notification deferral. +public partial class ReactiveList +{ + /// The number of active deferrals, guarded by the mutation lock. + [NonSerialized] + private int _deferralDepth; + + /// The state against which deferred changes are compared. + [NonSerialized] + private DeferredListSnapshot _deferralStart; + + /// Defers change notifications until the last active deferral is disposed. + /// The token that releases this deferral. + /// The list is disposed. + /// Writes are immediately visible to readers. If the list changed, it publishes one reset when notifications resume. + /// Open and release deferrals outside callbacks that run under the list lock. + public NotificationDeferral DeferNotifications() + { + var release = new NotificationDeferralState(ResumeNotifications); + lock (SynchronizationLock) + { + EnterMutation(); + if (_deferralDepth == 0) + { + _deferralStart = new(SnapshotLocked(), _version); + } + + _deferralDepth++; + } + + return new(release); + } + + /// Releases one token and dispatches the coalesced change outside the mutation lock. + /// The token's shared state. + private void ResumeNotifications(NotificationDeferralState release) + { + ListChange change; + bool owner; + Exception? failure; + lock (SynchronizationLock) + { + if (_inCallback) + { + throw MutationRejection(); + } + + if (!release.TryRelease() || IsDisposed) + { + return; + } + + _deferralDepth--; + if (_deferralDepth != 0) + { + return; + } + + var start = _deferralStart; + _deferralStart = default; + if (start.Version == _version) + { + return; + } + + change = CreateDeferredChange(start.Items, out failure); + owner = Publish(in change); + } + + if (owner) + { + Drain(in change); + } + + RethrowIfFailed(failure); + } + + /// Creates one reset and computes the added and removed history for the scope. + /// The contents before the first deferral began. + /// Receives the exception thrown by item equality while the history was worked out, or . + /// The change to dispatch; its added and removed history is empty when the calculation failed. + private ListChange CreateDeferredChange(T[] before, out Exception? failure) + { + _ = TryComputeDifference(before, out var added, out var removed, out failure); + + return new( + ListChangeKind.Deferred, + Touch(), + default, + default, + added, + removed, + -1, + -1, + NeedsContentsSnapshot() ? SnapshotLocked() : null); + } + + /// The contents and version when the first deferral began. + /// The initial contents. + /// The initial version. + private readonly record struct DeferredListSnapshot(T[] Items, long Version); +} diff --git a/src/ReactiveList/Collections/ReactiveList.Notifications.cs b/src/ReactiveList/Collections/ReactiveList.Notifications.cs new file mode 100644 index 00000000..2bb0abbd --- /dev/null +++ b/src/ReactiveList/Collections/ReactiveList.Notifications.cs @@ -0,0 +1,607 @@ +// 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.Collections; +#else +namespace ReactiveList.Collections; +#endif + +/// Commit, queueing and delivery of change notifications. +public partial class ReactiveList +{ + /// The property name used for indexed item notifications. + private const string ItemArray = "Item[]"; + + /// The number of locked indexer reads without a mutation after which a snapshot is built for lock-free reads. + private const int SnapshotAfterReads = 3; + + /// The cached property-change arguments for count updates. + private static readonly PropertyChangedEventArgs CountPropertyChangedEventArgs = new(nameof(Count)); + + /// The cached property-change arguments for indexed item updates. + private static readonly PropertyChangedEventArgs ItemArrayPropertyChangedEventArgs = new(ItemArray); + + /// The cached collection-reset event arguments. + private static readonly NotifyCollectionChangedEventArgs ResetCollectionChangedEventArgs = new(NotifyCollectionChangedAction.Reset); + + /// The synchronization primitive recreated lazily after deserialization. + [NonSerialized] + private Lock? _lock = new(); + + /// The changes committed while another thread was delivering; guarded by the list lock. + [NonSerialized] + private Queue>? _pending; + + /// The immutable copy of the contents shared by enumeration and spans until the next mutation; guarded by the list lock. + [NonSerialized] + private T[]? _snapshot; + + /// The number of locked indexer reads since the last mutation; guarded by the list lock. + [NonSerialized] + private int _readsSinceMutation; + + /// The last change that replaced the added and removed history; guarded by the list lock. + [NonSerialized] + private ListHistory _historyAddedRemoved; + + /// The last change that replaced the changed history; guarded by the list lock. + [NonSerialized] + private ListHistory _historyChanged; + + /// The monotonically increasing collection version. + [NonSerialized] + private long _version; + + /// The item count, readable without the lock. + [NonSerialized] + private int _count; + + /// Non-zero once the list has been disposed. + [NonSerialized] + private int _disposed; + + /// + /// The delivery state: is set while a thread delivers, and every change queued behind it adds + /// . Publishers change it under the list lock; the delivering thread releases ownership without the lock. + /// + [NonSerialized] + private int _drainState; + + /// Whether a user callback is running under the list lock; guarded by the list lock. + [NonSerialized] + private bool _inCallback; + + /// Gets the stable synchronization primitive, creating it once when deserialization left it unset. + private Lock SynchronizationLock => _lock ?? LazyInitializer.EnsureInitialized(ref _lock)!; + + /// Handles post-deserialization processing to restore the state that is not serialized. + /// The streaming context for the deserialization operation. + [OnDeserialized] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void OnDeserialized(StreamingContext context) => InitializeRuntimeState(); + + /// Creates the collection-changed arguments for a change. + /// The change. + /// The arguments, or when the change is not announced through this event. + private static NotifyCollectionChangedEventArgs? CreateCollectionChangedArgs(in ListChange change) => change.Kind switch + { + ListChangeKind.Added => new(NotifyCollectionChangedAction.Add, change.Item, change.Index), + ListChangeKind.Removed => new(NotifyCollectionChangedAction.Remove, change.Item, change.Index), + ListChangeKind.Updated => new(NotifyCollectionChangedAction.Replace, change.Item, change.Previous, change.Index), + ListChangeKind.Moved => new(NotifyCollectionChangedAction.Move, change.Item, change.Index, change.PreviousIndex), + ListChangeKind.AddedRange or ListChangeKind.RemovedRange or ListChangeKind.Cleared or ListChangeKind.Edited or ListChangeKind.Deferred => ResetCollectionChangedEventArgs, + ListChangeKind.Replaced when change.Added!.Length > 0 || change.Removed!.Length > 0 => ResetCollectionChangedEventArgs, + _ => null + }; + + /// Completes and disposes a stream signal that may already have been completed by a subscriber that raced disposal. + /// The notification type. + /// The signal, if it was created. + /// Receives the first observer exception. + private static void CompleteAndDispose(Signal? signal, ref Exception? failure) + { + if (signal is null) + { + return; + } + + try + { + signal.OnCompleted(); + } + catch (ObjectDisposedException) + { + // A subscriber that arrived while disposal began created this signal after the disposed flag was set, and completed and disposed it already. + } + catch (Exception ex) + { + failure ??= ex; + } + finally + { + signal.Dispose(); + } + } + + /// Initializes fields that are not serialized during deserialization or object construction. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void InitializeRuntimeState() => Volatile.Write(ref _count, _internalList.Count); + + /// Rejects mutations of a disposed list and mutations from inside a lock-held callback. + private void EnterMutation() + { + if (Volatile.Read(ref _disposed) == 0 && !_inCallback) + { + return; + } + + throw MutationRejection(); + } + + /// Creates the exception for a mutation that is not allowed right now. + /// An when disposed; otherwise an for a call from a lock-held callback. + [MethodImpl(MethodImplOptions.NoInlining)] + private Exception MutationRejection() => + Volatile.Read(ref _disposed) != 0 + ? new ObjectDisposedException(GetType().FullName) + : new InvalidOperationException("The list cannot be modified from inside its own Edit action or RemoveMany predicate."); + + /// Gets the shared immutable copy of the contents, creating it when a mutation invalidated it. + /// The snapshot; callers must not modify it. + private T[] SnapshotLocked() + { + var snapshot = _snapshot; + if (snapshot is not null) + { + return snapshot; + } + + snapshot = _internalList.Count == 0 ? [] : _internalList.ToArray(); + Volatile.Write(ref _snapshot, snapshot); + return snapshot; + } + + /// Publishes the new count and version after a mutation. + /// The new version. + private long Touch() + { + Volatile.Write(ref _snapshot, null); + _readsSinceMutation = 0; + Volatile.Write(ref _count, _internalList.Count); + var version = _version + 1; + Volatile.Write(ref _version, version); + return version; + } + + /// Gets the contents after a change when an items mirror needs them to apply a reset. + /// The snapshot, or when there is no mirror. + private T[]? MirrorSnapshot() => _deferralDepth != 0 || Volatile.Read(ref _itemsMirror) is null ? null : SnapshotLocked(); + + /// Describes an added item. + /// The item. + /// The index. + /// The change. + private ListChange CreateAdded(T item, int index) => new(ListChangeKind.Added, Touch(), item, default, null, null, index, -1, null); + + /// Describes added items. + /// The items, which the list owns. + /// The index of the first item. + /// The change. + private ListChange CreateAddedRange(T[] items, int index) => new(ListChangeKind.AddedRange, Touch(), default, default, items, null, index, -1, null); + + /// Describes a removed item. + /// The item. + /// The index it had. + /// The change. + private ListChange CreateRemoved(T item, int index) => new(ListChangeKind.Removed, Touch(), item, default, null, null, index, -1, null); + + /// Describes removed items. + /// The items, which the list owns. + /// The index of the first item, or -1 when they were not contiguous. + /// The change. + private ListChange CreateRemovedRange(T[] items, int index) => + new(ListChangeKind.RemovedRange, Touch(), default, default, null, items, index, -1, index < 0 ? MirrorSnapshot() : null); + + /// Describes a clear. + /// The items that were removed. + /// The change. + private ListChange CreateCleared(T[] removed) => new(ListChangeKind.Cleared, Touch(), default, default, null, removed, -1, -1, null); + + /// Describes a clear that does not notify observers. + /// The change. + private ListChange CreateClearedSilent() => new(ListChangeKind.ClearedSilent, Touch(), default, default, null, null, -1, -1, null); + + /// Describes clearing an empty list. + /// The change. + private ListChange CreateHistoryReset() => new(ListChangeKind.HistoryReset, Touch(), default, default, null, null, -1, -1, null); + + /// Describes a replaced item. + /// The new item. + /// The old item. + /// The index. + /// The change. + private ListChange CreateUpdated(T item, T previous, int index) => new(ListChangeKind.Updated, Touch(), item, previous, null, null, index, index, null); + + /// Describes a moved item. + /// The item. + /// The new index. + /// The old index. + /// The change. + private ListChange CreateMoved(T item, int newIndex, int oldIndex) => new(ListChangeKind.Moved, Touch(), item, default, null, null, newIndex, oldIndex, null); + + /// Describes replacing all contents. + /// The new items, which the list owns. + /// The old items. + /// The change. + private ListChange CreateReplaced(T[] added, T[] removed) + { + var sequence = Touch(); + + // The list now holds exactly the array it owns, so that array is also the shared snapshot and no second copy is needed. + Volatile.Write(ref _snapshot, added); + return new(ListChangeKind.Replaced, sequence, default, default, added, removed, -1, -1, MirrorSnapshot()); + } + + /// Describes the net effect of an edit. + /// The contents before the edit. + /// The added items. + /// The removed items. + /// The change. + private ListChange CreateEdited(T[] before, T[] added, T[] removed) + { + var sequence = Touch(); + var wanted = NeedsContentsSnapshot(); + return new(ListChangeKind.Edited, sequence, default, default, added, removed, -1, -1, wanted ? SnapshotLocked() : null) { Before = wanted ? before : null }; + } + + /// Tests whether a mirror or stream observer needs the whole contents of an edit; call with the list lock held. + /// when the contents must be captured. + private bool NeedsContentsSnapshot() => _deferralDepth == 0 + && (Volatile.Read(ref _itemsMirror) is not null || Volatile.Read(ref _streamPipeline)?.HasObservers == true); + + /// Records a committed change and decides who delivers it; call with the list lock held. + /// The change. + /// when the caller must now call with . + private bool Publish(in ListChange change) + { + if (_deferralDepth != 0) + { + return false; + } + + if (change.AffectsAddedAndRemoved) + { + _historyAddedRemoved.Record(in change); + } + + if (change.AffectsChanged) + { + _historyChanged.Record(in change); + } + + if (HasConsumers()) + { + return BeginDrainOrQueue(in change); + } + + if (Volatile.Read(ref _currentItems) is not null) + { + Volatile.Write(ref _currentStale, true); + } + + return false; + } + + /// Makes the caller the delivering thread, or queues the change for the thread that already is; call with the list lock held. + /// The change. + /// when the caller became the delivering thread. + private bool BeginDrainOrQueue(in ListChange change) + { + var state = Volatile.Read(ref _drainState); + if (state == 0) + { + // Only a publisher moves the state away from zero and publishers hold the list lock, so no other thread can change it here. + Volatile.Write(ref _drainState, DrainState.DrainingBit); + return true; + } + + return DrainState.QueueBehind(ref _drainState, ref _pending, in change, state); + } + + /// Releases delivery ownership when nothing is queued, otherwise takes the next queued change. + /// Receives the next change to deliver. + /// when the caller must deliver ; when ownership was released. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool TryTakeNext(out ListChange next) + { + // The state is exactly the draining bit only while nothing is queued, so this releases ownership without taking the lock. + if (Interlocked.CompareExchange(ref _drainState, 0, DrainState.DrainingBit) == DrainState.DrainingBit) + { + next = default; + return false; + } + + return DrainState.TakeNext(ref _drainState, ref _pending, SynchronizationLock, out next); + } + + /// Discards the changes queued behind the delivering thread; call with the list lock held. + private void DiscardQueued() + { + if (_pending is not { Count: > 0 } pending) + { + return; + } + + _ = Interlocked.Add(ref _drainState, -(pending.Count * DrainState.QueuedStep)); + pending.Clear(); + } + + /// Tests whether anything would observe a change; call with the list lock held. + /// when a change must be delivered. + private bool HasConsumers() => + CollectionChanged is not null + || PropertyChanged is not null + || HasMirrors() + || Volatile.Read(ref _streamPipeline)?.HasObservers == true + || Volatile.Read(ref _versionedPipeline)?.HasObservers == true + || Volatile.Read(ref _currentItems)?.HasObservers == true; + + /// Tests whether any mirror collection was created. + /// when a mirror exists. + private bool HasMirrors() => + Volatile.Read(ref _itemsMirror) is not null + || Volatile.Read(ref _addedMirror) is not null + || Volatile.Read(ref _removedMirror) is not null + || Volatile.Read(ref _changedMirror) is not null; + + /// Delivers a change and then every change queued behind it, outside the list lock. + /// The change the caller owns. + /// Rethrows the first exception thrown by an observer after all changes were delivered. + private void Drain(in ListChange first) + { + Exception? failure = null; + var change = first; + while (true) + { + Dispatch(in change, ref failure); + if (!TryTakeNext(out change)) + { + break; + } + } + + if (failure is not null) + { + ExceptionDispatchInfo.Capture(failure).Throw(); + } + } + + /// Delivers one change to every kind of observer, continuing past observer failures. + /// The change. + /// Receives the first observer exception. + private void Dispatch(in ListChange change, ref Exception? failure) + { + if (change.Kind == ListChangeKind.Complete) + { + CompleteObservables(ref failure); + return; + } + + if (change.Kind == ListChangeKind.Refresh) + { + if (!IsDisposed) + { + EmitCurrentItems(in change, ref failure); + } + + return; + } + + // Once the list is disposed the remaining stages of an in-flight change are skipped, so nothing starts after Dispose returned. + TryApplyMirrors(in change, ref failure); + if (IsDisposed) + { + return; + } + + EmitCurrentItems(in change, ref failure); + if (IsDisposed) + { + return; + } + + TryRaiseCollectionChanged(in change, ref failure); + if (IsDisposed) + { + return; + } + + TryEmitStream(in change, ref failure); + if (!IsDisposed) + { + TryRaisePropertyChanged(change.Kind, ref failure); + } + } + + /// Applies a change to the mirror collections, recording an exception from their handlers. + /// The change. + /// Receives the first observer exception. + private void TryApplyMirrors(in ListChange change, ref Exception? failure) + { + try + { + ApplyMirrors(in change); + } + catch (Exception ex) + { + failure ??= ex; + } + } + + /// Raises , recording an exception from its handlers. + /// The change. + /// Receives the first observer exception. + private void TryRaiseCollectionChanged(in ListChange change, ref Exception? failure) + { + try + { + RaiseCollectionChanged(in change); + } + catch (Exception ex) + { + failure ??= ex; + } + } + + /// Emits to , recording an exception from its observers. + /// The change. + /// Receives the first observer exception. + private void TryEmitStream(in ListChange change, ref Exception? failure) + { + try + { + EmitStream(in change); + } + catch (Exception ex) + { + failure ??= ex; + } + + if (!IsDisposed) + { + try + { + EmitVersionedStream(in change); + } + catch (Exception ex) + { + failure ??= ex; + } + } + } + + /// Raises , recording an exception from its handlers. + /// The kind of change. + /// Receives the first observer exception. + private void TryRaisePropertyChanged(ListChangeKind kind, ref Exception? failure) + { + try + { + RaisePropertyChanged(kind); + } + catch (Exception ex) + { + failure ??= ex; + } + } + + /// Pushes a snapshot to the current-items observable, or marks it stale when nobody listens. + /// The change. + /// Receives the first observer exception. + private void EmitCurrentItems(in ListChange change, ref Exception? failure) + { + var current = Volatile.Read(ref _currentItems); + if (current is null || change.Kind is ListChangeKind.HistoryReset or ListChangeKind.ClearedSilent) + { + return; + } + + if (!current.HasObservers) + { + // Mark the snapshot stale first and look for observers again afterwards. A subscriber that attaches after the first check + // either appears in the second one and receives this change, or attaches after the mark and sees it when it checks for staleness. + Volatile.Write(ref _currentStale, true); + Thread.MemoryBarrier(); + if (!current.HasObservers) + { + return; + } + } + + try + { + current.OnNext(change.Snapshot ?? SnapshotNow()); + } + catch (Exception ex) + { + failure ??= ex; + } + } + + /// Gets the shared snapshot of the contents now. + /// The snapshot. + private T[] SnapshotNow() + { + lock (SynchronizationLock) + { + return SnapshotLocked(); + } + } + + /// Completes and releases the observable streams after the last queued change. + /// Receives the first observer exception. + private void CompleteObservables(ref Exception? failure) + { + var current = Volatile.Read(ref _currentItems); + if (current is not null) + { + try + { + current.OnCompleted(); + } + catch (Exception ex) + { + failure ??= ex; + } + finally + { + current.Dispose(); + } + } + + CompleteAndDispose(Volatile.Read(ref _streamPipeline), ref failure); + CompleteAndDispose(Volatile.Read(ref _versionedPipeline), ref failure); + } + + /// Raises for a change. + /// The change. + private void RaiseCollectionChanged(in ListChange change) + { + var handler = CollectionChanged; + if (handler is null) + { + return; + } + + var args = CreateCollectionChangedArgs(in change); + if (args is not null) + { + handler(this, args); + } + } + + /// Raises the property-changed notifications for a change. + /// The kind of change. + private void RaisePropertyChanged(ListChangeKind kind) + { + if (kind is ListChangeKind.ClearedSilent or ListChangeKind.None) + { + return; + } + + var handler = PropertyChanged; + if (handler is null) + { + return; + } + + if (kind is not (ListChangeKind.Updated or ListChangeKind.Moved)) + { + handler(this, CountPropertyChangedEventArgs); + } + + handler(this, ItemArrayPropertyChangedEventArgs); + } +} diff --git a/src/ReactiveList/Collections/ReactiveList.Observables.cs b/src/ReactiveList/Collections/ReactiveList.Observables.cs new file mode 100644 index 00000000..014f8d34 --- /dev/null +++ b/src/ReactiveList/Collections/ReactiveList.Observables.cs @@ -0,0 +1,714 @@ +// 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.Collections; +#else +namespace ReactiveList.Collections; +#endif + +/// The observable views of the list, which are created on first use. +public partial class ReactiveList +{ + /// The lazily created stream of added items. + [NonSerialized] + private IObservable>? _addedObservable; + + /// The lazily created stream of changed items. + [NonSerialized] + private IObservable>? _changedObservable; + + /// The lazily created stream of removed items. + [NonSerialized] + private IObservable>? _removedObservable; + + /// The lazily created observable over . + [NonSerialized] + private IObservable>? _currentObservable; + + /// The lazily created signal holding the latest snapshot. + [NonSerialized] + private BehaviorSignal>? _currentItems; + + /// Whether the latest snapshot in may be older than the list. + [NonSerialized] + private bool _currentStale; + + /// The lazily created signal that publishes cache notifications. + [NonSerialized] + private Signal>? _streamPipeline; + + /// The lazily created observable over . + [NonSerialized] + private IObservable>? _streamObservable; + + /// The lazily created signal that publishes each mutation with its committed version. + [NonSerialized] + private Signal>? _versionedPipeline; + + /// The lazily created observable for the versioned signal. + [NonSerialized] + private IObservable>? _versionedObservable; + + /// The lazily created mirror of the contents. + [NonSerialized] + private RangeObservableCollection? _itemsMirror; + + /// The lazily created mirror of the added history. + [NonSerialized] + private RangeObservableCollection? _addedMirror; + + /// The lazily created mirror of the changed history. + [NonSerialized] + private RangeObservableCollection? _changedMirror; + + /// The lazily created mirror of the removed history. + [NonSerialized] + private RangeObservableCollection? _removedMirror; + + /// The public read-only view of the contents. + [NonSerialized] + private ReadOnlyObservableCollection? _items; + + /// The public read-only view of the added history. + [NonSerialized] + private ReadOnlyObservableCollection? _itemsAdded; + + /// The public read-only view of the changed history. + [NonSerialized] + private ReadOnlyObservableCollection? _itemsChanged; + + /// The public read-only view of the removed history. + [NonSerialized] + private ReadOnlyObservableCollection? _itemsRemoved; + + /// Identifies one of the change-history collections. + internal enum HistoryKind + { + /// The items added by the last change. + Added = 0, + + /// The items removed by the last change. + Removed = 1, + + /// The items changed by the last change. + Changed = 2, + } + + /// Gets the added during the last change as an Observable. + /// The added. + public IObservable> Added => Volatile.Read(ref _addedObservable) ?? CreateAdded(); + + /// Gets the changed during the last change as an Observable. + /// The changed. + public IObservable> Changed => Volatile.Read(ref _changedObservable) ?? CreateChanged(); + + /// Gets the current items as an observable that replays the latest snapshot to new subscribers. + /// The current items. + public IObservable> CurrentItems => Volatile.Read(ref _currentObservable) ?? CreateCurrentObservable(); + + /// Gets the removed items during the last change as an Observable. + /// The removed. + public IObservable> Removed => Volatile.Read(ref _removedObservable) ?? CreateRemoved(); + + /// Gets a read-only observable mirror of the items. + /// The items. + /// The mirror is created on first use and is updated from then on, in notification order. + public ReadOnlyObservableCollection Items => Volatile.Read(ref _items) ?? CreateItems(); + + /// Gets the items added during the last change. + /// The items added. + public ReadOnlyObservableCollection ItemsAdded => Volatile.Read(ref _itemsAdded) ?? CreateItemsAdded(); + + /// Gets the items changed during the last change. + /// The items changed. + public ReadOnlyObservableCollection ItemsChanged => Volatile.Read(ref _itemsChanged) ?? CreateItemsChanged(); + + /// Gets the items removed during the last change. + /// The items removed. + public ReadOnlyObservableCollection ItemsRemoved => Volatile.Read(ref _itemsRemoved) ?? CreateItemsRemoved(); + + /// Gets an observable sequence that emits cache change notifications as they occur. + /// + /// This is the primary observable for change notifications. It provides all change information + /// including single item changes and batch operations. Notifications are delivered one at a time, in the order the + /// changes were committed. Batch notifications share an immutable array and need no disposal. Subscribing to a disposed list, to this + /// stream or to any other observable of the list, completes the observer immediately. + /// + public IObservable> Stream => Volatile.Read(ref _streamObservable) ?? CreateStreamObservable(); + + /// + public IObservable> VersionedStream => + Volatile.Read(ref _versionedObservable) ?? CreateVersionedStreamObservable(); + + /// Subscribes the specified observer to the CurrentItems. + /// The observer. + /// An IDisposable to release the subscription. + /// Subscribing to a disposed list completes the observer immediately. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IDisposable Subscribe(IObserver> observer) + { + ArgumentExceptionHelper.ThrowIfNull(observer); + + var subscription = IsDisposed ? null : SignalSubscription.TrySubscribe(EnsureCurrentSignal(), observer, ref _disposed); + if (subscription is null) + { + observer.OnCompleted(); + return Scope.Empty; + } + + RefreshCurrentIfStale(); + return subscription; + } + + /// Extracts items from a cache notification. + /// The cache notification. + /// The items from the notification. + internal static T[] GetItemsFromNotification(CacheNotify notification) + { + var batch = notification.Batch; + if (batch is null) + { + return notification.Item is not null ? [notification.Item] : []; + } + + if (!batch.ReturnToPool && batch.Count == batch.Items.Length) + { + return batch.Items; + } + + var result = new T[batch.Count]; + Array.Copy(batch.Items, result, batch.Count); + return result; + } + + /// Applies a change to the items mirror unless it already reflects the change. + /// The mirror. + /// The change. + internal static void ApplyToItems(RangeObservableCollection mirror, in ListChange change) + { + if (change.Sequence <= mirror.AppliedSequence) + { + return; + } + + mirror.AppliedSequence = change.Sequence; + switch (change.Kind) + { + case ListChangeKind.Added: + { + mirror.Insert(change.Index, change.Item!); + break; + } + + case ListChangeKind.Removed: + { + mirror.RemoveAt(change.Index); + break; + } + + case ListChangeKind.Updated: + { + mirror[change.Index] = change.Item!; + break; + } + + case ListChangeKind.Moved: + { + mirror.Move(change.PreviousIndex, change.Index); + break; + } + + default: + { + ApplyRangeToItems(mirror, in change); + break; + } + } + } + + /// Creates a stream signal, or returns the one another thread installed first. + /// The notification type. + /// The signal field. + /// The signal. + [MethodImpl(MethodImplOptions.NoInlining)] + internal Signal CreateStreamPipeline(ref Signal? pipeline) + { + var created = new Signal(); + var existing = Interlocked.CompareExchange(ref pipeline, created, null); + if (existing is not null) + { + created.Dispose(); + return existing; + } + + if (Volatile.Read(ref _disposed) != 0) + { + // Disposal may have finished completing the other signals before this one existed, or may be about to complete this one too. + Exception? ignored = null; + CompleteAndDispose(created, ref ignored); + } + + return created; + } + + /// Creates a history mirror from the last recorded change. + /// The field that holds the mirror. + /// Which history the mirror shows. + /// The mirror. + internal RangeObservableCollection EnsureHistoryMirror(ref RangeObservableCollection? field, HistoryKind kind) + { + lock (SynchronizationLock) + { + var mirror = Volatile.Read(ref field); + if (mirror is not null) + { + return mirror; + } + + mirror = new() { AppliedSequence = _version }; + var recorded = kind == HistoryKind.Changed ? _historyChanged.ToChange() : _historyAddedRemoved.ToChange(); + mirror.ReplaceAll(HistoryItems(in recorded, kind)); + Volatile.Write(ref field, mirror); + return mirror; + } + } + + /// Creates the current-items signal from a snapshot, or returns the one another thread created first. + /// The signal. + [MethodImpl(MethodImplOptions.NoInlining)] + internal BehaviorSignal> CreateCurrentSignal() + { + lock (SynchronizationLock) + { + var existing = Volatile.Read(ref _currentItems); + if (existing is not null) + { + return existing; + } + + existing = new(SnapshotLocked()); + if (Volatile.Read(ref _disposed) != 0) + { + existing.OnCompleted(); + } + + Volatile.Write(ref _currentStale, false); + Volatile.Write(ref _currentItems, existing); + return existing; + } + } + + /// Queues the fresh snapshot unless another thread already did or the list was disposed. + [MethodImpl(MethodImplOptions.NoInlining)] + internal void QueueStaleRefresh() + { + ListChange change; + bool owner; + lock (SynchronizationLock) + { + if (!_currentStale || IsDisposed) + { + return; + } + + _currentStale = false; + change = new(ListChangeKind.Refresh, _version, default, default, null, null, -1, -1, SnapshotLocked()); + owner = BeginDrainOrQueue(in change); + } + + if (owner) + { + Drain(in change); + } + } + + /// Gets the items a change contributes to the added history. + /// The change. + /// The items. + private static T[] AddedItems(in ListChange change) => change.Kind switch + { + ListChangeKind.Added => [change.Item!], + ListChangeKind.AddedRange or ListChangeKind.Replaced or ListChangeKind.Edited or ListChangeKind.Deferred => change.Added ?? [], + _ => [] + }; + + /// Gets the items a change contributes to the removed history. + /// The change. + /// The items. + private static T[] RemovedItems(in ListChange change) => change.Kind switch + { + ListChangeKind.Removed => [change.Item!], + ListChangeKind.RemovedRange or ListChangeKind.Cleared or ListChangeKind.Replaced or ListChangeKind.Edited or ListChangeKind.Deferred => change.Removed ?? [], + _ => [] + }; + + /// Gets the items a change contributes to the changed history. + /// The change. + /// The items. + private static T[] ChangedItems(in ListChange change) => change.Kind switch + { + ListChangeKind.Added or ListChangeKind.Removed or ListChangeKind.Updated or ListChangeKind.Moved => [change.Item!], + ListChangeKind.Edited or ListChangeKind.Deferred => [.. change.Added ?? [], .. change.Removed ?? []], + _ => RangeChangedItems(in change) + }; + + /// Gets the items a range change contributes to the changed history. + /// The change. + /// The items. + private static T[] RangeChangedItems(in ListChange change) => change.Kind switch + { + ListChangeKind.AddedRange => change.Added ?? [], + ListChangeKind.RemovedRange or ListChangeKind.Cleared or ListChangeKind.Replaced => change.Removed ?? [], + _ => [] + }; + + /// Replaces the contents of a history mirror unless it does not exist or already reflects the change. + /// The mirror, if it was created. + /// The change. + /// Which history the mirror shows. + /// The history items are only gathered once a mirror needs them, so a list without mirrors allocates nothing here. + private static void SetHistory(RangeObservableCollection? mirror, in ListChange change, HistoryKind kind) + { + if (mirror is null || change.Sequence <= mirror.AppliedSequence) + { + return; + } + + mirror.AppliedSequence = change.Sequence; + mirror.ReplaceAll(HistoryItems(in change, kind)); + } + + /// Gets the items a change contributes to a history. + /// The change. + /// Which history is wanted. + /// The items. + private static T[] HistoryItems(in ListChange change, HistoryKind kind) => kind switch + { + HistoryKind.Added => AddedItems(in change), + HistoryKind.Removed => RemovedItems(in change), + _ => ChangedItems(in change) + }; + + /// Applies a range, clear or whole-list change to the items mirror. + /// The mirror. + /// The change. + private static void ApplyRangeToItems(RangeObservableCollection mirror, in ListChange change) + { + switch (change.Kind) + { + case ListChangeKind.AddedRange: + { + mirror.InsertRange(change.Index, change.Added!); + break; + } + + case ListChangeKind.RemovedRange when change.Index >= 0: + { + mirror.RemoveRange(change.Index, change.Removed!.Length); + break; + } + + case ListChangeKind.RemovedRange or ListChangeKind.Replaced or ListChangeKind.Edited or ListChangeKind.Deferred: + { + mirror.ReplaceAll(change.Snapshot!); + break; + } + + case ListChangeKind.Cleared or ListChangeKind.ClearedSilent: + { + mirror.ClearIfNotEmpty(); + break; + } + + default: + { + break; + } + } + } + + /// Creates the notification for a change that can be delivered directly on either stream. + /// The committed change. + /// The notification, or when the change is not represented by a single notification. + private static CacheNotify? CreateStreamNotification(in ListChange change) => change.Kind switch + { + ListChangeKind.Added => new(CacheAction.Added, change.Item, null, change.Index), + ListChangeKind.Removed => new(CacheAction.Removed, change.Item, null, change.Index), + ListChangeKind.Updated => new(CacheAction.Updated, change.Item, null, change.Index, change.Index, change.Previous), + ListChangeKind.Moved => new(CacheAction.Moved, change.Item, null, change.Index, change.PreviousIndex), + ListChangeKind.AddedRange when change.Added is { Length: > 0 } added => + new(CacheAction.BatchAdded, default, new(added, added.Length, ReturnToPool: false), change.Index), + ListChangeKind.RemovedRange when change.Removed is { Length: > 0 } removed => + new(CacheAction.BatchRemoved, default, new(removed, removed.Length, ReturnToPool: false), change.Index), + ListChangeKind.Cleared when change.Removed is { Length: > 0 } cleared => + new(CacheAction.Cleared, default, new(cleared, cleared.Length, ReturnToPool: false), -1), + ListChangeKind.Deferred when change.Snapshot is { } snapshot => + new(CacheAction.Reset, default, new(snapshot, snapshot.Length, ReturnToPool: false)), + _ => null + }; + + /// Emits a change that rewrites the whole contents as a clear followed by one batch with every new item. + /// The stream signal. + /// The contents before the change. + /// The contents after the change. + /// + /// Applying these two notifications to any earlier copy of the list, or to a copy that already includes the change, gives the + /// new contents in the new order, so replaying the stream from any snapshot ends equal to the list. + /// + private static void EmitRewrite(Signal> pipeline, T[] before, T[] after) + { + // The clear is sent even when nothing was removed, so applying the pair to a copy that already holds the new contents still ends equal. + pipeline.OnNext(new(CacheAction.Cleared, default, new PooledBatch(before, before.Length, ReturnToPool: false), -1)); + EmitBatch(pipeline, CacheAction.BatchAdded, after, 0); + } + + /// Emits one batch notification over an immutable array, skipping empty batches. + /// The stream signal. + /// The batch action. + /// The items, which are shared and never modified. + /// The start index, or -1. + private static void EmitBatch(Signal> pipeline, CacheAction action, T[] items, int index) + { + if (items.Length == 0) + { + return; + } + + pipeline.OnNext(new(action, default, new PooledBatch(items, items.Length, ReturnToPool: false), index)); + } + + /// Updates every mirror that exists with a change. + /// The change. + private void ApplyMirrors(in ListChange change) + { + var items = Volatile.Read(ref _itemsMirror); + if (items is not null) + { + ApplyToItems(items, in change); + } + + if (change.AffectsAddedAndRemoved) + { + SetHistory(Volatile.Read(ref _addedMirror), in change, HistoryKind.Added); + SetHistory(Volatile.Read(ref _removedMirror), in change, HistoryKind.Removed); + } + + if (change.AffectsChanged) + { + SetHistory(Volatile.Read(ref _changedMirror), in change, HistoryKind.Changed); + } + } + + /// Emits a change to when it has observers. + /// The change. + private void EmitStream(in ListChange change) + { + if (Volatile.Read(ref _streamPipeline) is not { HasObservers: true } pipeline) + { + return; + } + + if (change.Kind == ListChangeKind.Replaced) + { + EmitRewrite(pipeline, change.Removed!, change.Added!); + } + else if (change.Kind == ListChangeKind.Edited && change.Before is { } before && change.Snapshot is { } after) + { + EmitRewrite(pipeline, before, after); + } + else if (CreateStreamNotification(in change) is { } notification) + { + pipeline.OnNext(notification); + } + } + + /// Emits at most one notification for the version produced by a mutation. + /// The committed change. + private void EmitVersionedStream(in ListChange change) + { + if (Volatile.Read(ref _versionedPipeline) is not { HasObservers: true } pipeline) + { + return; + } + + // A predicate can remove later occurrences of items that also occur earlier in the list. A clear that is hidden from the + // legacy stream still changes the contents, so a versioned subscriber must hear it as a reset to stay equal to the list. + var notification = change.Kind switch + { + ListChangeKind.Replaced or ListChangeKind.Edited or ListChangeKind.ClearedSilent => new(CacheAction.Reset, default, null), + ListChangeKind.RemovedRange when change.IsPredicateRemoval => new(CacheAction.Reset, default, null), + ListChangeKind.Deferred when change.Snapshot is null => new(CacheAction.Reset, default, null), + _ => CreateStreamNotification(in change) + }; + if (notification is not null) + { + pipeline.OnNext(new(notification, change.Sequence)); + } + } + + /// Creates the added-items observable. + /// The observable. + [MethodImpl(MethodImplOptions.NoInlining)] + private IObservable> CreateAdded() + { + IObservable> created = Stream + .Keep(static n => n.Action is CacheAction.Added or CacheAction.BatchAdded) + .Map(GetItemsFromNotification); + return Interlocked.CompareExchange(ref _addedObservable, created, null) ?? created; + } + + /// Creates the changed-items observable. + /// The observable. + [MethodImpl(MethodImplOptions.NoInlining)] + private IObservable> CreateChanged() + { + IObservable> created = Stream.Map(GetItemsFromNotification); + return Interlocked.CompareExchange(ref _changedObservable, created, null) ?? created; + } + + /// Creates the removed-items observable. + /// The observable. + [MethodImpl(MethodImplOptions.NoInlining)] + private IObservable> CreateRemoved() + { + IObservable> created = Stream + .Keep(static n => n.Action is CacheAction.Removed or CacheAction.BatchRemoved or CacheAction.Cleared) + .Map(GetItemsFromNotification); + return Interlocked.CompareExchange(ref _removedObservable, created, null) ?? created; + } + + /// Creates the observable that replays the current items. + /// The observable. + [MethodImpl(MethodImplOptions.NoInlining)] + private IObservable> CreateCurrentObservable() + { + var created = new CurrentItemsObservable(this); + return Interlocked.CompareExchange(ref _currentObservable, created, null) ?? created; + } + + /// Creates the stream observable, and the signal behind it when needed. + /// The observable. + [MethodImpl(MethodImplOptions.NoInlining)] + private IObservable> CreateStreamObservable() + { + var created = Signal.Create>(SubscribeStream); + return Interlocked.CompareExchange(ref _streamObservable, created, null) ?? created; + } + + /// Attaches a subscriber to the stream signal or completes it when the list has been disposed. + /// The subscriber. + /// The subscription. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private IDisposable SubscribeStream(IObserver> observer) => SubscribeOrComplete(ref _streamPipeline, observer); + + /// Creates the observable that attaches subscribers to the versioned signal. + /// The observable. + [MethodImpl(MethodImplOptions.NoInlining)] + private IObservable> CreateVersionedStreamObservable() + { + var created = Signal.Create>(SubscribeVersioned); + return Interlocked.CompareExchange(ref _versionedObservable, created, null) ?? created; + } + + /// Attaches a subscriber or completes it when the list has been disposed. + /// The subscriber. + /// The subscription. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private IDisposable SubscribeVersioned(IObserver> observer) => + SubscribeOrComplete(ref _versionedPipeline, observer); + + /// Attaches a subscriber to a stream signal, or completes it at once when the list has been disposed. + /// The notification type. + /// The signal field. + /// The subscriber. + /// The subscription. + private IDisposable SubscribeOrComplete(ref Signal? pipeline, IObserver observer) + { + var subscription = IsDisposed ? null : SignalSubscription.TrySubscribe(EnsureStreamPipeline(ref pipeline), observer, ref _disposed); + if (subscription is not null) + { + return subscription; + } + + observer.OnCompleted(); + return Scope.Empty; + } + + /// Gets a stream signal, creating it on first use. + /// The notification type. + /// The signal field. + /// The signal. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private Signal EnsureStreamPipeline(ref Signal? pipeline) => + Volatile.Read(ref pipeline) ?? CreateStreamPipeline(ref pipeline); + + /// Creates the items mirror and its read-only view. + /// The view. + [MethodImpl(MethodImplOptions.NoInlining)] + private ReadOnlyObservableCollection CreateItems() + { + RangeObservableCollection mirror; + lock (SynchronizationLock) + { + mirror = Volatile.Read(ref _itemsMirror) ?? new RangeObservableCollection(_internalList) { AppliedSequence = _version }; + Volatile.Write(ref _itemsMirror, mirror); + } + + var created = new ReadOnlyObservableCollection(mirror); + return Interlocked.CompareExchange(ref _items, created, null) ?? created; + } + + /// Creates the added-history view. + /// The view. + [MethodImpl(MethodImplOptions.NoInlining)] + private ReadOnlyObservableCollection CreateItemsAdded() + { + var created = new ReadOnlyObservableCollection(EnsureHistoryMirror(ref _addedMirror, HistoryKind.Added)); + return Interlocked.CompareExchange(ref _itemsAdded, created, null) ?? created; + } + + /// Creates the changed-history view. + /// The view. + [MethodImpl(MethodImplOptions.NoInlining)] + private ReadOnlyObservableCollection CreateItemsChanged() + { + var created = new ReadOnlyObservableCollection(EnsureHistoryMirror(ref _changedMirror, HistoryKind.Changed)); + return Interlocked.CompareExchange(ref _itemsChanged, created, null) ?? created; + } + + /// Creates the removed-history view. + /// The view. + [MethodImpl(MethodImplOptions.NoInlining)] + private ReadOnlyObservableCollection CreateItemsRemoved() + { + var created = new ReadOnlyObservableCollection(EnsureHistoryMirror(ref _removedMirror, HistoryKind.Removed)); + return Interlocked.CompareExchange(ref _itemsRemoved, created, null) ?? created; + } + + /// Gets the current-items signal, creating it from a snapshot on first use. + /// The signal. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private BehaviorSignal> EnsureCurrentSignal() => Volatile.Read(ref _currentItems) ?? CreateCurrentSignal(); + + /// Queues a fresh snapshot for the current-items signal when mutations happened while nobody listened. + private void RefreshCurrentIfStale() + { + // Pairs with the barrier in EmitCurrentItems: the new observer is visible to the publisher before this thread reads the flag. + Thread.MemoryBarrier(); + if (Volatile.Read(ref _currentStale) && !IsDisposed) + { + QueueStaleRefresh(); + } + } + + /// Exposes the current items as an observable that creates its signal on first subscription. + /// The list. + private sealed class CurrentItemsObservable(ReactiveList owner) : IObservable> + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IDisposable Subscribe(IObserver> observer) => owner.Subscribe(observer); + } +} diff --git a/src/ReactiveList/Collections/ReactiveList.cs b/src/ReactiveList/Collections/ReactiveList.cs index e6bb9276..6eb97063 100644 --- a/src/ReactiveList/Collections/ReactiveList.cs +++ b/src/ReactiveList/Collections/ReactiveList.cs @@ -7,130 +7,47 @@ namespace ReactiveList.Reactive.Collections; #else namespace ReactiveList.Collections; #endif + /// /// Represents a thread-safe, observable list that provides reactive notifications for item additions, removals, and /// changes. /// /// The type of elements in the list. Must be non-nullable. -/// combines the features of a standard list with reactive extensions, allowing consumers -/// to observe changes to the collection in real time. It implements standard collection interfaces and supports batch -/// operations, making it suitable for scenarios where both collection manipulation and change tracking are required. -/// The class raises collection and property change notifications, and exposes observables for added, removed, and -/// changed items. All public methods are thread-safe. This type is not read-only or fixed-size, and supports dynamic -/// modification. +/// +/// All public members are thread-safe. Mutations are applied under an internal lock, and notifications (, +/// , , and the observable collections) are queued in commit +/// order and delivered after the lock is released by one thread at a time. A mutation made from inside a handler is therefore applied +/// immediately but its notifications are delivered after the current handler returns, and a mutation made while another thread is +/// delivering may return before its own notifications have been delivered. Predicates passed to and the action +/// passed to run under the lock, must not block on other threads, and must not mutate the list. +/// [Serializable] [DebuggerDisplay("Count = {Count}")] -public class ReactiveList : IReactiveList +public sealed partial class ReactiveList : IReactiveList, IReactiveSourceWithOptions, IVersionedSnapshotSource where T : notnull { - /// The multiplier used when growing pooled buffers. - private const int BufferGrowthFactor = 2; - - /// The property name used for indexed item notifications. - private const string ItemArray = "Item[]"; - - /// The smallest pooled buffer rented for bulk removals. - private const int MinimumRemovalBufferSize = 16; - - /// The divisor used to estimate an initial bulk-removal buffer size. - private const int RemovalBufferSizingDivisor = 4; - - /// The cached property-change arguments for count updates. - private static readonly PropertyChangedEventArgs CountPropertyChangedEventArgs = new(nameof(Count)); - - /// The cached property-change arguments for indexed item updates. - private static readonly PropertyChangedEventArgs ItemArrayPropertyChangedEventArgs = new(ItemArray); - - /// The cached collection-reset event arguments. - private static readonly NotifyCollectionChangedEventArgs ResetCollectionChangedEventArgs = new(NotifyCollectionChangedAction.Reset); + /// The largest number of requested items matched by scanning instead of hashing. + private const int SmallRemovalThreshold = 8; /// The serialized list that stores the collection contents. private readonly List _internalList = []; - /// The synchronization primitive recreated lazily after deserialization. - [NonSerialized] - private Lock? _lock = new(); - - /// The lazily created stream of added items. - [NonSerialized] - private IObservable>? _added; - - /// The lazily created stream of changed items. - [NonSerialized] - private IObservable>? _changed; - - /// The signal containing the latest collection snapshot. - [NonSerialized] - private BehaviorSignal>? _currentItems; - - /// The lazily created stream of removed items. - [NonSerialized] - private IObservable>? _removed; - - /// The public read-only observable view of all items. - [NonSerialized] - private ReadOnlyObservableCollection? _items; - - /// The public read-only observable view of recently added items. - [NonSerialized] - private ReadOnlyObservableCollection? _itemsAdded; - - /// The mutable collection backing . - [NonSerialized] - private RangeObservableCollection? _itemsAddedCollection; - - /// The public read-only observable view of recently changed items. - [NonSerialized] - private ReadOnlyObservableCollection? _itemsChanged; - - /// The mutable collection backing . - [NonSerialized] - private RangeObservableCollection? _itemsChangedCollection; - - /// The public read-only observable view of recently removed items. - [NonSerialized] - private ReadOnlyObservableCollection? _itemsRemoved; - - /// The mutable collection backing . - [NonSerialized] - private RangeObservableCollection? _itemsRemovedCollection; - - /// The mutable observable collection mirroring the serialized list. + /// The options for this list instance. [NonSerialized] - private RangeObservableCollection? _observableItems; - - /// The signal pipeline that publishes cache notifications. - [NonSerialized] - private Signal>? _streamPipeline; - - /// Indicates whether this list has been disposed. - [NonSerialized] - private bool _disposed; - - /// The monotonically increasing collection version. - [NonSerialized] - private long _version; + private readonly ReactiveSourceOptions? _options; /// Initializes a new instance of the class. - public ReactiveList() => InitializeNonSerializedFields(); + public ReactiveList() => InitializeRuntimeState(); /// Initializes a new instance of the class. /// The items. + /// Thrown when is . public ReactiveList(IEnumerable items) { - var itemArray = (items as T[]) ?? [.. items]; - if (itemArray.Length > 0) - { - _internalList.AddRange(itemArray); - } - - InitializeNonSerializedFields(); - if (itemArray.Length == 0) - { - return; - } + ArgumentExceptionHelper.ThrowIfNull(items); - _currentItems!.OnNext(_internalList); + _internalList.AddRange(items); + InitializeRuntimeState(); } /// Initializes a new instance of the class. @@ -138,8 +55,7 @@ public ReactiveList(IEnumerable items) public ReactiveList(T item) { _internalList.Add(item); - InitializeNonSerializedFields(); - _currentItems!.OnNext(_internalList); + InitializeRuntimeState(); } /// @@ -148,42 +64,11 @@ public ReactiveList(T item) /// public event PropertyChangedEventHandler? PropertyChanged; - /// Defines the bulk-removal contract used by the observable collection helper. - private interface IRangeRemovable - { - /// Removes a contiguous range of items. - /// The index of the first item to remove. - /// The number of items to remove. - void RemoveRange(int index, int count); - } - - /// Gets the added during the last change as an Observable. - /// The added. - public IObservable> Added => _added ??= Stream - .Keep(static n => n.Action is CacheAction.Added or CacheAction.BatchAdded) - .Map(GetItemsFromNotification); - - /// Gets the changed during the last change as an Observable. - /// The changed. - public IObservable> Changed => _changed ??= Stream.Map(GetItemsFromNotification); - - /// Gets the current items during the last change as an Observable. - /// - /// The current items. - /// - public IObservable> CurrentItems => _currentItems!; - - /// Gets the removed items during the last change as an Observable. - /// The removed. - public IObservable> Removed => _removed ??= Stream - .Keep(static n => n.Action is CacheAction.Removed or CacheAction.BatchRemoved or CacheAction.Cleared) - .Map(GetItemsFromNotification); - /// - public int Count => _internalList.Count; + public int Count => Volatile.Read(ref _count); /// - public bool IsDisposed => _disposed; + public bool IsDisposed => Volatile.Read(ref _disposed) != 0; /// public bool IsFixedSize => false; @@ -194,84 +79,66 @@ private interface IRangeRemovable /// public bool IsSynchronized => false; - /// Gets the items. - /// The items. - public ReadOnlyObservableCollection Items => _items ??= new(_observableItems!); - - /// Gets the items added during the last change. - /// The items added. - public ReadOnlyObservableCollection ItemsAdded => _itemsAdded ??= new(_itemsAddedCollection!); - - /// Gets the items changed during the last change. - /// The items changed. - public ReadOnlyObservableCollection ItemsChanged => _itemsChanged ??= new(_itemsChangedCollection!); - - /// Gets the items removed during the last change. - /// The items removed. - public ReadOnlyObservableCollection ItemsRemoved => _itemsRemoved ??= new(_itemsRemovedCollection!); - - /// Gets an observable sequence that emits cache change notifications as they occur. - /// - /// This is the primary observable for change notifications. It provides all change information - /// including single item changes and batch operations. The Stream uses a channel-based pipeline - /// for efficient, low-allocation event delivery. - /// - public IObservable> Stream => _streamPipeline!.AsObservable(); + /// + public ReactiveSourceOptions Options + { + get => _options ?? ReactiveSourceOptions.Default; + init + { + ArgumentExceptionHelper.ThrowIfNull(value); + _options = value; + } + } /// Gets the current version number of the collection, which is incremented on each modification. - /// - /// This property can be used for efficient change detection without acquiring locks. - /// The version is incremented atomically using . - /// + /// This property can be read without taking the list lock. public long Version => Interlocked.Read(ref _version); /// public object SyncRoot => this; - /// Gets the stable synchronization primitive, creating it once when deserialization left it unset. - private Lock SynchronizationLock => LazyInitializer.EnsureInitialized(ref _lock)!; - /// object? IList.this[int index] { - get => _internalList[index]; - set => SetItem(index, (T)value!); + get => GetItem(index); + set => SetItem(index, CoerceItem(value)); } /// public T this[int index] { - get => _internalList[index]; + get => GetItem(index); set => SetItem(index, value); } /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Add(T item) - { - lock (SynchronizationLock) - { - _internalList.Add(item); - _observableItems!.Add(item); - NotifyAdded(item); - } - } + public void Add(T item) => _ = AddCore(item); /// public int Add(object? value) { - Add((T)value!); - return Count - 1; + var item = CoerceItem(value); + return AddCore(item); } /// Creates a snapshot of current items as an array. /// An array containing all current items. [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[] ToArray() + { + // An existing snapshot is immutable and already describes the latest committed contents, so copying it needs no lock. + var snapshot = Volatile.Read(ref _snapshot); + return snapshot is null ? ToArraySlow() : snapshot.AsSpan().ToArray(); + } + + /// + public T[] CopyVersioned(out long version) { lock (SynchronizationLock) { - return [.. _internalList]; + version = _version; + return _internalList.ToArray(); } } @@ -284,44 +151,25 @@ public void AddRange(ReadOnlySpan items) return; } - var itemArray = items.ToArray(); - lock (SynchronizationLock) - { - var requiredCapacity = _internalList.Count + itemArray.Length; - if (_internalList.Capacity < requiredCapacity) - { - _internalList.Capacity = requiredCapacity; - } - - _internalList.AddRange(itemArray); - _observableItems!.AddRange(itemArray); - NotifyAddedRange(itemArray); - } + AddRangeCore(items.ToArray()); } /// + /// Thrown when is . public void AddRange(IEnumerable items) { - var itemArray = (items as T[]) ?? [.. items]; + ArgumentExceptionHelper.ThrowIfNull(items); + + var itemArray = CopyToArray(items); if (itemArray.Length == 0) { return; } - lock (SynchronizationLock) - { -#if NET6_0_OR_GREATER - // Use AddRange with capacity hint for List - _ = _internalList.EnsureCapacity(_internalList.Count + itemArray.Length); -#endif - _internalList.AddRange(itemArray); - _observableItems!.AddRange(itemArray); - - NotifyAddedRange(itemArray); - } + AddRangeCore(itemArray); } - /// Copies items to the specified span. + /// Copies the items to the specified span. /// The destination span. /// Thrown when destination is too small. public void CopyTo(Span destination) @@ -333,151 +181,93 @@ public void CopyTo(Span destination) throw new ArgumentException("Destination span is too small.", nameof(destination)); } -#if NET6_0_OR_GREATER - CollectionsMarshal.AsSpan(_internalList).CopyTo(destination); -#else for (var i = 0; i < _internalList.Count; i++) { destination[i] = _internalList[i]; } -#endif } } /// + /// Thrown when is . public void CopyTo(T[] array, int arrayIndex) { + ArgumentExceptionHelper.ThrowIfNull(array); + lock (SynchronizationLock) { -#if NET6_0_OR_GREATER - CollectionsMarshal.AsSpan(_internalList).CopyTo(array.AsSpan(arrayIndex)); -#else _internalList.CopyTo(array, arrayIndex); -#endif } } /// public void CopyTo(Array array, int index) { - ThrowHelper.ThrowIfNull(array); - - if (array.Rank != 1) - { - throw new ArgumentException("Only single dimensional arrays are supported for the requested action.", nameof(array)); - } - - if (array.GetLowerBound(0) != 0) - { - throw new ArgumentException("The lower bound of target array must be zero.", nameof(array)); - } - -#if NET8_0_OR_GREATER - ArgumentOutOfRangeException.ThrowIfNegative(index); -#else - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index), "Index is less than zero."); - } -#endif - - if (array.Length - index < Count) - { - throw new ArgumentException("The number of elements in the source collection is greater than the available space from index to the end of the destination array.", nameof(array)); - } + ArgumentExceptionHelper.ThrowIfNull(array); + ValidateNonGenericCopyTarget(array, index); if (array is T[] tArray) { + ValidateSpace(array, index, Count); CopyTo(tArray, index); } else if (array is object[] objects) { - try - { - lock (SynchronizationLock) - { - foreach (var item in _internalList) - { - objects[index] = item; - index++; - } - } - } - catch (ArrayTypeMismatchException) - { - throw new ArgumentException("Invalid array type."); - } + CopyToObjects(objects, index); + } + else + { + throw new ArgumentException("Invalid array type.", nameof(array)); } } - /// Gets a read-only span over the internal list for zero-copy access. - /// A read-only span over the internal items. + /// Gets a read-only span over a snapshot of the items. + /// A span over the items as they were when this method ran. /// - /// WARNING: This method does not acquire a lock. The caller must ensure thread safety. - /// The returned span is only valid while no modifications are made to the list. + /// The span is a point-in-time view. It never changes and never throws when other threads mutate the list, but it also + /// never shows those later mutations: call this method again to see them. Calls made with no mutation in between return + /// the same shared snapshot without copying. The snapshot must be treated as read-only. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ReadOnlySpan AsSpan() => -#if NET6_0_OR_GREATER - CollectionsMarshal.AsSpan(_internalList); -#else - new([.. _internalList]); -#endif + public ReadOnlySpan AsSpan() => new(Volatile.Read(ref _snapshot) ?? SnapshotSlow()); - /// Gets a memory region over the internal list for async operations. - /// A read-only memory region over the internal items. + /// Gets a read-only memory region over a snapshot of the items. + /// A read-only memory region over the items as they were when this method ran. /// - /// WARNING: This method does not acquire a lock. The caller must ensure thread safety. - /// The returned memory is only valid while no modifications are made to the list. + /// The region has the same contract as : it is a point-in-time view that later mutations do not change, + /// and it is shared with and enumeration until the next mutation. It stays valid after the list is + /// disposed. It must be treated as read-only. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ReadOnlyMemory AsMemory() => _internalList.ToArray().AsMemory(); + public ReadOnlyMemory AsMemory() => Volatile.Read(ref _snapshot) ?? SnapshotSlow(); - /// Clears all items from the list without releasing the internal array capacity. - /// - /// This method is more efficient than Clear() when you plan to add items back to the list, - /// as it avoids the overhead of reallocating the internal array. The capacity is preserved. - /// + /// Clears all items from the list; the internal array capacity is kept for reuse. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void ClearWithoutDeallocation() => ClearWithoutDeallocation(notifyChange: true); + public void ClearWithoutDeallocation() => Clear(); - /// Clears all items from the list without releasing the internal array capacity. - /// Whether to emit change notifications. + /// Clears all items from the list; the internal array capacity is kept for reuse. + /// Whether to notify observers; when only the mirror is updated + /// and carries one payloadless , so a versioned replica stays equal to the list. public void ClearWithoutDeallocation(bool notifyChange) { + ListChange change; + bool owner; lock (SynchronizationLock) { - if (_internalList.Count == 0) + EnterMutation(); + if (_internalList.Count == 0 && (!notifyChange || CanSkipHistoryReset())) { - if (notifyChange) - { - ClearHistory(); - } - return; } - var clearedItems = notifyChange ? [.. _internalList] : Array.Empty(); - var capacity = _internalList.Capacity; - - _internalList.Clear(); - _observableItems!.Clear(); - - // Restore capacity to avoid reallocation on next add - _internalList.Capacity = capacity; - - if (notifyChange) - { - NotifyCleared(clearedItems); - } + change = ClearLocked(notifyChange); + owner = Publish(in change); } - } - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); + if (owner) + { + Drain(in change); + } } /// @@ -486,79 +276,74 @@ public void Dispose() /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - void IList.Clear() => Clear(); + void IList.Clear() => ClearWithoutDeallocation(); /// - public void Clear() - { - lock (SynchronizationLock) - { - if (_internalList.Count == 0) - { - ClearHistory(); - return; - } - - var clearedItems = _internalList.ToArray(); - _internalList.Clear(); - _observableItems!.Clear(); - NotifyCleared(clearedItems); - } - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() => ClearWithoutDeallocation(notifyChange: true); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { - lock (SynchronizationLock) - { - return _internalList.Contains(item); - } + var snapshot = Volatile.Read(ref _snapshot); + return snapshot is not null ? Array.IndexOf(snapshot, item) >= 0 : IndexOfSlow(item) >= 0; } /// public bool Contains(object? value) => IsCompatibleObject(value) && Contains((T)value!); - /// Executes a batch edit operation on the list. - /// The action to perform on the internal list. + /// Applies several changes as one notification. + /// The action to perform on the list; it runs under the list lock and must not mutate the list directly. + /// Thrown when is . + /// Thrown, from the action, when it mutates this list instead of the supplied editor. + /// + /// An edit that changes the contents or only the order is announced once: raises one reset, and + /// carries a Cleared notification followed by one BatchAdded notification with the whole new contents, so replaying the stream + /// from any earlier copy ends equal to the list. and show the net change. An edit with no + /// net effect announces nothing. If the action throws, the changes it already made are kept and announced before the exception propagates. + /// If the equality or hash code of an item throws while the net change is worked out, the edit is still committed and announced, with + /// empty and , and the exception propagates. + /// public void Edit(Action> editAction) { - ThrowHelper.ThrowIfNull(editAction); + ArgumentExceptionHelper.ThrowIfNull(editAction); - lock (SynchronizationLock) + var change = default(ListChange); + var owner = false; + Exception? failure = null; + try { - var snapshot = _internalList.ToArray(); - var wrapper = new EditableListWrapper(_internalList); - editAction(wrapper); - - _observableItems!.ReplaceAll(_internalList); - - var added = GetMultisetDifference(_internalList, snapshot); - var removed = GetMultisetDifference(snapshot, _internalList); - - if (added.Length > 0) + lock (SynchronizationLock) { - NotifyAddedRange(added, notifyINPC: false); + EnterMutation(); + var before = SnapshotLocked(); + _inCallback = true; + try + { + editAction(new EditableListWrapper(_internalList)); + } + finally + { + _inCallback = false; + owner = PublishEdit(before, out change, out failure); + } } - - if (removed.Length > 0) + } + finally + { + if (owner) { - NotifyRemovedRange(removed, notifyINPC: false); + Drain(in change); } - - OnPropertyChanged(nameof(Count)); - OnPropertyChanged(ItemArray); } + + RethrowIfFailed(failure); } /// - public IEnumerator GetEnumerator() - { - lock (SynchronizationLock) - { - return ((IEnumerable)_internalList.ToArray()).GetEnumerator(); - } - } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator GetEnumerator() => new SnapshotArrayEnumerator(Volatile.Read(ref _snapshot) ?? SnapshotSlow()); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -568,80 +353,102 @@ public IEnumerator GetEnumerator() [MethodImpl(MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { - lock (SynchronizationLock) - { - return _internalList.IndexOf(item); - } + var snapshot = Volatile.Read(ref _snapshot); + return snapshot is not null ? Array.IndexOf(snapshot, item) : IndexOfSlow(item); } /// public int IndexOf(object? value) => IsCompatibleObject(value) ? IndexOf((T)value!) : -1; /// + /// Thrown when is negative or greater than . [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Insert(int index, T item) { + ListChange change; + bool owner; lock (SynchronizationLock) { + EnterMutation(); _internalList.Insert(index, item); - _observableItems?.Insert(index, item); - NotifyAdded(item, index); + change = CreateAdded(item, index); + owner = Publish(in change); + } + + if (owner) + { + Drain(in change); } } /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Insert(int index, object? value) => Insert(index, (T)value!); + public void Insert(int index, object? value) => Insert(index, CoerceItem(value)); - /// Inserts the range. - /// The index. + /// Inserts a range of items at an index. + /// The index at which to insert the first item. /// The items. + /// Thrown when is . + /// Thrown when is negative or greater than . public void InsertRange(int index, IEnumerable items) { - var itemArray = (items as T[]) ?? [.. items]; - if (itemArray.Length == 0) - { - return; - } + ArgumentExceptionHelper.ThrowIfNull(items); + var itemArray = CopyToArray(items); + ListChange change; + bool owner; lock (SynchronizationLock) { + EnterMutation(); + if (index < 0 || index > _internalList.Count) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + + if (itemArray.Length == 0) + { + return; + } + _internalList.InsertRange(index, itemArray); - _observableItems?.InsertRange(index, itemArray); + change = CreateAddedRange(itemArray, index); + owner = Publish(in change); + } - NotifyAddedRange(itemArray, index); + if (owner) + { + Drain(in change); } } /// Moves an item from one index to another. /// The current index of the item. /// The new index for the item. - /// Thrown when oldIndex < 0 || oldIndex >= Count. + /// Thrown when either index is outside the list. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { - if (oldIndex < 0 || oldIndex >= Count) - { - throw new ArgumentOutOfRangeException(nameof(oldIndex)); - } - - if (newIndex < 0 || newIndex >= Count) - { - throw new ArgumentOutOfRangeException(nameof(newIndex)); - } - - if (oldIndex == newIndex) - { - return; - } - + ListChange change; + bool owner; lock (SynchronizationLock) { + EnterMutation(); + ValidateMoveIndexes(oldIndex, newIndex); + if (oldIndex == newIndex) + { + return; + } + var item = _internalList[oldIndex]; _internalList.RemoveAt(oldIndex); _internalList.Insert(newIndex, item); - _observableItems!.Move(oldIndex, newIndex); - NotifyChangedSingle(item, ChangeReason.Move, newIndex, oldIndex); + change = CreateMoved(item, newIndex, oldIndex); + owner = Publish(in change); + } + + if (owner) + { + Drain(in change); } } @@ -649,50 +456,62 @@ public void Move(int oldIndex, int newIndex) [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { + ListChange change; + bool owner; lock (SynchronizationLock) { + EnterMutation(); var index = _internalList.IndexOf(item); if (index < 0) { return false; } + var removed = _internalList[index]; _internalList.RemoveAt(index); - _observableItems!.RemoveAt(index); - NotifyRemoved(item, index); - return true; + change = CreateRemoved(removed, index); + owner = Publish(in change); + } + + if (owner) + { + Drain(in change); } + + return true; } /// + /// Thrown when is . + /// Each requested item removes one matching occurrence, earliest first, in a single pass. public void Remove(IEnumerable items) { - var itemArray = (items as T[]) ?? [.. items]; - if (itemArray.Length == 0) + ArgumentExceptionHelper.ThrowIfNull(items); + + var requested = CopyToArray(items); + if (requested.Length == 0) { return; } + ListChange change; + bool owner; lock (SynchronizationLock) { - var removed = new List(); - foreach (var item in itemArray) + EnterMutation(); + var removed = RemoveRequestedLocked(requested); + if (removed.Length == 0) { - var index = _internalList.IndexOf(item); - if (index < 0) - { - continue; - } - - _internalList.RemoveAt(index); - removed.Add(item); + return; } - if (removed.Count > 0) - { - _observableItems!.ReplaceAll(_internalList); - NotifyRemovedRange([.. removed]); - } + change = CreateRemovedRange(removed, -1); + owner = Publish(in change); + } + + if (owner) + { + Drain(in change); } } @@ -708,70 +527,41 @@ public void Remove(object? value) } /// + /// Thrown when is . + /// The predicate runs exactly once per item, under the list lock, and the list is unchanged if it throws. [MethodImpl(MethodImplOptions.AggressiveInlining)] public int RemoveMany(Func predicate) { - ThrowHelper.ThrowIfNull(predicate); + ArgumentExceptionHelper.ThrowIfNull(predicate); + ListChange change; + bool owner; + int removedCount; lock (SynchronizationLock) { + EnterMutation(); if (_internalList.Count == 0) { return 0; } - var removedBuffer = ArrayPool.Shared.Rent( - Math.Max(MinimumRemovalBufferSize, _internalList.Count / RemovalBufferSizingDivisor)); - var removedCount = 0; - - try + var removed = RemoveMatchingLocked(predicate); + if (removed.Length == 0) { - // Iterate in reverse to avoid index shifting issues - for (var i = _internalList.Count - 1; i >= 0; i--) - { - var item = _internalList[i]; - if (!predicate(item)) - { - continue; - } - - _internalList.RemoveAt(i); - - // Grow buffer if needed - if (removedCount >= removedBuffer.Length) - { - var newBuffer = ArrayPool.Shared.Rent(removedBuffer.Length * BufferGrowthFactor); - Array.Copy(removedBuffer, newBuffer, removedCount); - ArrayPool.Shared.Return( - removedBuffer, - clearArray: ArrayPoolClearHelper.IsReferenceOrContainsReferences()); - removedBuffer = newBuffer; - } - - removedBuffer[removedCount] = item; - removedCount++; - } - - if (removedCount > 0) - { - _observableItems!.ReplaceAll(_internalList); + return 0; + } - // Reverse in-place to maintain original order - Array.Reverse(removedBuffer, 0, removedCount); - var removedItems = new T[removedCount]; - Array.Copy(removedBuffer, removedItems, removedCount); - NotifyRemovedRange(removedItems); - } + removedCount = removed.Length; + change = CreateRemovedRange(removed, -1) with { IsPredicateRemoval = true }; + owner = Publish(in change); + } - return removedCount; - } - finally - { - ArrayPool.Shared.Return( - removedBuffer, - clearArray: ArrayPoolClearHelper.IsReferenceOrContainsReferences()); - } + if (owner) + { + Drain(in change); } + + return removedCount; } /// @@ -783,738 +573,694 @@ public int RemoveMany(Func predicate) void IList.RemoveAt(int index) => RemoveAt(index); /// + /// Thrown when is outside the list. public void RemoveAt(int index) { + ListChange change; + bool owner; lock (SynchronizationLock) { - if (index < 0 || index >= _internalList.Count) + EnterMutation(); + if ((uint)index >= (uint)_internalList.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } var item = _internalList[index]; _internalList.RemoveAt(index); - _observableItems!.RemoveAt(index); - NotifyRemoved(item, index); + change = CreateRemoved(item, index); + owner = Publish(in change); + } + + if (owner) + { + Drain(in change); } } /// + /// Thrown when or is negative, or the range extends past the end of the list. public void RemoveRange(int index, int count) { - if (count == 0) - { - return; - } - + ListChange change; + bool owner; lock (SynchronizationLock) { - if (index < 0 || index >= _internalList.Count) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - - if (index + count > _internalList.Count) + EnterMutation(); + ValidateRange(index, count); + if (count == 0) { - throw new ArgumentOutOfRangeException(nameof(count)); + return; } -#if NET6_0_OR_GREATER var removed = new T[count]; _internalList.CopyTo(index, removed, 0, count); _internalList.RemoveRange(index, count); - _observableItems!.RemoveRange(index, count); -#else - var removed = new T[count]; - for (var i = 0; i < count; i++) - { - removed[i] = _internalList[index]; - _internalList.RemoveAt(index); - _observableItems!.RemoveAt(index); - } -#endif + change = CreateRemovedRange(removed, index); + owner = Publish(in change); + } - NotifyRemovedRange(removed); + if (owner) + { + Drain(in change); } } /// + /// Thrown when is . public void ReplaceAll(IEnumerable items) { - var itemArray = (items as T[]) ?? [.. items]; + ArgumentExceptionHelper.ThrowIfNull(items); + var itemArray = CopyToArray(items); + ListChange change; + bool owner; lock (SynchronizationLock) { - var oldItems = _internalList.ToArray(); + EnterMutation(); + var old = SnapshotLocked(); _internalList.Clear(); - -#if NET6_0_OR_GREATER - _ = _internalList.EnsureCapacity(itemArray.Length); -#endif _internalList.AddRange(itemArray); - _observableItems!.ReplaceAll(itemArray); - - _ = Interlocked.Increment(ref _version); - - TrackReplacement(oldItems, itemArray); + change = CreateReplaced(itemArray, old); + owner = Publish(in change); + } - OnPropertyChanged(nameof(Count)); - OnPropertyChanged(ItemArray); + if (owner) + { + Drain(in change); } } - /// Subscribes the specified observer to the CurrentItems. - /// The observer. - /// An IDisposable to release the subscription. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public IDisposable Subscribe(IObserver> observer) => _currentItems!.Subscribe(observer); - /// + /// Nothing happens when is not in the list. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { + ListChange change; + bool owner; lock (SynchronizationLock) { + EnterMutation(); var index = _internalList.IndexOf(item); - if (index >= 0) + if (index < 0) { - var oldValue = _internalList[index]; - _internalList[index] = newValue; - _observableItems![index] = newValue; - NotifyChangedSingle(newValue, ChangeReason.Update, index, index, previous: oldValue); + return; } + + var previous = _internalList[index]; + _internalList[index] = newValue; + change = CreateUpdated(newValue, previous, index); + owner = Publish(in change); + } + + if (owner) + { + Drain(in change); } } - /// Disposes the specified disposables. - /// if set to true [disposing]. - protected virtual void Dispose(bool disposing) + /// Releases the stream and observable resources; calling it more than once, or from several threads, is safe. + /// Reads keep working after disposal, mutations throw . + public void Dispose() { - if (!disposing) + if (Interlocked.Exchange(ref _disposed, 1) != 0) { return; } - _disposed = true; - _currentItems?.Dispose(); - _streamPipeline?.OnCompleted(); - _streamPipeline?.Dispose(); - } - - /// Raises a PropertyChanged event (per ). - /// Name of the property. - protected virtual void OnPropertyChanged(string propertyName) - { - var args = propertyName switch + var change = new ListChange(ListChangeKind.Complete, 0, default, default, null, null, -1, -1, null); + bool owner; + lock (SynchronizationLock) { - nameof(Count) => CountPropertyChangedEventArgs, - ItemArray => ItemArrayPropertyChangedEventArgs, - _ => new PropertyChangedEventArgs(propertyName) - }; + // Changes that were committed but not yet delivered are discarded: nothing is announced once disposal has begun. + DiscardQueued(); + _deferralStart = default; + owner = BeginDrainOrQueue(in change); + } - PropertyChanged?.Invoke(this, args); + if (owner) + { + Drain(in change); + } } - /// Determines whether the specified object is compatible with the generic type parameter T. - /// The object to test for compatibility with type T. May be null. + /// Determines whether the specified object can be stored in this list. + /// The object to test. /// true if the object is of type T, or if both the object and the default value of T are null; otherwise, false. - [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsCompatibleObject(object? value) => (value is T) || (value is null && default(T) is null); - /// Replaces all items in the specified observable collection with the elements from the provided array. - /// The observable collection to update. All existing items in this collection will be removed and replaced. - /// The array of items to add to the collection. The collection will contain these items after the operation - /// completes. - /// The method clears the target collection before adding the new items. The order of items in - /// the collection will match the order in the provided array. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void UpdateTrackingCollection(RangeObservableCollection target, T[] items) => target.ReplaceAll(items); - - /// Creates data for the CreateBatch operation. - /// The items value. - /// A pooled batch wrapping a copy of the specified items. - private static PooledBatch CreateBatch(T[] items) + /// Converts a non-generic value into an item, following the contract. + /// The value. + /// The item. + /// Thrown when is null and cannot hold null. + /// Thrown when is not a . + private static T CoerceItem(object? value) { - var batchItems = new T[items.Length]; - Array.Copy(items, batchItems, items.Length); - return new(batchItems, items.Length, ReturnToPool: false); - } - - /// Gets data for the GetMultisetDifference operation. - /// The source value. - /// The subtract value. - /// The source items after removing matching occurrences from the subtract list. - private static T[] GetMultisetDifference(IReadOnlyList source, IReadOnlyList subtract) - { - if (source.Count == 0) + if (value is T item) { - return []; + return item; } - var counts = new Dictionary(subtract.Count); - for (var i = 0; i < subtract.Count; i++) + if (value is null && default(T) is null) { - var item = subtract[i]; - _ = counts.TryGetValue(item, out var count); - counts[item] = count + 1; + return default!; } - List? difference = null; - for (var i = 0; i < source.Count; i++) + throw value is null + ? new ArgumentNullException(nameof(value)) + : new ArgumentException($"The value is not of type {typeof(T)}.", nameof(value)); + } + + /// Copies a sequence into a new array that the list owns. + /// The items. + /// The array. + private static T[] CopyToArray(IEnumerable items) => [.. items]; + + /// Validates the destination of a non-generic copy. + /// The destination. + /// The first destination index. + /// Thrown when the array is not one-dimensional with a zero lower bound. + /// Thrown when is negative. + private static void ValidateNonGenericCopyTarget(Array array, int index) + { + if (array.Rank != 1) { - var item = source[i]; - if (counts.TryGetValue(item, out var count) && count > 0) - { - counts[item] = count - 1; - continue; - } + throw new ArgumentException("Only single dimensional arrays are supported for the requested action.", nameof(array)); + } - difference ??= []; - difference.Add(item); + if (array.GetLowerBound(0) != 0) + { + throw new ArgumentException("The lower bound of target array must be zero.", nameof(array)); } - return difference is null ? [] : [.. difference]; + ArgumentOutOfRangeExceptionHelper.ThrowIfNegative(index); } - /// Extracts items from a cache notification. - /// The cache notification. - /// The items from the notification. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static T[] GetItemsFromNotification(CacheNotify notification) + /// Checks that an array has room for items. + /// The destination. + /// The first destination index. + /// The number of items to copy. + /// Thrown when the array is too small. + private static void ValidateSpace(Array array, int index, int count) { - if (notification.Batch is not null) + if (array.Length - index < count) { - // Return a copy to avoid issues with pooled array disposal - var batch = notification.Batch; - var result = new T[batch.Count]; - Array.Copy(batch.Items, result, batch.Count); - return result; + throw new ArgumentException("The number of elements in the source collection is greater than the available space from index to the end of the destination array.", nameof(array)); } - - return notification.Item is not null ? [notification.Item] : []; } - /// Updates change tracking and observers after replacing the complete list contents. - /// The items that were replaced. - /// The replacement items. - private void TrackReplacement(T[] oldItems, T[] newItems) + /// Tests whether any item is . + /// The items. + /// when a null is present. + private static bool HasNull(T[] items) { - // ReplaceAll semantics expose the new items as added and the old items as both removed and changed. - UpdateTrackingCollection(_itemsAddedCollection!, newItems); - UpdateTrackingCollection(_itemsRemovedCollection!, oldItems); - UpdateTrackingCollection(_itemsChangedCollection!, oldItems); - _currentItems!.OnNext(_internalList); + for (var i = 0; i < items.Length; i++) + { + if (items[i] is null) + { + return true; + } + } - var hasObservers = _streamPipeline?.HasObservers == true; - EmitReplacementBatchIfObserved(CacheAction.BatchRemoved, oldItems, hasObservers); - EmitReplacementBatchIfObserved(CacheAction.BatchAdded, newItems, hasObservers); + return false; + } - if (oldItems.Length == 0 && newItems.Length == 0) + /// Finds an item in the first entries of an array. + /// The array. + /// The number of live entries. + /// The item to find. + /// The equality comparer. + /// The index, or -1. + private static int IndexOfPending(T[] requested, int pending, T item, EqualityComparer comparer) + { + for (var i = 0; i < pending; i++) { - return; + if (comparer.Equals(requested[i], item)) + { + return i; + } } - RaiseCollectionReset(); + return -1; } - /// Emits a replacement batch when the stream has observers and the batch contains items. - /// The batch action. - /// The batch items. - /// Whether the stream has observers. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void EmitReplacementBatchIfObserved(CacheAction action, T[] items, bool hasObservers) + /// Throws a captured exception with its original stack trace; does nothing for . + /// The captured exception, if any. + private static void RethrowIfFailed(Exception? failure) { - if (!hasObservers || items.Length == 0) + if (failure is not null) { - return; + ExceptionDispatchInfo.Capture(failure).Throw(); } - - EmitObservedStreamBatch(action, items); } - /// Sets data for the SetItem operation. - /// The index value. - /// The new value. - /// Thrown when index < 0 || index >= _internalList.Count. - private void SetItem(int index, T value) + /// Adds items that the list now owns. + /// The items. + private void AddRangeCore(T[] itemArray) { + ListChange change; + bool owner; lock (SynchronizationLock) { - if (index < 0 || index >= _internalList.Count) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } + EnterMutation(); + var start = _internalList.Count; + _internalList.AddRange(itemArray); + change = CreateAddedRange(itemArray, start); + owner = Publish(in change); + } - var oldValue = _internalList[index]; - _internalList[index] = value; - _observableItems![index] = value; - NotifyChangedSingle(value, ChangeReason.Update, index, index, previous: oldValue); + if (owner) + { + Drain(in change); } } - /// Handles post-deserialization processing to restore the object's state after deserialization is complete. - /// The streaming context for the deserialization operation. Provides contextual information about the source or - /// destination of the serialization stream. - /// This method is automatically invoked by the deserialization infrastructure after the object - /// has been deserialized. It is used to reinitialize fields or properties that are not serialized. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - [OnDeserialized] - private void OnDeserialized(StreamingContext context) => InitializeNonSerializedFields(); - - /// Initializes fields that are not serialized during deserialization or object construction. - /// Call this method after deserialization to ensure that all non-serialized fields are properly - /// initialized and the object is in a valid state. This method is intended for internal use and should not be - /// called directly in normal application code. - private void InitializeNonSerializedFields() + /// Adds one item. + /// The item. + /// The index of the item. + private int AddCore(T item) { - _ = SynchronizationLock; - _disposed = false; - _observableItems = new(_internalList); - _itemsAddedCollection = []; - _itemsChangedCollection = []; - _itemsRemovedCollection = []; - _items = null; - _itemsAdded = null; - _itemsChanged = null; - _itemsRemoved = null; - _currentItems = new([]); - _streamPipeline = new(); - _added = null; - _removed = null; - _changed = null; - - OnPropertyChanged(nameof(Count)); - OnPropertyChanged(ItemArray); - } + ListChange change; + bool owner; + int index; + lock (SynchronizationLock) + { + EnterMutation(); + index = _internalList.Count; + _internalList.Add(item); + change = CreateAdded(item, index); + owner = Publish(in change); + } - /// Raises collectionreset notifications. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void RaiseCollectionReset() => CollectionChanged?.Invoke(this, ResetCollectionChangedEventArgs); + if (owner) + { + Drain(in change); + } - /// Raises collectionadded notifications. - /// The item value. - /// The index value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void RaiseCollectionAdded(T item, int index) => - CollectionChanged?.Invoke( - this, - new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); - - /// Raises collectionremoved notifications. - /// The item value. - /// The index value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void RaiseCollectionRemoved(T item, int index) => - CollectionChanged?.Invoke( - this, - new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index)); - - /// Raises collectionchanged notifications. - /// The item value. - /// The previous value. - /// The index value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void RaiseCollectionChanged(T item, T? previous, int index) => - CollectionChanged?.Invoke( - this, - new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, item, previous, index)); - - /// Raises collectionmoved notifications. - /// The item value. - /// The currentIndex value. - /// The previousIndex value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void RaiseCollectionMoved(T item, int currentIndex, int previousIndex) => - CollectionChanged?.Invoke( - this, - new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, item, currentIndex, previousIndex)); - - /// Performs the TrackAdded operation. - /// The item value. - /// The index value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void TrackAdded(T item, int index) - { - _itemsAddedCollection!.ReplaceWithSingle(item); - _itemsRemovedCollection!.Clear(); - _itemsChangedCollection!.ReplaceWithSingle(item); - _currentItems!.OnNext(_internalList); - RaiseCollectionAdded(item, index); + return index; } - /// Performs the TrackAddedRange operation. - /// The items value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void TrackAddedRange(T[] items) + /// Reads the item at an index, without locking when an immutable snapshot already exists. + /// The index. + /// The item. + private T GetItem(int index) { - UpdateTrackingCollection(_itemsAddedCollection!, items); - _itemsRemovedCollection!.Clear(); - UpdateTrackingCollection(_itemsChangedCollection!, items); - _currentItems!.OnNext(_internalList); - RaiseCollectionReset(); + var snapshot = Volatile.Read(ref _snapshot); + return snapshot is not null && (uint)index < (uint)snapshot.Length ? snapshot[index] : GetItemSlow(index); } - /// Performs the TrackRemoved operation. - /// The item value. - /// The index value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void TrackRemoved(T item, int index) + /// Reads the item at an index under the lock, which also reports an out-of-range index. + /// The index. + /// The item. + [MethodImpl(MethodImplOptions.NoInlining)] + private T GetItemSlow(int index) { - _itemsRemovedCollection!.ReplaceWithSingle(item); - _itemsAddedCollection!.Clear(); - _itemsChangedCollection!.ReplaceWithSingle(item); - _currentItems!.OnNext(_internalList); - RaiseCollectionRemoved(item, index); - } + lock (SynchronizationLock) + { + var item = _internalList[index]; - /// Performs the TrackRemovedRange operation. - /// The items value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void TrackRemovedRange(T[] items) - { - UpdateTrackingCollection(_itemsRemovedCollection!, items); - _itemsAddedCollection!.Clear(); - UpdateTrackingCollection(_itemsChangedCollection!, items); - _currentItems!.OnNext(_internalList); - RaiseCollectionReset(); + // Repeated reads with no mutation in between earn a snapshot, so later reads skip the lock; a write-then-read loop never pays the copy. + CountLockedRead(); + return item; + } } - /// Performs the TrackChanged operation. - /// The item value. - /// The action value. - /// The currentIndex value. - /// The previousIndex value. - /// The previous value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void TrackChanged(T item, CacheAction action, int currentIndex, int previousIndex, T? previous) + /// Searches the list under the lock, which also earns a snapshot after repeated reads so later searches skip the lock. + /// The item to find. + /// The index, or -1. + [MethodImpl(MethodImplOptions.NoInlining)] + private int IndexOfSlow(T item) { - _itemsChangedCollection!.ReplaceWithSingle(item); - _currentItems!.OnNext(_internalList); - if (action == CacheAction.Moved) - { - RaiseCollectionMoved(item, currentIndex, previousIndex); - } - else + lock (SynchronizationLock) { - RaiseCollectionChanged(item, previous, currentIndex); + var index = _internalList.IndexOf(item); + CountLockedRead(); + return index; } } - /// Notifies subscribers that an item has been added to the collection and raises the appropriate collection changed event. - /// The item that was added to the collection. - /// The zero-based index at which the item was added, or -1 to indicate the item was added at the end of the - /// collection. - /// True to notify INotifyPropertyChanged subscribers; otherwise, false. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void NotifyAdded(T item, int index = -1, bool notifyINPC = true) + /// Counts a read made under the lock and builds the snapshot once reads keep arriving without a mutation; call with the list lock held. + private void CountLockedRead() { - _ = Interlocked.Increment(ref _version); - var startIndex = index >= 0 ? index : _internalList.Count - 1; - TrackAdded(item, startIndex); - EmitStream(CacheAction.Added, item, currentIndex: startIndex); - - if (!notifyINPC) + _readsSinceMutation++; + if (_readsSinceMutation == SnapshotAfterReads) { - return; + _ = SnapshotLocked(); } - - OnPropertyChanged(nameof(Count)); - OnPropertyChanged(ItemArray); } - /// Notifies observers that a range of items has been added to the collection and updates tracking collections accordingly. - /// The array of items that were added to the collection. Cannot be null. - /// The zero-based index at which the items were added, or -1 if the index is not specified. - /// True to notify INotifyPropertyChanged subscribers; otherwise, false. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void NotifyAddedRange(T[] items, int index = -1, bool notifyINPC = true) + /// Copies the contents under the lock. + /// A new array. + [MethodImpl(MethodImplOptions.NoInlining)] + private T[] ToArraySlow() { - _ = Interlocked.Increment(ref _version); - var startIndex = index >= 0 ? index : _internalList.Count - items.Length; - TrackAddedRange(items); - if (_streamPipeline?.HasObservers == true) - { - EmitObservedStreamBatch(CacheAction.BatchAdded, items, startIndex); - } - - if (!notifyINPC) + lock (SynchronizationLock) { - return; + return _internalList.ToArray(); } - - OnPropertyChanged(nameof(Count)); - OnPropertyChanged(ItemArray); } - /// Notifies subscribers that an item has been removed from the collection at the specified index. - /// The item that was removed from the collection. - /// The zero-based index at which the item was removed. - /// True to notify INotifyPropertyChanged subscribers; otherwise, false. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void NotifyRemoved(T item, int index, bool notifyINPC = true) + /// Gets the shared snapshot under the lock, creating it when a mutation invalidated it. + /// The snapshot. + [MethodImpl(MethodImplOptions.NoInlining)] + private T[] SnapshotSlow() { - _ = Interlocked.Increment(ref _version); - TrackRemoved(item, index); - EmitStream(CacheAction.Removed, item, currentIndex: index); - - if (!notifyINPC) + lock (SynchronizationLock) { - return; + return SnapshotLocked(); } - - OnPropertyChanged(nameof(Count)); - OnPropertyChanged(ItemArray); } - /// Notifies observers that a range of items has been removed from the collection. - /// The array of items that were removed from the collection. Cannot be null. - /// True to notify INotifyPropertyChanged subscribers; otherwise, false. - /// This method updates internal tracking collections and raises collection change notifications - /// to observers. It should be called after items have been removed to ensure that all observers receive the - /// appropriate notifications. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void NotifyRemovedRange(T[] items, bool notifyINPC = true) + /// Replaces the item at an index. + /// The index. + /// The new value. + /// Thrown when is outside the list. + private void SetItem(int index, T value) { - _ = Interlocked.Increment(ref _version); - TrackRemovedRange(items); - if (_streamPipeline?.HasObservers == true) + ListChange change; + bool owner; + lock (SynchronizationLock) { - EmitObservedStreamBatch(CacheAction.BatchRemoved, items); + EnterMutation(); + if ((uint)index >= (uint)_internalList.Count) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + + var previous = _internalList[index]; + _internalList[index] = value; + change = CreateUpdated(value, previous, index); + owner = Publish(in change); } - if (!notifyINPC) + if (owner) { - return; + Drain(in change); } - - OnPropertyChanged(nameof(Count)); - OnPropertyChanged(ItemArray); } - /// Notifies subscribers that the collection has been cleared and provides the items that were removed. - /// An array containing the items that were removed from the collection when it was cleared. Cannot be null. - /// True to notify INotifyPropertyChanged subscribers; otherwise, false. - /// This method raises collection change notifications and updates internal tracking collections - /// to reflect the cleared state. It should be called after the collection is cleared to ensure that observers - /// receive accurate updates. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void NotifyCleared(T[] clearedItems, bool notifyINPC = true) + /// Copies the items into an array. + /// The destination. + /// The first destination index. + /// Thrown when the array is too small or cannot hold the items. + private void CopyToObjects(object[] array, int index) { - _ = Interlocked.Increment(ref _version); - TrackRemovedRange(clearedItems); - if (_streamPipeline?.HasObservers == true) + try { - if (clearedItems.Length > 0) - { - EmitObservedStreamBatch(CacheAction.Cleared, clearedItems); - } - else + lock (SynchronizationLock) { - EmitStream(CacheAction.Cleared, default); + ValidateSpace(array, index, _internalList.Count); + for (var i = 0; i < _internalList.Count; i++) + { + array[index + i] = _internalList[i]; + } } } + catch (ArrayTypeMismatchException) + { + throw new ArgumentException("Invalid array type.", nameof(array)); + } + } - if (!notifyINPC) + /// Checks both indexes of a move. + /// The source index. + /// The target index. + /// Thrown when either index is outside the list. + private void ValidateMoveIndexes(int oldIndex, int newIndex) + { + if ((uint)oldIndex >= (uint)_internalList.Count) { - return; + throw new ArgumentOutOfRangeException(nameof(oldIndex)); } - OnPropertyChanged(nameof(Count)); - OnPropertyChanged(ItemArray); + if ((uint)newIndex >= (uint)_internalList.Count) + { + throw new ArgumentOutOfRangeException(nameof(newIndex)); + } } - /// Notifies observers that a single item has changed by updating the change collection and publishing the change event. - /// The item that has changed and should be reported to observers. - /// The reason for the change. Defaults to Refresh. - /// The current index, if applicable. - /// The previous index, if applicable (for moves). - /// The previous item value (for update operations), or default if not applicable. - /// This method is intended for scenarios where only one item has changed and should be - /// communicated as such to subscribers. It clears any previous change notifications before reporting the new - /// change. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void NotifyChangedSingle(T item, ChangeReason reason = ChangeReason.Refresh, int currentIndex = -1, int previousIndex = -1, T? previous = default) + /// Checks a range against the list. + /// The first index. + /// The number of items. + /// Thrown when the range is not inside the list. + private void ValidateRange(int index, int count) { - _ = Interlocked.Increment(ref _version); - var cacheAction = reason switch - { - ChangeReason.Update => CacheAction.Updated, - ChangeReason.Move => CacheAction.Moved, - ChangeReason.Refresh => CacheAction.Refreshed, - _ => CacheAction.Updated - }; - TrackChanged(item, cacheAction, currentIndex, previousIndex, previous); - EmitStream(cacheAction, item, currentIndex: currentIndex, previousIndex: previousIndex, previous: previous); - OnPropertyChanged(ItemArray); + ArgumentOutOfRangeExceptionHelper.ThrowIfNegative(index); + + if (count < 0 || _internalList.Count - index < count) + { + throw new ArgumentOutOfRangeException(nameof(count)); + } } - /// Clears all tracked item history, removing records of added, changed, and removed items. - /// Call this method to reset the internal collections that track item changes. After calling - /// this method, any previous history of item additions, modifications, or removals will be lost. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ClearHistory() + /// Clears the list and describes the change. + /// Whether observers are told. + /// The change. + private ListChange ClearLocked(bool notify) { - _itemsAddedCollection!.Clear(); - _itemsChangedCollection!.Clear(); - _itemsRemovedCollection!.Clear(); - OnPropertyChanged(nameof(Count)); - OnPropertyChanged(ItemArray); + if (_internalList.Count == 0) + { + return CreateHistoryReset(); + } + + var removed = notify ? SnapshotLocked() : null; + _internalList.Clear(); + return notify ? CreateCleared(removed!) : CreateClearedSilent(); } - /// Creates a pooled batch and emits it to the stream pipeline with disposal fallback. - /// The cache action type. - /// The items to copy into the batch. - /// The starting index for the batch, or -1 if not applicable. - private void EmitObservedStreamBatch(CacheAction action, T[] items, int currentIndex = -1) + /// Tests whether an empty clear would change the history or raise property notifications. + /// Whether the clear would have no observable effect. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool CanSkipHistoryReset() => + PropertyChanged is null + && _historyAddedRemoved.Kind is ListChangeKind.None or ListChangeKind.HistoryReset + && _historyChanged.Kind is ListChangeKind.None or ListChangeKind.HistoryReset; + + /// Removes the items matching a predicate in one pass. + /// The predicate. + /// The removed items in list order. + private T[] RemoveMatchingLocked(Func predicate) { - var batch = (PooledBatch?)CreateBatch(items); + var count = _internalList.Count; + var flags = ArrayPool.Shared.Rent(count); try { - EmitStream(action, default, batch, currentIndex); - batch = null; + var matches = MarkMatches(predicate, flags, count); + if (matches == 0) + { + return []; + } + + var removed = new T[matches]; + Compact(flags, count, removed); + return removed; } finally { - batch?.Dispose(); + ArrayPool.Shared.Return(flags); } } - /// Emits a cache event to the Stream pipeline. - /// The cache action type. - /// The item associated with the action. - /// An optional batch of items. - /// The current index of the item, or -1 if not applicable. - /// The previous index of the item, or -1 if not applicable. - /// The previous item value (for update operations), or default if not applicable. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void EmitStream(CacheAction action, T? item, PooledBatch? batch = null, int currentIndex = -1, int previousIndex = -1, T? previous = default) + /// Evaluates a predicate once for each item without changing the list. + /// The predicate. + /// Receives one flag per item. + /// The number of items. + /// The number of matches. + private int MarkMatches(Func predicate, bool[] flags, int count) { - if (_streamPipeline?.HasObservers != true) + var matches = 0; + _inCallback = true; + try { - batch?.Dispose(); - return; + for (var i = 0; i < count; i++) + { + var match = predicate(_internalList[i]); + flags[i] = match; + if (match) + { + matches++; + } + } } - - _streamPipeline.OnNext(new(action, item, batch, currentIndex, previousIndex, previous)); - } - - /// Provides the RangeObservableCollection implementation. - private sealed class RangeObservableCollection : ObservableCollection, IRangeRemovable - { - /// Initializes a new instance of the class. - public RangeObservableCollection() + finally { + _inCallback = false; } - /// Initializes a new instance of the class. - /// The items value. - public RangeObservableCollection(IEnumerable items) - : base([.. items]) - { - } + return matches; + } - /// Adds data for the AddRange operation. - /// The items value. - public void AddRange(T[] items) + /// Moves the kept items to the front and copies the flagged items out. + /// One flag per item; set for the items to remove. + /// The number of items. + /// Receives the removed items. + private void Compact(bool[] flags, int count, T[] removed) + { + var write = 0; + var removedIndex = 0; + for (var read = 0; read < count; read++) { - if (items.Length == 0) + var item = _internalList[read]; + if (flags[read]) { - return; + removed[removedIndex] = item; + removedIndex++; + continue; } - CheckReentrancy(); - EnsureCapacity(Items.Count + items.Length); - for (var i = 0; i < items.Length; i++) + if (write != read) { - Items.Add(items[i]); + _internalList[write] = item; } - RaiseReset(); + write++; } - /// Inserts data for the InsertRange operation. - /// The index value. - /// The items value. - public void InsertRange(int index, T[] items) + _internalList.RemoveRange(write, count - write); + } + + /// Removes one occurrence for each requested item, earliest first. + /// The requested items; the array is reordered. + /// The removed items in list order. + private T[] RemoveRequestedLocked(T[] requested) + { + var count = _internalList.Count; + if (count == 0) { - if (items.Length == 0) + return []; + } + + // Item equality and hash codes are user code, so every match is decided before the first item moves: a throw leaves the list untouched. + var flags = ArrayPool.Shared.Rent(count); + try + { + _inCallback = true; + int matches; + try { - return; + matches = requested.Length <= SmallRemovalThreshold || HasNull(requested) + ? MarkByScan(requested, flags, count) + : MarkByCounts(requested, flags, count); + } + finally + { + _inCallback = false; } - CheckReentrancy(); - EnsureCapacity(Items.Count + items.Length); - for (var i = 0; i < items.Length; i++) + if (matches == 0) { - Items.Insert(index + i, items[i]); + return []; } - RaiseReset(); + var removed = new T[matches]; + Compact(flags, count, removed); + return removed; } - - /// Performs the ReplaceAll operation. - /// The items value. - public void ReplaceAll(IReadOnlyList items) + finally { - CheckReentrancy(); - Items.Clear(); - EnsureCapacity(items.Count); - for (var i = 0; i < items.Count; i++) + ArrayPool.Shared.Return(flags); + } + } + + /// Flags the list items that match a short pending array, without changing the list. + /// The pending items; matched entries are swapped out. + /// Receives one flag per item. + /// The number of items. + /// The number of flagged items. + private int MarkByScan(T[] requested, bool[] flags, int count) + { + var comparer = EqualityComparer.Default; + var pending = requested.Length; + var matches = 0; + for (var read = 0; read < count; read++) + { + var match = pending > 0 ? IndexOfPending(requested, pending, _internalList[read], comparer) : -1; + flags[read] = match >= 0; + if (match < 0) { - Items.Add(items[i]); + continue; } - RaiseReset(); + pending--; + requested[match] = requested[pending]; + matches++; } - /// Performs the ReplaceWithSingle operation. - /// The item value. - public void ReplaceWithSingle(T item) + return matches; + } + + /// Flags the list items that match a table of requested counts, without changing the list. + /// The requested items. + /// Receives one flag per item. + /// The number of items. + /// The number of flagged items. + private int MarkByCounts(T[] requested, bool[] flags, int count) + { + var counts = new Dictionary(requested.Length); + for (var i = 0; i < requested.Length; i++) { - CheckReentrancy(); - Items.Clear(); - Items.Add(item); - RaiseReset(); + DictionaryCompat.Increment(counts, requested[i]); } - /// Removes data for the RemoveRange operation. - /// The index value. - /// The count value. - public void RemoveRange(int index, int count) + var matches = 0; + for (var read = 0; read < count; read++) { - if (count == 0) + // A null supplied by a caller that did not enforce the type constraint is never matched. + var item = _internalList[read]; + var match = item is not null && DictionaryCompat.TryConsume(counts, item); + flags[read] = match; + if (match) { - return; + matches++; } + } - CheckReentrancy(); - for (var i = 0; i < count; i++) - { - Items.RemoveAt(index); - } + return matches; + } - RaiseReset(); + /// Computes and publishes the net change of an edit. + /// The contents before the edit. + /// Receives the change. + /// Receives the exception thrown by item equality while the difference was worked out, or . + /// when the caller must deliver . + private bool PublishEdit(T[] before, out ListChange change, out Exception? failure) + { + change = default; + if (!TryComputeDifference(before, out var added, out var removed, out failure)) + { + return false; } - /// Raises reset notifications. - private void RaiseReset() + change = CreateEdited(before, added, removed); + return Publish(in change); + } + + /// Works out which items were added and removed, running item equality under the lock without letting a throw escape. + /// The contents before the change. + /// Receives the added items; empty when the calculation failed. + /// Receives the removed items; empty when the calculation failed. + /// Receives the exception thrown by item equality, or . + /// when the contents differ, which is also the answer when the calculation failed, because the change is already applied. + /// The caller commits and announces the change and then rethrows . + private bool TryComputeDifference(T[] before, out T[] added, out T[] removed, out Exception? failure) + { + failure = null; + _inCallback = true; + try { - OnPropertyChanged(CountPropertyChangedEventArgs); - OnPropertyChanged(ItemArrayPropertyChangedEventArgs); - OnCollectionChanged(ResetCollectionChangedEventArgs); + return ListMultisetDifference.Compute(before, _internalList, out added, out removed); } - - /// Ensures state for the EnsureCapacity operation. - /// The capacity value. - private void EnsureCapacity(int capacity) + catch (Exception ex) when (ex is not OutOfMemoryException) { - if (Items is not List list || list.Capacity >= capacity) - { - return; - } - - list.Capacity = capacity; + failure = ex; + added = []; + removed = []; + return true; + } + finally + { + _inCallback = false; } } } diff --git a/src/ReactiveList/Collections/ReactiveSourceOptions.cs b/src/ReactiveList/Collections/ReactiveSourceOptions.cs new file mode 100644 index 00000000..10fd3183 --- /dev/null +++ b/src/ReactiveList/Collections/ReactiveSourceOptions.cs @@ -0,0 +1,21 @@ +// 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.Collections; +#else +namespace ReactiveList.Collections; +#endif + +/// Describes how views can observe items in a reactive source. +[System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] +public sealed class ReactiveSourceOptions +{ + /// Gets a value indicating whether items are immutable. + /// When true, views ignore in-place refresh notifications. Replacing an item still updates every view. + public bool ItemsAreImmutable { get; init; } + + /// Gets the options for a source that has not specified any. + internal static ReactiveSourceOptions Default { get; } = new(); +} diff --git a/src/ReactiveList/Collections/VersionedNotification.cs b/src/ReactiveList/Collections/VersionedNotification.cs new file mode 100644 index 00000000..ca94e210 --- /dev/null +++ b/src/ReactiveList/Collections/VersionedNotification.cs @@ -0,0 +1,16 @@ +// 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.Collections; +#else +namespace ReactiveList.Collections; +#endif + +/// A change notification together with the collection version the change produced. +/// The item type. +/// The change notification. +/// The collection version right after the change. +[System.Diagnostics.DebuggerDisplay("Version = {Version}")] +public readonly record struct VersionedNotification(CacheNotify Notification, long Version); diff --git a/src/ReactiveList/Core/CacheAction.cs b/src/ReactiveList/Core/CacheAction.cs index 94b59b57..bf145ccf 100644 --- a/src/ReactiveList/Core/CacheAction.cs +++ b/src/ReactiveList/Core/CacheAction.cs @@ -42,4 +42,11 @@ public enum CacheAction /// Represents a batch removal operation where multiple items are removed at once. BatchRemoved = 8, + + /// + /// Replaces all contents with the snapshot in the batch, which may be empty. A list raises it when a deferral ends and the + /// contents changed, and on the versioned stream (without a snapshot) after a replace, an edit, a silent clear or a removal + /// by predicate. A consumer that sees it without a snapshot must copy the source again. + /// + Reset = 9, } diff --git a/src/ReactiveList/Core/CacheNotifyExtensions.cs b/src/ReactiveList/Core/CacheNotifyExtensions.cs index 394f36d9..986027c9 100644 --- a/src/ReactiveList/Core/CacheNotifyExtensions.cs +++ b/src/ReactiveList/Core/CacheNotifyExtensions.cs @@ -54,7 +54,7 @@ notification is null [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable> WhereAction(CacheAction action) { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); return source.Keep(n => n.Action == action); } @@ -64,7 +64,7 @@ public IObservable> WhereAction(CacheAction action) [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable> WhereAdded() { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); return source.Keep(static n => n.Action is CacheAction.Added or CacheAction.BatchAdded); } @@ -74,7 +74,7 @@ public IObservable> WhereAdded() [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable> WhereRemoved() { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); return source.Keep(static n => n.Action is CacheAction.Removed or CacheAction.BatchRemoved); } @@ -84,7 +84,7 @@ public IObservable> WhereRemoved() [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable SelectItems() { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); return source .Keep(static n => n.Item is not null) @@ -96,7 +96,7 @@ public IObservable SelectItems() [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable SelectAllItems() { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); return source.FlatMap(static n => { @@ -131,7 +131,7 @@ public IObservable SelectAllItems() [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable<(T Item, int OldIndex, int NewIndex)> OnItemMoved() { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); return source .WhereAction(CacheAction.Moved) @@ -150,7 +150,7 @@ public IObservable SelectAllItems() [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable>> BufferNotifications(TimeSpan bufferTime) { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); return source .Buffer(bufferTime) @@ -163,7 +163,7 @@ public IObservable>> BufferNotifications(TimeSpan bufferTim [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable> ThrottleNotifications(TimeSpan throttleTime) { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); return throttleTime == TimeSpan.Zero ? source : source.Throttle(throttleTime); } @@ -174,8 +174,8 @@ public IObservable> ThrottleNotifications(TimeSpan throttleTime) [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable> ObserveOnScheduler(ISequencer scheduler) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(scheduler); + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(scheduler); return source.ObserveOn(scheduler); } @@ -187,8 +187,8 @@ public IObservable> ObserveOnScheduler(ISequencer scheduler) [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable TransformItems(Func selector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(selector); return source.SelectAllItems().Map(selector); } @@ -199,8 +199,8 @@ public IObservable TransformItems(Func selector) [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable FilterItems(Func predicate) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(predicate); return source.SelectAllItems().Keep(predicate); } @@ -210,7 +210,7 @@ public IObservable FilterItems(Func predicate) [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable> AutoDisposeBatches() { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); return source.Tap(static n => n.Batch?.Dispose()); } @@ -220,7 +220,7 @@ public IObservable> AutoDisposeBatches() [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable<(CacheAction Action, int Count)> CountByAction() { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); return source.Map(static n => { @@ -234,15 +234,20 @@ public IObservable> AutoDisposeBatches() /// /// This method bridges the gap between the Stream-based notifications and ChangeSet-based processing. /// Batch operations are expanded into individual changes within the change set. - /// Clear operations emit a change set with individual Remove changes for each cleared item (consistent with DynamicData). + /// Clear operations emit a change set with individual Remove changes for each cleared item. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable> ToChangeSets() { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); return source.Map(static notification => { + if (notification.Action == CacheAction.Reset && notification.Batch is { } snapshot) + { + return ToResetChanges(snapshot); + } + if (notification.Batch is { Count: > 0 }) { var changes = new Change[notification.Batch.Count]; @@ -285,4 +290,20 @@ public IObservable> ToChangeSets() }).Where(static cs => cs.Count > 0); } } + + /// Converts a reset to one change set that clears and repopulates the downstream collection. + /// The item type. + /// The replacement contents. + /// The reset changes in application order. + internal static ChangeSet ToResetChanges(PooledBatch snapshot) + { + var changes = new Change[snapshot.Count + 1]; + changes[0] = new(ChangeReason.Clear, default!); + for (var i = 0; i < snapshot.Count; i++) + { + changes[i + 1] = Change.CreateAdd(snapshot.Items[i], i); + } + + return new(changes); + } } diff --git a/src/ReactiveList/Core/Change.cs b/src/ReactiveList/Core/Change.cs index cb29475b..705d5ed4 100644 --- a/src/ReactiveList/Core/Change.cs +++ b/src/ReactiveList/Core/Change.cs @@ -11,7 +11,6 @@ namespace ReactiveList.Core; /// The type of item that changed. /// /// This is a struct-based change notification to minimize heap allocations. -/// Compatible with DynamicData's change patterns. /// [System.Diagnostics.DebuggerDisplay("Change: {Reason}")] public readonly record struct Change diff --git a/src/ReactiveList/Core/ChangeReason.cs b/src/ReactiveList/Core/ChangeReason.cs index 9c038ebf..a6c4da75 100644 --- a/src/ReactiveList/Core/ChangeReason.cs +++ b/src/ReactiveList/Core/ChangeReason.cs @@ -9,7 +9,7 @@ namespace ReactiveList.Core; #endif /// Specifies the reason for a change in a reactive collection. /// -/// This enumeration provides a unified change reason type compatible with DynamicData patterns. +/// This enumeration provides a unified change reason type. /// Use this to identify the type of modification that occurred in a collection. /// public enum ChangeReason diff --git a/src/ReactiveList/Core/ChangeSet.cs b/src/ReactiveList/Core/ChangeSet.cs index d632e146..faf991b4 100644 --- a/src/ReactiveList/Core/ChangeSet.cs +++ b/src/ReactiveList/Core/ChangeSet.cs @@ -7,7 +7,7 @@ namespace ReactiveList.Reactive.Core; #else namespace ReactiveList.Core; #endif -/// Represents a set of changes to a collection, compatible with DynamicData patterns. +/// Represents a set of changes to a collection. /// The type of items in the collection. /// /// This struct stores changes in a compact array. The disposable contract is retained for binary compatibility. @@ -32,17 +32,13 @@ public ChangeSet(Change change) } /// Initializes a new instance of the struct from an array. - /// The changes array. This array is not copied on .NET Framework. + /// The changes array, which is copied. public ChangeSet(Change[] changes) { - ThrowHelper.ThrowIfNull(changes); + ArgumentExceptionHelper.ThrowIfNull(changes); -#if NET6_0_OR_GREATER _changes = new Change[changes.Length]; changes.CopyTo(_changes, 0); -#else - _changes = changes; -#endif Count = changes.Length; } @@ -96,11 +92,7 @@ public Change this[int index] /// Returns a hash code for this instance. /// A hash code for this instance. -#if NET6_0_OR_GREATER - public override int GetHashCode() => HashCode.Combine(_changes, Count); -#else - public override int GetHashCode() => (_changes?.GetHashCode() ?? 0) ^ Count; -#endif + public override int GetHashCode() => HashCodeCompat.CombineArrayAndCount(_changes, Count); /// Returns an enumerator that iterates through the changes. /// An enumerator for the change set. @@ -144,10 +136,8 @@ private int CountByReason(ChangeReason reason) [System.Diagnostics.DebuggerDisplay("Enumerator: {Current}")] public struct Enumerator : IEnumerator>, IEquatable { -#if NETFRAMEWORK /// The multiplier used to combine legacy hash-code components. private const int EqualityHashMultiplier = 397; -#endif /// The array being enumerated. private readonly Change[] _changes; @@ -212,26 +202,11 @@ public readonly bool Equals(Enumerator other) => public override readonly bool Equals(object? obj) => obj is Enumerator other && Equals(other); /// - public override readonly int GetHashCode() => -#if NET6_0_OR_GREATER - HashCode.Combine(_changes, _count); -#else - GetLegacyEqualityHashCode(); -#endif + public override readonly int GetHashCode() => HashCodeCompat.CombineArrayAndCount(_changes, _count, EqualityHashMultiplier); /// Releases resources used by the enumerator. public readonly void Dispose() { } - -#if !NET6_0_OR_GREATER - /// Computes an equality hash code on target frameworks without the built-in hash combiner. - /// A hash code for the current source and enumeration state. - private readonly int GetLegacyEqualityHashCode() - { - var hashCode = _changes?.GetHashCode() ?? 0; - return (hashCode * EqualityHashMultiplier) ^ _count; - } -#endif } } diff --git a/src/ReactiveList/Core/ReactiveGroup.cs b/src/ReactiveList/Core/ReactiveGroup.cs index f7db0ea7..9fccfd60 100644 --- a/src/ReactiveList/Core/ReactiveGroup.cs +++ b/src/ReactiveList/Core/ReactiveGroup.cs @@ -7,6 +7,7 @@ namespace ReactiveList.Reactive.Core; #else namespace ReactiveList.Core; #endif + /// Represents a group of items with a key for use in grouped views. /// The type of the grouping key. /// The type of elements in the group. @@ -31,7 +32,7 @@ public sealed class ReactiveGroup : IGrouping, INotifyCollecti /// The items in the group. public ReactiveGroup(TKey key, ObservableCollection items) { - ThrowHelper.ThrowIfNull(items); + ArgumentExceptionHelper.ThrowIfNull(items); Key = key; _items = items; diff --git a/src/ReactiveList/Core/SecondaryIndex.cs b/src/ReactiveList/Core/SecondaryIndex.cs index d966af81..e4d72a44 100644 --- a/src/ReactiveList/Core/SecondaryIndex.cs +++ b/src/ReactiveList/Core/SecondaryIndex.cs @@ -11,8 +11,13 @@ namespace ReactiveList.Core; /// The type of items to be indexed. /// The type of the key used for indexing. Must be non-nullable. /// A function that extracts the secondary key from an item. +/// +/// The index is a multiset: an item added twice is returned twice by and must be removed twice. +/// The key is computed when an item is added. If an item's key changes afterwards, still finds +/// and removes the stale entry, but lookups reflect the key the item had when it was added. +/// [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] -public class SecondaryIndex(Func selector) : ISecondaryIndex +public sealed class SecondaryIndex(Func selector) : ISecondaryIndex where TKey : notnull { /// The fixed number of independently locked shards. @@ -27,7 +32,7 @@ public class SecondaryIndex(Func selector) : ISecondaryIndexThe hash buckets used to partition indexed values. + /// The hash buckets used to partition indexed values; each key maps to the distinct items stored under it. private readonly Dictionary>[] _shards = [ [], @@ -36,6 +41,9 @@ public class SecondaryIndex(Func selector) : ISecondaryIndexThe extra copies of items stored more than once, per shard, created when the first duplicate arrives. + private Dictionary>?[]? _extras; + /// Adds the specified item to the collection. /// The item to add. [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -46,20 +54,15 @@ public void OnAdded(T item) lock (_locks[s]) { -#if NET8_0_OR_GREATER - ref var set = ref CollectionsMarshal.GetValueRefOrAddDefault(_shards[s], key, out _); - set ??= []; - _ = set.Add(item); -#else var shard = _shards[s]; if (!shard.TryGetValue(key, out var set)) { - set = []; - shard[key] = set; + AddFirst(shard, key, item); + } + else if (!set.Add(item)) + { + AddExtraCopy(s, key, item); } - - _ = set.Add(item); -#endif } } @@ -73,18 +76,13 @@ public void OnRemoved(T item) lock (_locks[s]) { - var shard = _shards[s]; - if (!shard.TryGetValue(key, out var set)) + if (RemoveFromShard(s, key, item)) { return; } - - _ = set.Remove(item); - if (set.Count == 0) - { - _ = shard.Remove(key); - } } + + RemoveUnderStaleKey(item); } /// Handles the update of an item. @@ -98,13 +96,22 @@ public void OnUpdated(T oldItem, T newItem) /// Retrieves all values associated with the specified key. /// The key to look up. - /// An enumerable of items matching the key. + /// An enumerable of items matching the key, repeating an item once per copy. public IEnumerable Lookup(TKey key) { var s = GetShardIndex(key); lock (_locks[s]) { - return _shards[s].TryGetValue(key, out var set) ? [.. set] : []; + if (!_shards[s].TryGetValue(key, out var set)) + { + return []; + } + + var extra = GetExtraCopies(s, key); + var result = new T[set.Count + (extra?.Total ?? 0)]; + set.CopyTo(result); + extra?.CopyTo(result, set.Count); + return result; } } @@ -116,6 +123,7 @@ public void Clear() lock (_locks[i]) { _shards[i].Clear(); + Volatile.Read(ref _extras)?[i]?.Clear(); } } } @@ -124,16 +132,14 @@ public void Clear() /// The item whose key should be compared. /// The key to compare against. Must be of type . /// if the item's key matches the specified key; otherwise, . - public bool MatchesKey(T item, object key) - { - if (key is not TKey typedKey) - { - return false; - } + public bool MatchesKey(T item, object key) => key is TKey typedKey && MatchesTypedKey(item, typedKey); - var itemKey = selector(item); - return EqualityComparer.Default.Equals(itemKey, typedKey); - } + /// Determines whether the item's key equals without boxing the key. + /// The item whose key should be compared. + /// The key to compare against. + /// if the item's key matches the specified key; otherwise, . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal bool MatchesTypedKey(T item, TKey key) => EqualityComparer.Default.Equals(selector(item), key); /// Calculates the shard index for the specified key. /// The key for which to compute the shard index. @@ -141,4 +147,181 @@ public bool MatchesKey(T item, object key) /// to 3. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int GetShardIndex(TKey item) => ShardHash.GetShardIndex4(item); + + /// Stores the first item under a key; nothing is stored when hashing the item throws. + /// The shard dictionary, which the caller has locked. + /// The key of the new bucket. + /// The item to add. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void AddFirst(Dictionary> shard, TKey key, T item) + { + HashSet created = []; + _ = created.Add(item); + shard[key] = created; + } + + /// Counts one more copy of an item that the set of its key already holds. + /// The shard the key belongs to; the caller holds its gate. + /// The key of the item. + /// The item that was added again. + [MethodImpl(MethodImplOptions.NoInlining)] + private void AddExtraCopy(int s, TKey key, T item) + { + var extras = Volatile.Read(ref _extras); + if (extras is null) + { + Dictionary>?[] created = [null, null, null, null]; + _ = Interlocked.CompareExchange(ref _extras, created, null); + extras = Volatile.Read(ref _extras)!; + } + + var shardExtras = extras[s] ??= []; + DictionaryCompat.Increment(DictionaryCompat.GetOrAdd(shardExtras, key), new(item)); + } + + /// Gets the extra copies stored under a key. + /// The shard the key belongs to; the caller holds its gate. + /// The key to look up. + /// The extra copies, or when no item under the key is stored more than once. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private ExtraCopies? GetExtraCopies(int s, TKey key) + { + var shardExtras = Volatile.Read(ref _extras)?[s]; + return shardExtras is not null && shardExtras.TryGetValue(key, out var copies) ? new(copies) : null; + } + + /// Removes one copy of an item from the bucket of a key, dropping the bucket when it empties. + /// The shard the key belongs to; the caller holds its gate. + /// The key whose bucket holds the item. + /// The item to remove. + /// when a copy was found and removed. + private bool RemoveFromShard(int s, TKey key, T item) + { + var shard = _shards[s]; + if (!shard.TryGetValue(key, out var set)) + { + return false; + } + + if (Volatile.Read(ref _extras) is not null && RemoveExtraCopy(s, key, item)) + { + return true; + } + + if (!set.Remove(item)) + { + return false; + } + + if (set.Count == 0) + { + _ = shard.Remove(key); + } + + return true; + } + + /// Removes one extra copy of an item, if the item is stored more than once. + /// The shard the key belongs to; the caller holds its gate. + /// The key of the item. + /// The item to remove. + /// when an extra copy was found and removed. + [MethodImpl(MethodImplOptions.NoInlining)] + private bool RemoveExtraCopy(int s, TKey key, T item) + { + var shardExtras = Volatile.Read(ref _extras)?[s]; + if (shardExtras is null || !shardExtras.TryGetValue(key, out var copies)) + { + return false; + } + + var wrapped = new ItemKey(item); + if (!copies.TryGetValue(wrapped, out var count)) + { + return false; + } + + if (count > 1) + { + copies[wrapped] = count - 1; + return true; + } + + _ = copies.Remove(wrapped); + if (copies.Count == 0) + { + _ = shardExtras.Remove(key); + } + + return true; + } + + /// Finds and removes one copy of an item whose key changed after it was added. + /// The item to remove. + private void RemoveUnderStaleKey(T item) + { + for (var s = 0; s < ShardCount; s++) + { + lock (_locks[s]) + { + foreach (var pair in _shards[s]) + { + if (!pair.Value.Contains(item)) + { + continue; + } + + _ = RemoveFromShard(s, pair.Key, item); + return; + } + } + } + } + + /// Wraps an item so it can key a dictionary even when allows null. + /// The wrapped item. + private readonly record struct ItemKey(T Value) + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Equals(ItemKey other) => EqualityComparer.Default.Equals(Value, other.Value); + + /// + public override int GetHashCode() => Value is null ? 0 : EqualityComparer.Default.GetHashCode(Value); + } + + /// Reads the extra copies stored under one key. + /// How many copies beyond the first each repeated item has. + private readonly record struct ExtraCopies(Dictionary Copies) + { + /// Gets the number of extra copies. + internal int Total + { + get + { + var total = 0; + foreach (var pair in Copies) + { + total += pair.Value; + } + + return total; + } + } + + /// Writes every extra copy into an array. + /// The array to fill. + /// The position of the first copy. + internal void CopyTo(T[] destination, int offset) + { + foreach (var pair in Copies) + { + for (var i = 0; i < pair.Value; i++) + { + destination[offset] = pair.Key.Value; + offset++; + } + } + } + } } diff --git a/src/ReactiveList/Internal/ArrayCompat.cs b/src/ReactiveList/Internal/ArrayCompat.cs new file mode 100644 index 00000000..c3e506f2 --- /dev/null +++ b/src/ReactiveList/Internal/ArrayCompat.cs @@ -0,0 +1,25 @@ +// 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 + +/// Provides array operations that need a different implementation on .NET Framework. +internal static class ArrayCompat +{ + /// Creates an array whose every element the caller writes before the array is read or returned. + /// The item type. + /// The number of elements. + /// An array that may hold old memory until the caller fills it. Arrays of references are always cleared. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static T[] AllocateForFullOverwrite(int length) => +#if NETFRAMEWORK + new T[length]; +#else + GC.AllocateUninitializedArray(length); +#endif +} diff --git a/src/ReactiveList/Internal/AutoRefreshSubscription.cs b/src/ReactiveList/Internal/AutoRefreshSubscription.cs new file mode 100644 index 00000000..4772823e --- /dev/null +++ b/src/ReactiveList/Internal/AutoRefreshSubscription.cs @@ -0,0 +1,410 @@ +// 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 + +/// +/// Watches on every item that a change-set stream currently holds and emits a refresh for each +/// relevant property change. A handler is attached when an item is added or swapped in and detached as soon as the item is removed, replaced or cleared, +/// when the source ends, or when the subscription is disposed. +/// +/// The item type. +internal sealed class AutoRefreshSubscription : IObserver>, IDisposable + where T : INotifyPropertyChanged +{ + /// The property to watch, or or empty to watch every property. + private readonly string? _propertyName; + + /// The downstream observer; only called by the thread that owns delivery. + private readonly IObserver> _observer; + + /// Guards the watch table, the pending queue and the lifecycle flags. + private readonly Lock _gate = new(); + + /// The watched items, compared by reference, so equal but distinct items are watched separately. + private readonly Dictionary _watches = [with(ReferenceComparer.Instance)]; + + /// The notifications waiting for the delivering thread. + private readonly Queue _pending = []; + + /// The subscription to the source. + private IDisposable? _sourceSubscription; + + /// Whether a thread is currently delivering notifications. + private bool _delivering; + + /// Whether the subscription ended through disposal, completion or error. + private bool _finished; + + /// Initializes a new instance of the class. + /// The downstream observer. + /// The property to watch, or or empty to watch every property. + internal AutoRefreshSubscription(IObserver> observer, string? propertyName) + { + _observer = observer; + _propertyName = propertyName; + } + + /// + public void OnNext(ChangeSet value) + { + lock (_gate) + { + if (_finished) + { + return; + } + + ApplyChanges(value); + _pending.Enqueue(new(value, null, false)); + } + + Drain(); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnError(Exception error) => Finish(new(default, error, false)); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted() => Finish(new(default, null, true)); + + /// + public void Dispose() + { + IDisposable? sourceSubscription; + List detached; + lock (_gate) + { + if (_finished) + { + return; + } + + _finished = true; + _pending.Clear(); + sourceSubscription = _sourceSubscription; + _sourceSubscription = null; + detached = TakeAllWatches(); + } + + Detach(detached); + sourceSubscription?.Dispose(); + } + + /// Connects the subscription to its source. + /// The change-set stream. + internal void Connect(IObservable> source) + { + var subscription = source.Subscribe(this); + bool finished; + lock (_gate) + { + finished = _finished; + if (!finished) + { + _sourceSubscription = subscription; + } + } + + if (finished) + { + subscription.Dispose(); + } + } + + /// Detaches the handlers of several watches. + /// The watches. + private static void Detach(List watches) + { + for (var i = 0; i < watches.Count; i++) + { + Detach(watches[i]); + } + } + + /// Detaches the handler of one watch. + /// The watch. + private static void Detach(Watch watch) => watch.Item.PropertyChanged -= watch.Handler; + + /// Ends the subscription with a terminal notification and detaches every handler. + /// The terminal notification. + private void Finish(in Pending terminal) + { + IDisposable? sourceSubscription; + List detached; + lock (_gate) + { + if (_finished) + { + return; + } + + _finished = true; + sourceSubscription = _sourceSubscription; + _sourceSubscription = null; + detached = TakeAllWatches(); + _pending.Enqueue(terminal); + } + + Detach(detached); + sourceSubscription?.Dispose(); + Drain(); + } + + /// Applies the watch bookkeeping for a change set; call with the gate held. + /// The changes. + private void ApplyChanges(ChangeSet changes) + { + for (var i = 0; i < changes.Count; i++) + { + var change = changes[i]; + switch (change.Reason) + { + case ChangeReason.Add: + { + Attach(change.Current, change.CurrentIndex); + break; + } + + case ChangeReason.Update: + { + ApplyUpdate(change); + break; + } + + case ChangeReason.Remove: + { + Release(change.Current); + break; + } + + case ChangeReason.Clear: + { + Detach(TakeAllWatches()); + break; + } + + default: + { + break; + } + } + } + } + + /// Moves a watch from the replaced item to the new one; call with the gate held. + /// The update change. + private void ApplyUpdate(in Change change) + { + // Updating an item with itself neither adds nor removes an occurrence, but the item may not have been seen before. + if (change.Previous is not null && ReferenceEquals(change.Previous, change.Current)) + { + if (_watches.TryGetValue(change.Current, out var same)) + { + same.Index = change.CurrentIndex; + return; + } + + Attach(change.Current, change.CurrentIndex); + return; + } + + // The new item is attached before the old one is released so neither is ever left without its handler. + Attach(change.Current, change.CurrentIndex); + if (change.Previous is not null) + { + Release(change.Previous); + } + } + + /// Starts watching an item, or counts another occurrence of an item that is already watched; call with the gate held. + /// The item. + /// The index to report in refreshes. + private void Attach(T item, int index) + { + object key = item; + if (_watches.TryGetValue(key, out var existing)) + { + existing.Count++; + existing.Index = index; + return; + } + + var watch = new Watch(item, index); + watch.Handler = (_, args) => OnItemPropertyChanged(watch, args); + _watches[key] = watch; + item.PropertyChanged += watch.Handler; + } + + /// Stops counting one occurrence of an item and detaches its handler when none remain; call with the gate held. + /// The item. + private void Release(T item) + { + object key = item; + if (!_watches.TryGetValue(key, out var watch)) + { + return; + } + + watch.Count--; + if (watch.Count > 0) + { + return; + } + + _ = _watches.Remove(key); + Detach(watch); + } + + /// Removes every watch from the table; call with the gate held. + /// The removed watches, whose handlers the caller must detach. + private List TakeAllWatches() + { + var all = new List(_watches.Count); + foreach (var watch in _watches.Values) + { + all.Add(watch); + } + + _watches.Clear(); + return all; + } + + /// Queues a refresh when a watched item raises a relevant property change. + /// The watch that raised the event. + /// The event arguments. + private void OnItemPropertyChanged(Watch watch, PropertyChangedEventArgs args) + { + if (!IsRelevant(args)) + { + return; + } + + lock (_gate) + { + if (_finished || !_watches.TryGetValue(watch.Item, out var current) || !ReferenceEquals(current, watch)) + { + return; + } + + _pending.Enqueue(new(new(Change.CreateRefresh(watch.Item, watch.Index)), null, false)); + } + + Drain(); + } + + /// Tests whether a property change matches the watched property. + /// The event arguments. + /// when a refresh should be emitted. + private bool IsRelevant(PropertyChangedEventArgs args) => + string.IsNullOrEmpty(_propertyName) + || string.IsNullOrEmpty(args.PropertyName) + || string.Equals(args.PropertyName, _propertyName, StringComparison.Ordinal); + + /// Delivers queued notifications one thread at a time, outside the gate, so the downstream observer sees a serialized sequence. + private void Drain() + { + lock (_gate) + { + if (_delivering) + { + return; + } + + _delivering = true; + } + + while (true) + { + Pending next; + lock (_gate) + { + if (_pending.Count == 0) + { + _delivering = false; + return; + } + + next = _pending.Dequeue(); + } + + try + { + Deliver(in next); + } + catch + { + lock (_gate) + { + _delivering = false; + } + + throw; + } + } + } + + /// Sends one notification to the downstream observer. + /// The notification. + private void Deliver(in Pending notification) + { + if (notification.Error is not null) + { + _observer.OnError(notification.Error); + } + else if (notification.Completed) + { + _observer.OnCompleted(); + } + else + { + _observer.OnNext(notification.Changes); + } + } + + /// A notification waiting to be delivered. + /// The change set for a value notification. + /// The error for an error notification. + /// Whether this is the completion notification. + private readonly record struct Pending(ChangeSet Changes, Exception? Error, bool Completed); + + /// Compares objects by reference. + private sealed class ReferenceComparer : IEqualityComparer + { + /// Gets the shared instance. + internal static readonly ReferenceComparer Instance = new(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + bool IEqualityComparer.Equals(object? x, object? y) => ReferenceEquals(x, y); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + int IEqualityComparer.GetHashCode(object obj) => RuntimeHelpers.GetHashCode(obj); + } + + /// The handler and bookkeeping for one watched item. + /// The watched item. + /// The index reported in refreshes. + private sealed class Watch(T item, int index) + { + /// Gets the watched item. + internal T Item { get; } = item; + + /// Gets or sets the number of times the item occurs in the source. + internal int Count { get; set; } = 1; + + /// Gets or sets the index reported in refreshes. + internal int Index { get; set; } = index; + + /// Gets or sets the attached handler. + internal PropertyChangedEventHandler Handler { get; set; } = static (_, _) => { }; + } +} diff --git a/src/ReactiveList/Internal/BatchFilterHelper.cs b/src/ReactiveList/Internal/BatchFilterHelper.cs index f32da17f..fe5fc2e6 100644 --- a/src/ReactiveList/Internal/BatchFilterHelper.cs +++ b/src/ReactiveList/Internal/BatchFilterHelper.cs @@ -24,8 +24,8 @@ internal static class BatchFilterHelper Func predicate) where T : notnull { - ThrowHelper.ThrowIfNull(notification); - ThrowHelper.ThrowIfNull(predicate); + ArgumentExceptionHelper.ThrowIfNull(notification); + ArgumentExceptionHelper.ThrowIfNull(predicate); if (notification.Batch is null) { @@ -42,7 +42,7 @@ internal static class BatchFilterHelper } } - if (matchCount == 0) + if (matchCount == 0 && notification.Action != CacheAction.Reset) { return null; } @@ -64,7 +64,8 @@ internal static class BatchFilterHelper PooledBatch? filteredBatch = new(filteredItems, filteredItems.Length, ReturnToPool: false); try { - var filteredNotification = new CacheNotify(CacheAction.BatchOperation, default, filteredBatch); + var action = BatchAction(notification.Action); + var filteredNotification = new CacheNotify(action, default, filteredBatch); filteredBatch = null; return filteredNotification; } @@ -87,8 +88,8 @@ internal static IObservable> FilterNotificationStream( Func predicate) where T : notnull { - ThrowHelper.ThrowIfNull(stream); - ThrowHelper.ThrowIfNull(predicate); + ArgumentExceptionHelper.ThrowIfNull(stream); + ArgumentExceptionHelper.ThrowIfNull(predicate); return stream .Map(notification => FilterNotification(notification, state, predicate)) @@ -109,17 +110,23 @@ internal static IObservable> FilterNotificationStream( Func predicate) where T : notnull { - ThrowHelper.ThrowIfNull(notification); - ThrowHelper.ThrowIfNull(predicate); + ArgumentExceptionHelper.ThrowIfNull(notification); + ArgumentExceptionHelper.ThrowIfNull(predicate); return notification.Action switch { CacheAction.Cleared => notification, CacheAction.Added or CacheAction.Removed when notification.Item is { } item && predicate(item, state) => notification, - CacheAction.BatchAdded or CacheAction.BatchRemoved or CacheAction.BatchOperation + CacheAction.BatchAdded or CacheAction.BatchRemoved or CacheAction.BatchOperation or CacheAction.Reset when notification.Batch is not null => FilterBatch(notification, state, predicate), _ => null }; } + + /// Gets the action to use for a narrowed batch. + /// The original action. + /// The action of the filtered notification. + private static CacheAction BatchAction(CacheAction action) => + action is CacheAction.BatchAdded or CacheAction.BatchRemoved or CacheAction.Reset ? action : CacheAction.BatchOperation; } diff --git a/src/ReactiveList/Internal/BatchObservableCollection.cs b/src/ReactiveList/Internal/BatchObservableCollection.cs new file mode 100644 index 00000000..04c4e2b9 --- /dev/null +++ b/src/ReactiveList/Internal/BatchObservableCollection.cs @@ -0,0 +1,508 @@ +// 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 +{ + /// The number of changed positions above which the live query engine replaces its contents with one reset notification. Views use . + 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); + + /// Serializes reads with storage writes for facades that publish snapshots. + private readonly Lock? _readGate; + + /// The captured array, if the current contents have been enumerated. + private T[]? _readSnapshot; + + /// Whether changes are applied without notifications until . + private bool _quiet; + + /// Whether a change was applied while quiet. + private bool _changedWhileQuiet; + + /// Initializes a new instance of the class. + internal BatchObservableCollection() + { + } + + /// Initializes a new instance of the class. + /// Whether the facade can read from other threads. + internal BatchObservableCollection(bool synchronizeReads) => _readGate = synchronizeReads ? new() : null; + + /// Gets or sets the gate the owner closes on disposal, after which no change is applied and no notification is raised, or when changes are never stopped. + internal DisposalGate? Gate { get; set; } + + /// Gets or sets the number of changes above which one operation raises a single reset instead of one notification per change. + internal int ResetLimit { get; set; } = int.MaxValue; + + /// Copies the items as they exist at one point in time. + /// The copied items. + internal T[] CopySnapshot() + { + lock (_readGate!) + { + return _readSnapshot ??= [.. Items]; + } + } + + /// Finds the last occurrence of an item, preferring reference identity over value equality. + /// The item to find. + /// The index, or -1. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal int FindLast(T item) => ItemComparison.FindLastIndex(Items, item); + + /// Finds the last occurrence of an item with a caller-supplied comparer. + /// The item to find. + /// The comparer that decides equality. + /// The index, or -1. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal int FindLast(T item, IEqualityComparer comparer) => ItemComparison.FindLastIndex(Items, item, comparer); + + /// Reads the number of stored items independently of the dispatcher. + /// The number of items. + internal int ReadCount() + { + lock (_readGate!) + { + return Items.Count; + } + } + + /// Reads one stored item independently of the dispatcher. + /// The index of the item. + /// The item at the index. + internal T ReadAt(int index) + { + lock (_readGate!) + { + return Items[index]; + } + } + + /// Starts applying one batch of changes, silently when the batch is larger than . + /// The number of items in the batch. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void BeginBatch(int size) => _quiet = size > ResetLimit; + + /// Starts applying changes silently until , for a collection created while a larger batch is being applied. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void BeginQuiet() => _quiet = true; + + /// Finishes a batch and raises the single reset when the batch was applied silently. + internal void EndBatch() + { + if (!_quiet) + { + return; + } + + _quiet = false; + if (!_changedWhileQuiet) + { + return; + } + + _changedWhileQuiet = false; + if (Gate is { } gate && !gate.TryEnter()) + { + return; + } + + try + { + OnPropertyChanged(CountChangedArgs); + OnPropertyChanged(IndexerChangedArgs); + OnCollectionChanged(ResetArgs); + } + finally + { + ExitGate(); + } + } + + /// Fills an empty collection without raising any event, for an owner that has not handed the collection to anyone yet. + /// The initial contents. + internal void Populate(ICollection items) + { + // The parameterless base constructor always stores the items in a List. + ((List)Items).AddRange(items); + } + + /// Appends an item without raising any event, for an owner that has not handed the collection to anyone yet. + /// The item to append. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void AddQuietly(T item) => Items.Add(item); + + /// 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 (!ItemComparison.SameItem(this[i], target[i])) + { + differences++; + } + } + + differences += Math.Abs(target.Count - Count); + if (differences > ResetLimit) + { + ReplaceAll(target); + return; + } + + for (var i = 0; i < limit; i++) + { + if (!ItemComparison.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) + { + EnterGate(); + try + { + ReplaceAllCore(items); + } + finally + { + ExitGate(); + } + } + + /// + protected override void InsertItem(int index, T item) + { + EnterGate(); + try + { + InsertCore(index, item); + } + finally + { + ExitGate(); + } + } + + /// + protected override void RemoveItem(int index) + { + EnterGate(); + try + { + RemoveCore(index); + } + finally + { + ExitGate(); + } + } + + /// + protected override void SetItem(int index, T item) + { + EnterGate(); + try + { + SetCore(index, item); + } + finally + { + ExitGate(); + } + } + + /// + protected override void MoveItem(int oldIndex, int newIndex) + { + EnterGate(); + try + { + MoveCore(oldIndex, newIndex); + } + finally + { + ExitGate(); + } + } + + /// + protected override void ClearItems() + { + EnterGate(); + try + { + ClearCore(); + } + finally + { + ExitGate(); + } + } + + /// Starts a change, throwing when the owner closed the gate so the drain applying it stops. + /// The gate is closed. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void EnterGate() => ObjectDisposedExceptionHelper.ThrowIf(Gate is { } gate && !gate.TryEnter(), this); + + /// Ends a change started by . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ExitGate() => Gate?.Exit(); + + /// Inserts an item. + /// The index. + /// The item. + private void InsertCore(int index, T item) + { + if (_readGate is not null) + { + // The base mutation raises events inline. Change only storage under the gate and notify after releasing it. + CheckReentrancy(); + lock (_readGate) + { + Items.Insert(index, item); + _readSnapshot = null; + } + + if (!_quiet) + { + ReportStorageChange(new(NotifyCollectionChangedAction.Add, item, index), countChanged: true); + return; + } + + _changedWhileQuiet = true; + return; + } + + if (!_quiet) + { + base.InsertItem(index, item); + return; + } + + Items.Insert(index, item); + _changedWhileQuiet = true; + } + + /// Removes an item. + /// The index. + private void RemoveCore(int index) + { + if (_readGate is not null) + { + CheckReentrancy(); + T removed; + lock (_readGate) + { + removed = Items[index]; + Items.RemoveAt(index); + _readSnapshot = null; + } + + if (!_quiet) + { + ReportStorageChange(new(NotifyCollectionChangedAction.Remove, removed, index), countChanged: true); + return; + } + + _changedWhileQuiet = true; + return; + } + + if (!_quiet) + { + base.RemoveItem(index); + return; + } + + Items.RemoveAt(index); + _changedWhileQuiet = true; + } + + /// Replaces an item. + /// The index. + /// The item. + private void SetCore(int index, T item) + { + if (_readGate is not null) + { + CheckReentrancy(); + T previous; + lock (_readGate) + { + previous = Items[index]; + Items[index] = item; + _readSnapshot = null; + } + + if (!_quiet) + { + ReportStorageChange(new(NotifyCollectionChangedAction.Replace, item, previous, index), countChanged: false); + return; + } + + _changedWhileQuiet = true; + return; + } + + if (!_quiet) + { + base.SetItem(index, item); + return; + } + + Items[index] = item; + _changedWhileQuiet = true; + } + + /// Moves an item. + /// The old index. + /// The new index. + private void MoveCore(int oldIndex, int newIndex) + { + if (_readGate is not null) + { + CheckReentrancy(); + T moved; + lock (_readGate) + { + moved = Items[oldIndex]; + _readSnapshot = null; + Items.RemoveAt(oldIndex); + Items.Insert(newIndex, moved); + } + + if (!_quiet) + { + ReportStorageChange(new(NotifyCollectionChangedAction.Move, moved, newIndex, oldIndex), countChanged: false); + return; + } + + _changedWhileQuiet = true; + return; + } + + if (!_quiet) + { + base.MoveItem(oldIndex, newIndex); + return; + } + + var item = Items[oldIndex]; + Items.RemoveAt(oldIndex); + Items.Insert(newIndex, item); + _changedWhileQuiet = true; + } + + /// Removes every item. + private void ClearCore() + { + if (_readGate is not null) + { + CheckReentrancy(); + lock (_readGate) + { + Items.Clear(); + _readSnapshot = null; + } + + if (!_quiet) + { + ReportStorageChange(ResetArgs, countChanged: true); + return; + } + + _changedWhileQuiet = true; + return; + } + + if (!_quiet) + { + base.ClearItems(); + return; + } + + Items.Clear(); + _changedWhileQuiet = true; + } + + /// Replaces every element with the supplied items and raises one reset notification. + /// The replacement items. + private void ReplaceAllCore(List items) + { + CheckReentrancy(); + if (_readGate is not null) + { + lock (_readGate) + { + _readSnapshot = null; + ReplaceStorage(items); + } + } + else + { + ReplaceStorage(items); + } + + ReportStorageChange(ResetArgs, countChanged: true); + } + + /// Replaces the underlying items without raising events. + /// The replacement items. + private void ReplaceStorage(List items) + { + Items.Clear(); + for (var i = 0; i < items.Count; i++) + { + Items.Add(items[i]); + } + } + + /// Publishes a storage mutation after releasing the read lock. + /// The change event. + /// Whether to report that the count changed. + private void ReportStorageChange(NotifyCollectionChangedEventArgs args, bool countChanged) + { + if (countChanged) + { + OnPropertyChanged(CountChangedArgs); + } + + OnPropertyChanged(IndexerChangedArgs); + OnCollectionChanged(args); + } +} diff --git a/src/ReactiveList/Internal/CacheActionHelper.cs b/src/ReactiveList/Internal/CacheActionHelper.cs index 2e0ca987..d17e833e 100644 --- a/src/ReactiveList/Internal/CacheActionHelper.cs +++ b/src/ReactiveList/Internal/CacheActionHelper.cs @@ -15,5 +15,5 @@ internal static class CacheActionHelper /// The cache action to inspect. /// Whether the projection must be rebuilt from its source. internal static bool RequiresIndexRebuild(CacheAction action) => - action is CacheAction.Moved or CacheAction.Refreshed or CacheAction.BatchOperation or CacheAction.BatchAdded or CacheAction.BatchRemoved; + action is CacheAction.Moved or CacheAction.Refreshed or CacheAction.BatchOperation or CacheAction.BatchAdded or CacheAction.BatchRemoved or CacheAction.Reset; } diff --git a/src/ReactiveList/Internal/DictionaryCompat.cs b/src/ReactiveList/Internal/DictionaryCompat.cs new file mode 100644 index 00000000..499cbbf6 --- /dev/null +++ b/src/ReactiveList/Internal/DictionaryCompat.cs @@ -0,0 +1,80 @@ +// 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 + +/// Updates dictionaries without a second lookup when the runtime supports it. +internal static class DictionaryCompat +{ + /// Gets a value or adds a new one when the key is missing. + /// The key type. + /// The value type. + /// The entries. + /// The key to look up. + /// The existing or newly added value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static TValue GetOrAdd(Dictionary dictionary, TKey key) + where TKey : notnull + where TValue : class, new() + { +#if NETFRAMEWORK + if (!dictionary.TryGetValue(key, out var value)) + { + value = new(); + dictionary.Add(key, value); + } + + return value; +#else + return CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out _) ??= new(); +#endif + } + + /// Increments a key's count, starting from zero if the key is missing. + /// The key type. + /// The counts. + /// The key to count. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void Increment(Dictionary counts, TKey key) + where TKey : notnull + { +#if NETFRAMEWORK + counts[key] = counts.TryGetValue(key, out var count) ? count + 1 : 1; +#else + CollectionsMarshal.GetValueRefOrAddDefault(counts, key, out _)++; +#endif + } + + /// Consumes one occurrence from the requested counts. + /// The key type. + /// The temporary counts for one removal operation. + /// The key to check. + /// Whether there was a remaining occurrence. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool TryConsume(Dictionary counts, TKey key) + where TKey : notnull + { +#if NETFRAMEWORK + if (!counts.TryGetValue(key, out var count) || count == 0) + { + return false; + } + + counts[key] = count - 1; +#else + ref var count = ref CollectionsMarshal.GetValueRefOrNullRef(counts, key); + if (Unsafe.IsNullRef(ref count) || count == 0) + { + return false; + } + + count--; +#endif + return true; + } +} diff --git a/src/ReactiveList/Internal/DisposalGate.cs b/src/ReactiveList/Internal/DisposalGate.cs new file mode 100644 index 00000000..2ff152fb --- /dev/null +++ b/src/ReactiveList/Internal/DisposalGate.cs @@ -0,0 +1,95 @@ +// 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 + +/// +/// Lets an owner stop work that runs on another thread without waiting for it. Work runs between and +/// . Once has returned, always fails, so no new unit of work starts. +/// +/// +/// When returns, no unit of work is running on another thread and none can start, so nothing runs after disposal. +/// It skips the wait when the calling thread is inside a unit, so disposing from a handler raised by a unit, or from the +/// scheduler thread, returns at once. Units must stay short, because waits for them. +/// Units never overlap on different threads: a drain owns its collections, so one thread at a time enters the gate. That lets +/// be a plain store and cost a single fence, instead of two atomic updates of a shared count. +/// +internal sealed class DisposalGate +{ + /// The nesting depth of the unit of work in progress, written only by the thread that owns the gate. + private int _depth; + + /// The managed thread id that most recently started a unit of work from depth zero. + private int _owner; + + /// Non-zero once was called. + private int _closed; + + /// Gets a value indicating whether the gate was closed. + internal bool IsClosed => Volatile.Read(ref _closed) != 0; + + /// Gets a value indicating whether no unit of work is in progress. + internal bool IsIdle => Volatile.Read(ref _depth) == 0; + + /// Starts a unit of work unless the gate is closed. + /// when the work may run, and must then be called. + internal bool TryEnter() + { + var depth = Volatile.Read(ref _depth); + if (depth == 0) + { + Volatile.Write(ref _owner, Environment.CurrentManagedThreadId); + } + else + { + Debug.Assert(Volatile.Read(ref _owner) == Environment.CurrentManagedThreadId, "A second thread entered the gate while a unit of work was running."); + } + + Volatile.Write(ref _depth, depth + 1); + + // The fence pairs with the one in Close: either this sees the closed flag or Close sees this unit. + Interlocked.MemoryBarrier(); + if (Volatile.Read(ref _closed) == 0) + { + return true; + } + + Volatile.Write(ref _depth, depth); + return false; + } + + /// Ends a unit of work started by . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void Exit() => Volatile.Write(ref _depth, Volatile.Read(ref _depth) - 1); + + /// + /// Closes the gate so that no further unit of work starts, then waits for a unit that another thread already started. + /// It does not wait when the calling thread is itself inside a unit, so disposing from a handler is safe. + /// + internal void Close() + { + // The exchange is a full fence, so the depth read below cannot be older than the flag. + _ = Interlocked.Exchange(ref _closed, 1); + if (Volatile.Read(ref _depth) == 0 || Volatile.Read(ref _owner) == Environment.CurrentManagedThreadId) + { + return; + } + + WaitUntilIdle(); + } + + /// Waits for a unit started on another thread. A unit is only a few collection operations and the events they raise, so this ends as soon as those return. + private void WaitUntilIdle() + { + SpinWait spinner = default; + while (!IsIdle) + { + spinner.SpinOnce(); + } + } +} diff --git a/src/ReactiveList/Internal/DrainState.cs b/src/ReactiveList/Internal/DrainState.cs new file mode 100644 index 00000000..1c392810 --- /dev/null +++ b/src/ReactiveList/Internal/DrainState.cs @@ -0,0 +1,85 @@ +// 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 hand-off between the thread that delivers a list's notifications and the threads that commit changes while it does. +/// The state is while a thread delivers, plus for every change queued behind it. +/// +internal static class DrainState +{ + /// The state bit that is set while a thread delivers notifications. + internal const int DrainingBit = 1; + + /// The amount a queued change adds to the state. + internal const int QueuedStep = 2; + + /// Queues an item for the thread that is delivering; call with the publishing lock held. + /// The queued item type. + /// The shared state. + /// The queue, created on first use. + /// The item to queue. + /// The state that was read last, which has set. + /// when the delivering thread released ownership first and the caller became the delivering thread. + [MethodImpl(MethodImplOptions.NoInlining)] + internal static bool QueueBehind(ref int drainState, ref Queue? pending, in TItem item, int observed) + { + // The count goes up before the item is enqueued, so a delivering thread that fails to release ownership always finds it by taking the lock. + var state = observed; + while (true) + { + var seen = Interlocked.CompareExchange(ref drainState, state + QueuedStep, state); + if (seen == state) + { + (pending ??= new()).Enqueue(item); + return false; + } + + if (seen == 0) + { + // The delivering thread released ownership between the read and the exchange, and nothing can claim it while the caller holds the lock. + Volatile.Write(ref drainState, DrainingBit); + return true; + } + + state = seen; + } + } + + /// Takes the next queued item under the lock, or releases ownership when none is left. + /// The queued item type. + /// The shared state. + /// The queue, guarded by ; null until an item was queued. + /// The publishing lock. + /// Receives the next item to deliver. + /// when the caller must deliver ; when ownership was released. + [MethodImpl(MethodImplOptions.NoInlining)] + internal static bool TakeNext(ref int drainState, ref Queue? pending, Lock gate, out TItem? next) + { + do + { + // The queue is created by a publisher under the lock after it raised the count, so it is read only while holding the lock. + lock (gate) + { + if (pending is { Count: > 0 }) + { + next = pending.Dequeue(); + _ = Interlocked.Add(ref drainState, -QueuedStep); + return true; + } + } + + // Disposal can discard the queued items after the count was seen, so the release can succeed on a later attempt. + } + while (Interlocked.CompareExchange(ref drainState, 0, DrainingBit) != DrainingBit); + + next = default; + return false; + } +} diff --git a/src/ReactiveList/Internal/DynamicFilterRelay.cs b/src/ReactiveList/Internal/DynamicFilterRelay.cs new file mode 100644 index 00000000..50e03ce7 --- /dev/null +++ b/src/ReactiveList/Internal/DynamicFilterRelay.cs @@ -0,0 +1,92 @@ +// 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 filters of a dynamic view. The first value is only recorded, so the view can start with it, and every later value +/// replaces the rules of the view's projection. One observer serves both subscriptions, so neither needs a closure or a wrapper. +/// +/// The element type. +internal sealed class DynamicFilterRelay : IObserver> + where T : notnull +{ + /// The source the rules are built for. + private readonly IReactiveSource _source; + + /// The projection that receives later filters, or while the first value is being probed. + private StreamProjection? _projection; + + /// Whether the next live value is the replay of the first value. + private bool _skipFirst; + + /// Initializes a new instance of the class. + /// The source the rules are built for. + internal DynamicFilterRelay(IReactiveSource source) => _source = source; + + /// Gets a value indicating whether a first value was recorded. + internal bool HasInitial { get; private set; } + + /// Gets the first value that was recorded. + internal Func? Initial { get; private set; } + + /// + public void OnNext(Func value) + { + if (Volatile.Read(ref _projection) is { } projection) + { + if (_skipFirst) + { + _skipFirst = false; + return; + } + + projection.SetRules(ViewSourceRules.Create(_source, value ?? AllItems)); + return; + } + + if (HasInitial) + { + return; + } + + Initial = value; + HasInitial = true; + } + + /// + public void OnError(Exception error) + { + // A failure while probing only ends the probe. A failure of the live subscription surfaces to its publisher. + if (Volatile.Read(ref _projection) is not null) + { + ExceptionDispatchInfo.Capture(error).Throw(); + } + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted() + { + } + + /// Sends every later value to a projection. + /// The projection that applies the filters. + internal void Attach(StreamProjection projection) + { + // The live subscription replays the first value again, which the projection already started with. + _skipFirst = HasInitial; + Volatile.Write(ref _projection, projection); + } + + /// Accepts every element. + /// The element. + /// Always . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool AllItems(T item) => true; +} diff --git a/src/ReactiveList/Internal/DynamicFilterSubscription.cs b/src/ReactiveList/Internal/DynamicFilterSubscription.cs new file mode 100644 index 00000000..700b6bf3 --- /dev/null +++ b/src/ReactiveList/Internal/DynamicFilterSubscription.cs @@ -0,0 +1,115 @@ +// 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 + +/// +/// Filters a notification stream with a predicate that changes over time. The stream is subscribed to once for the lifetime of the subscription, so a +/// predicate change never opens a gap in which notifications are lost; the newest predicate is simply read for each notification. +/// +/// The item type. +internal sealed class DynamicFilterSubscription : IDisposable + where T : notnull +{ + /// The serialized downstream observer. + private readonly SerializedObserver> _observer; + + /// The subscription to the stream; set after both subscriptions exist. + private IDisposable? _streamSubscription; + + /// The subscription to the filter predicates. + private IDisposable? _filterSubscription; + + /// The predicate applied to each notification; replaced as new predicates arrive. + private Func _filter = static _ => true; + + /// Whether the subscription has been disposed or has ended; 1 once it has. + private int _ended; + + /// Initializes a new instance of the class. + /// The downstream observer. + internal DynamicFilterSubscription(IObserver> observer) => _observer = new(observer); + + /// + public void Dispose() + { + if (Interlocked.Exchange(ref _ended, 1) == 0) + { + _observer.Stop(); + } + + ReleaseSubscriptions(); + } + + /// Subscribes to the filter predicates and then to the stream. + /// The notification stream. + /// The predicates; the newest one applies. + internal void Connect(IObservable> stream, IObservable> filters) + { + // The predicates are subscribed first so a predicate that is emitted on subscription is in place before the first notification. + Volatile.Write(ref _filterSubscription, filters.Subscribe(OnFilter, Fail, static () => { })); + if (Volatile.Read(ref _ended) == 0) + { + Volatile.Write(ref _streamSubscription, stream.Subscribe(OnNotification, Fail, Complete)); + } + + // An error or disposal that raced with the subscribe calls above released nothing yet, so release now. + if (Volatile.Read(ref _ended) != 0) + { + ReleaseSubscriptions(); + } + } + + /// Ends the sequence with an error and releases both subscriptions. + /// The error. + internal void Fail(Exception error) + { + if (Interlocked.Exchange(ref _ended, 1) != 0) + { + return; + } + + _observer.OnError(error); + ReleaseSubscriptions(); + } + + /// Ends the sequence normally and releases both subscriptions. + internal void Complete() + { + if (Interlocked.Exchange(ref _ended, 1) != 0) + { + return; + } + + _observer.OnCompleted(); + ReleaseSubscriptions(); + } + + /// Stores the newest predicate. + /// The predicate. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void OnFilter(Func filter) => Volatile.Write(ref _filter, filter); + + /// Filters one notification and forwards it when it survives. + /// The notification. + private void OnNotification(CacheNotify notification) + { + var forwarded = ReactiveListExtensions.FilterNotification(notification, Volatile.Read(ref _filter)); + if (forwarded is not null) + { + _observer.OnNext(forwarded); + } + } + + /// Disposes the stream and filter subscriptions, each at most once. + private void ReleaseSubscriptions() + { + Interlocked.Exchange(ref _streamSubscription, null)?.Dispose(); + Interlocked.Exchange(ref _filterSubscription, null)?.Dispose(); + } +} diff --git a/src/ReactiveList/Internal/EnumerableExtensions.cs b/src/ReactiveList/Internal/EnumerableExtensions.cs index af746b59..e0a8355f 100644 --- a/src/ReactiveList/Internal/EnumerableExtensions.cs +++ b/src/ReactiveList/Internal/EnumerableExtensions.cs @@ -2,7 +2,7 @@ // 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 NET462 || NET47 || NET471 +#if NET47 || NET471 using System.Collections.Generic; namespace System.Linq; diff --git a/src/ReactiveList/Internal/FacadeNotificationHelper.cs b/src/ReactiveList/Internal/FacadeNotificationHelper.cs index 5555ce2a..4c8b6d01 100644 --- a/src/ReactiveList/Internal/FacadeNotificationHelper.cs +++ b/src/ReactiveList/Internal/FacadeNotificationHelper.cs @@ -11,13 +11,19 @@ namespace ReactiveList.Internal; /// Bridges observable inner-state streams onto public and facades. internal static class FacadeNotificationHelper { + /// The shared event args for a change of Count. + private static readonly PropertyChangedEventArgs CountChangedArgs = new("Count"); + + /// The shared event args for a change of the indexer. + private static readonly PropertyChangedEventArgs IndexerChangedArgs = new("Item[]"); + /// Creates a cold observable that forwards while subscribed. /// The item type in . /// The observable collection to observe. /// An observable sequence of collection-change event arguments. internal static IObservable ObserveCollectionChanges(ObservableCollection collection) { - ThrowHelper.ThrowIfNull(collection); + ArgumentExceptionHelper.ThrowIfNull(collection); return Signal.Create(observer => { @@ -35,14 +41,14 @@ internal static IObservable ObserveCollectionC /// An observable sequence of property-change event arguments. internal static IObservable ObserveCollectionPropertyChanges(ObservableCollection collection) { - ThrowHelper.ThrowIfNull(collection); + ArgumentExceptionHelper.ThrowIfNull(collection); return Signal.Create(observer => { NotifyCollectionChangedEventHandler typedHandler = (_, _) => { - observer.OnNext(new("Count")); - observer.OnNext(new("Item[]")); + observer.OnNext(CountChangedArgs); + observer.OnNext(IndexerChangedArgs); }; collection.CollectionChanged += typedHandler; return Scope.Create( @@ -63,21 +69,31 @@ internal static void AddCollectionChanged( IObservable source, NotifyCollectionChangedEventHandler? handler) { - ThrowHelper.ThrowIfNull(state); + ArgumentExceptionHelper.ThrowIfNull(state); state.AddCollectionHandler(facade, source, handler); } + /// Adds a collection-changed handler to a relay state that is created on the first handler, so a facade nobody listens to never allocates one. + /// The facade's relay state slot. + /// The public facade instance reported as the sender on relayed events. + /// The observable stream of collection-change notifications. + /// The handler to add, or . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void AddCollectionChanged( + ref FacadeRelayState? state, + object facade, + IObservable source, + NotifyCollectionChangedEventHandler? handler) => + (Volatile.Read(ref state) ?? CreateState(ref state)).AddCollectionHandler(facade, source, handler); + /// Removes a collection-changed handler from . /// The facade relay state. /// The handler to remove, or . [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void RemoveCollectionChanged( - FacadeRelayState state, - NotifyCollectionChangedEventHandler? handler) - { - ThrowHelper.ThrowIfNull(state); - state.RemoveCollectionHandler(handler); - } + FacadeRelayState? state, + NotifyCollectionChangedEventHandler? handler) => + state?.RemoveCollectionHandler(handler); /// Adds a property-changed handler to backed by . /// The facade relay state. @@ -91,20 +107,39 @@ internal static void AddPropertyChanged( IObservable source, PropertyChangedEventHandler? handler) { - ThrowHelper.ThrowIfNull(state); + ArgumentExceptionHelper.ThrowIfNull(state); state.AddPropertyHandler(facade, source, handler); } + /// Adds a property-changed handler to a relay state that is created on the first handler, so a facade nobody listens to never allocates one. + /// The facade's relay state slot. + /// The public facade instance reported as the sender on relayed events. + /// The observable stream of property-change notifications. + /// The handler to add, or . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void AddPropertyChanged( + ref FacadeRelayState? state, + object facade, + IObservable source, + PropertyChangedEventHandler? handler) => + (Volatile.Read(ref state) ?? CreateState(ref state)).AddPropertyHandler(facade, source, handler); + /// Removes a property-changed handler from . /// The facade relay state. /// The handler to remove, or . [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void RemovePropertyChanged( - FacadeRelayState state, - PropertyChangedEventHandler? handler) + FacadeRelayState? state, + PropertyChangedEventHandler? handler) => + state?.RemovePropertyHandler(handler); + + /// Creates the relay state for a slot, or returns the one another thread stored first. + /// The relay state slot. + /// The relay state. + private static FacadeRelayState CreateState(ref FacadeRelayState? slot) { - ThrowHelper.ThrowIfNull(state); - state.RemovePropertyHandler(handler); + FacadeRelayState created = new(); + return Interlocked.CompareExchange(ref slot, created, null) ?? created; } /// Carries an observable collection and registered handler for deterministic unsubscription. diff --git a/src/ReactiveList/Internal/FacadeRelayState.cs b/src/ReactiveList/Internal/FacadeRelayState.cs index 0a27ff20..282e6807 100644 --- a/src/ReactiveList/Internal/FacadeRelayState.cs +++ b/src/ReactiveList/Internal/FacadeRelayState.cs @@ -108,8 +108,8 @@ private void AddHandler( where TEventArgs : EventArgs where THandler : Delegate { - ThrowHelper.ThrowIfNull(facade); - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(facade); + ArgumentExceptionHelper.ThrowIfNull(source); if (handler is null) { 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..3b16340e --- /dev/null +++ b/src/ReactiveList/Internal/FilteredViewEngine.cs @@ -0,0 +1,412 @@ +// 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 observable stream of collection-change notifications, created when something first asks for it. + private IObservable? _collectionChanges; + + /// The active filter. + private Func _filter; + + /// The filter waiting to be applied by the next drain. + private Func? _pendingFilter; + + /// Whether a batch of structural changes is being applied. + private bool _inBatch; + + /// The mirror index of the last removal in the batch, or -1 when there is none. + private int _cursorIndex = -1; + + /// The number of included items before . + private int _cursorPosition; + + /// Initializes a new instance of the class. + /// The source to project. + /// The initial filter. + internal FilteredViewEngine(IReactiveSource source, Func filter) + { + ArgumentExceptionHelper.ThrowIfNull(filter); + + _filter = filter; + _pump = new(source); + Filtered = new() { Gate = _pump.Gate }; + Items = new(Filtered); + try + { + // Nobody can listen yet, so the first fill raises no events. + var matched = EvaluateMirror(); + Filtered.Populate(Project(matched)); + } + catch + { + // The constructor throws, so nobody else can dispose the source subscription. + _pump.Dispose(); + throw; + } + } + + /// Gets the observable stream of collection-change notifications. + internal IObservable CollectionChanges => + _collectionChanges ??= FacadeNotificationHelper.ObserveCollectionChanges(Filtered); + + /// 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(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void BatchStarted(int size) + { + _inBatch = true; + _cursorIndex = -1; + Filtered.BeginBatch(size); + } + + /// + public void BatchEnded() + { + _inBatch = false; + _cursorIndex = -1; + Filtered.EndBatch(); + } + + /// + public void ItemsInserted(int index, int count) + { + _cursorIndex = -1; + if (count == 1) + { + _flags.Insert(index, false); + } + else + { + _flags.InsertRange(index, new bool[count]); + } + + // Every flag in the inserted range is still clear, so each included item lands right after the previous one. + var position = IncludedBefore(index); + for (var i = index; i < index + count; i++) + { + var item = Buffer.Items[i]; + if (!_filter(item)) + { + continue; + } + + _flags[i] = true; + Filtered.Insert(position, item); + position++; + } + } + + /// + public void ItemRemoved(int index, T item) + { + if (_flags[index]) + { + Filtered.RemoveAt(PositionForRemoval(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 matched = EvaluateMirror(); + Filtered.ReconcileTo(Project(matched)); + } + + /// 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, coverSubscriptionGap: true); + + /// 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() + { + // The plain read keeps the exchange, which is a full fence, off every drain that has no filter queued. + if (Volatile.Read(ref _pendingFilter) is null || 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; + + /// Gets the projection position of an item being removed, resuming from the previous removal of the same batch. + /// The mirror index of the removed item. + /// The projection position of the first included item at or after the index. + private int PositionForRemoval(int index) + { + if (!_inBatch) + { + return IncludedBefore(index); + } + + // Removing at an index leaves the flags before it untouched, so the count before the last removal still holds. + var resume = _cursorIndex >= 0 && index >= _cursorIndex; + var position = resume ? _cursorPosition : IncludedBefore(index); + for (var i = resume ? _cursorIndex : index; i < index; i++) + { + if (_flags[i]) + { + position++; + } + } + + _cursorIndex = index; + _cursorPosition = position; + return position; + } + + /// 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 > Filtered.ResetLimit) + { + _flags.Clear(); + _flags.AddRange(newFlags); + Filtered.ReplaceAll(Project(Filtered.Count)); + 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]; + } + } + + /// Evaluates the filter for every mirror item and records the result. + /// The number of items that pass the filter. + private int EvaluateMirror() + { + var items = Buffer.Items; + _flags.Clear(); + ListCompat.EnsureCapacity(_flags, items.Count); + for (var i = 0; i < items.Count; i++) + { + _flags.Add(false); + } + + var matched = 0; + for (var i = 0; i < items.Count; i++) + { + var included = _filter(items[i]); + _flags[i] = included; + if (included) + { + matched++; + } + } + + return matched; + } + + /// Builds the projected sequence from the mirror and flags. + /// The number of included items. + /// The included items in source order. + private List Project(int capacity) + { + var items = Buffer.Items; + var result = new List(capacity); + 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/FirstValueRelay.cs b/src/ReactiveList/Internal/FirstValueRelay.cs new file mode 100644 index 00000000..2b75f2dd --- /dev/null +++ b/src/ReactiveList/Internal/FirstValueRelay.cs @@ -0,0 +1,78 @@ +// 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 values that configure a dynamic view. The first value is only recorded, so the view can start with it, and every +/// later value goes to the view. One observer serves both the probe and the live subscription, so neither needs a closure or a wrapper. +/// +/// The value type. +internal sealed class FirstValueRelay : IObserver +{ + /// Applies later values, or while the first value is being probed. + private Action? _apply; + + /// Whether the next live value is the replay of the first value. + private bool _skipFirst; + + /// Gets a value indicating whether a first value was recorded. + internal bool HasInitial { get; private set; } + + /// Gets the first value that was recorded. + internal TValue? Initial { get; private set; } + + /// + public void OnNext(TValue value) + { + if (Volatile.Read(ref _apply) is { } apply) + { + if (_skipFirst) + { + _skipFirst = false; + return; + } + + apply(value); + return; + } + + if (HasInitial) + { + return; + } + + Initial = value; + HasInitial = true; + } + + /// + public void OnError(Exception error) + { + // A failure while probing only ends the probe. A failure of the live subscription surfaces to its publisher. + if (Volatile.Read(ref _apply) is not null) + { + ExceptionDispatchInfo.Capture(error).Throw(); + } + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted() + { + } + + /// Sends every later value to the view. + /// Applies a value. + internal void Attach(Action apply) + { + // The live subscription replays the first value again, which the view already started with. + _skipFirst = HasInitial; + Volatile.Write(ref _apply, apply); + } +} diff --git a/src/ReactiveList/Internal/GroupSlot.cs b/src/ReactiveList/Internal/GroupSlot.cs new file mode 100644 index 00000000..84e7b64a --- /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, BatchObservableCollection 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..05e2c27c --- /dev/null +++ b/src/ReactiveList/Internal/GroupedViewEngine.cs @@ -0,0 +1,381 @@ +// 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 BatchObservableCollection> _groupCollection; + + /// The observable stream of collection-change notifications, created when something first asks for it. + private IObservable? _collectionChanges; + + /// Whether the batch being applied is larger than and is applied silently. + private bool _quietBatch; + + /// Initializes a new instance of the class. + /// The source to group. + /// Extracts the grouping key. + internal GroupedViewEngine(IReactiveSource source, Func keySelector) + { + ArgumentExceptionHelper.ThrowIfNull(keySelector); + + _keySelector = keySelector; + _pump = new(source); + _groupCollection = new() { Gate = _pump.Gate }; + Groups = new(_groupCollection); + try + { + // Nobody can listen yet, so the first fill raises no events. + Rebuild(quietly: true); + } + catch + { + // The constructor throws, so nobody else can dispose the source subscription. + _pump.Dispose(); + throw; + } + } + + /// Gets the observable stream of collection-change notifications. + internal IObservable CollectionChanges => + _collectionChanges ??= FacadeNotificationHelper.ObserveCollectionChanges(_groupCollection); + + /// Gets the observable stream of property-change notifications. + internal IObservable PropertyChanges => _pump.PropertyChanges; + + /// Gets the read-only group collection. + internal ReadOnlyObservableCollection> Groups { get; } + + /// Gets or sets the batch size above which one applied batch raises a single reset on each changed collection instead of one notification per change. + internal int ResetLimit { get; set; } = int.MaxValue; + + /// 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(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void BatchStarted(int size) + { + if (size <= ResetLimit) + { + return; + } + + _quietBatch = true; + _groupCollection.BeginQuiet(); + foreach (var slot in _slots.Values) + { + slot.Items.BeginQuiet(); + } + } + + /// + public void BatchEnded() + { + if (!_quietBatch) + { + return; + } + + _quietBatch = false; + foreach (var slot in _slots.Values) + { + slot.Items.EndBatch(); + } + + _groupCollection.EndBatch(); + } + + /// + 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(); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void MirrorReset() => Rebuild(quietly: false); + + /// 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, coverSubscriptionGap: true); + + /// 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) + { + if (typeof(T).IsValueType) + { + return slot.Items.IndexOf(item); + } + + for (var i = 0; i < slot.Items.Count; i++) + { + if (ItemComparison.SameItem(slot.Items[i], item)) + { + return i; + } + } + + return -1; + } + + /// Rebuilds every group from the mirror. + /// Whether to raise no events, for the first fill before anyone can listen. + private void Rebuild(bool quietly) + { + MirrorCleared(); + var items = Buffer.Items; + for (var i = 0; i < items.Count; i++) + { + AddToGroup(items[i], quietly); + } + } + + /// Adds an item to the group for its key, creating the group when needed. + /// The item to add. + /// Whether to raise no events. + private void AddToGroup(T item, bool quietly = false) + { + var key = _keySelector(item); + if (!_slots.TryGetValue(key, out var slot)) + { + BatchObservableCollection members = new() { Gate = _pump.Gate }; + if (_quietBatch) + { + members.BeginQuiet(); + } + + slot = new(key, members, new(key, members)); + _slots[key] = slot; + if (quietly) + { + _groupCollection.AddQuietly(slot.Group); + } + else + { + _groupCollection.Add(slot.Group); + } + } + + if (quietly) + { + slot.Items.AddQuietly(item); + return; + } + + 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/HashCodeCompat.cs b/src/ReactiveList/Internal/HashCodeCompat.cs new file mode 100644 index 00000000..3ad10655 --- /dev/null +++ b/src/ReactiveList/Internal/HashCodeCompat.cs @@ -0,0 +1,27 @@ +// 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 + +/// Combines an array identity and count for equality hashes. +internal static class HashCodeCompat +{ + /// Combines a source array and count while keeping the caller's legacy hash formula. + /// The array element type. + /// The source array, if any. + /// The number of items. + /// The multiplier used on .NET Framework. + /// The combined hash code. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int CombineArrayAndCount(T[]? items, int count, int legacyMultiplier = 1) => +#if NETFRAMEWORK + unchecked(((items?.GetHashCode() ?? 0) * legacyMultiplier) ^ count); +#else + HashCode.Combine(items, count); +#endif +} diff --git a/src/ReactiveList/Internal/IViewMirrorSink.cs b/src/ReactiveList/Internal/IViewMirrorSink.cs new file mode 100644 index 00000000..900cffc6 --- /dev/null +++ b/src/ReactiveList/Internal/IViewMirrorSink.cs @@ -0,0 +1,55 @@ +// 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 +{ + /// The mirror is about to apply one notification that changes several items. + /// The number of items the notification carries. + void BatchStarted(int size); + + /// The mirror finished applying the notification announced by . + void BatchEnded(); + + /// 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/IdentityItemComparer.cs b/src/ReactiveList/Internal/IdentityItemComparer.cs new file mode 100644 index 00000000..83df1efb --- /dev/null +++ b/src/ReactiveList/Internal/IdentityItemComparer.cs @@ -0,0 +1,27 @@ +// 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 + +/// Treats two items as the same key the way does: by reference for reference types and by value for value types. +/// The item type. +internal sealed class IdentityItemComparer : IEqualityComparer> +{ + /// Gets the shared instance. + internal static IdentityItemComparer Instance { get; } = new(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Equals(ItemKey x, ItemKey y) => ItemComparison.SameItem(x.Value, y.Value); + + /// + public int GetHashCode(ItemKey obj) => + typeof(T).IsValueType + ? EqualityComparer.Default.GetHashCode(obj.Value!) + : RuntimeHelpers.GetHashCode(obj.Value); +} diff --git a/src/ReactiveList/Internal/IndexEntry.cs b/src/ReactiveList/Internal/IndexEntry.cs new file mode 100644 index 00000000..456a825f --- /dev/null +++ b/src/ReactiveList/Internal/IndexEntry.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 + +/// Pairs a registered secondary index with its name. +/// The secondary index value type. +/// The index name. +/// The index. +internal readonly record struct IndexEntry(string Name, ISecondaryIndex Index); diff --git a/src/ReactiveList/Internal/IsExternalInit.cs b/src/ReactiveList/Internal/IsExternalInit.cs deleted file mode 100644 index 20bfaf3c..00000000 --- a/src/ReactiveList/Internal/IsExternalInit.cs +++ /dev/null @@ -1,34 +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 NETFRAMEWORK -namespace System.Runtime.CompilerServices; - -/// Reserved for compiler support. -internal sealed class IsExternalInit -{ - /// Initializes a new instance of the class. - internal IsExternalInit() - { - } -} -#elif REACTIVELIST_REACTIVE -namespace ReactiveList.Reactive.Internal; - -/// Marks the runtime-provided init-only compatibility path. -file enum IsExternalInit -{ - /// Indicates that the target runtime provides init-only support. - RuntimeProvided = 0, -} -#else -namespace ReactiveList.Internal; - -/// Marks the runtime-provided init-only compatibility path. -file enum IsExternalInit -{ - /// Indicates that the target runtime provides init-only support. - RuntimeProvided = 0, -} -#endif diff --git a/src/ReactiveList/Internal/ItemComparison.cs b/src/ReactiveList/Internal/ItemComparison.cs new file mode 100644 index 00000000..b9b2b51d --- /dev/null +++ b/src/ReactiveList/Internal/ItemComparison.cs @@ -0,0 +1,190 @@ +// 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 + +/// Locates item occurrences in a view, treating reference types by identity and value types by value. +internal static class ItemComparison +{ + /// Finds an occurrence, preferring reference identity over value equality. + /// The item type. + /// The collection to search. + /// The occurrence to locate. + /// The matching index, or -1. + internal static int FindIndex(IEnumerable items, T item) + { + var index = 0; + var equalIndex = -1; + foreach (var candidate in items) + { + if (typeof(T).IsValueType ? EqualityComparer.Default.Equals(candidate, item) : ReferenceEquals(candidate, item)) + { + return index; + } + + if (equalIndex < 0 && EqualityComparer.Default.Equals(candidate, item)) + { + equalIndex = index; + } + + index++; + } + + return equalIndex; + } + + /// Finds the first occurrence in a list, preferring reference identity over value equality, without allocating an enumerator. + /// The item type. + /// The list to search. + /// The occurrence to locate. + /// The matching index, or -1. + internal static int FindIndex(IList items, T item) + { + if (typeof(T).IsValueType) + { + return items.IndexOf(item); + } + + var equalIndex = -1; + for (var i = 0; i < items.Count; i++) + { + var candidate = items[i]; + if (ReferenceEquals(candidate, item)) + { + return i; + } + + if (equalIndex < 0 && EqualityComparer.Default.Equals(candidate, item)) + { + equalIndex = i; + } + } + + return equalIndex; + } + + /// Finds the last occurrence in a list, preferring reference identity over value equality, without allocating an enumerator. + /// The item type. + /// The list to search. + /// The occurrence to locate. + /// The matching index, or -1. + internal static int FindLastIndex(IList items, T item) + { + if (!typeof(T).IsValueType) + { + return FindLastReferenceIndex(items, item); + } + + return item is IEquatable ? FindLastValueIndex(items, item) : FindLastBoxedIndex(items, item); + } + + /// Finds the last occurrence of an item with a caller-supplied comparer, for structs whose default equality allocates. + /// The item type. + /// The list to search. + /// The occurrence to locate. + /// The comparer that decides equality. + /// The matching index, or -1. + internal static int FindLastIndex(IList items, T item, IEqualityComparer comparer) + { + for (var i = items.Count - 1; i >= 0; i--) + { + if (comparer.Equals(items[i], item)) + { + return i; + } + } + + return -1; + } + + /// Gets the comparer that treats two items as the same occurrence the way does. + /// The item type. + /// The comparer. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static IdentityItemComparer SameItemComparer() => IdentityItemComparer.Instance; + + /// Compares two items by reference for reference types and by value for value types. + /// The item type. + /// 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); + + /// Finds the last occurrence of a struct that does not implement , boxing the target once. + /// The item type. + /// The list to search. + /// The occurrence to locate. + /// The matching index, or -1. + private static int FindLastBoxedIndex(IList items, T item) + { + // The default comparer boxes its argument on every call for a struct such as KeyValuePair, so box the target once. + object boxed = item!; + for (var i = items.Count - 1; i >= 0; i--) + { + if (items[i]!.Equals(boxed)) + { + return i; + } + } + + return -1; + } + + /// Finds the last occurrence of an equatable struct, stopping at the first match from the end. + /// The item type. + /// The list to search. + /// The occurrence to locate. + /// The matching index, or -1. + private static int FindLastValueIndex(IList items, T item) + { + // The list search is vectorized for primitive items, which matters when the item is absent and the whole list is scanned. + if (items is List list) + { + return list.LastIndexOf(item); + } + + for (var i = items.Count - 1; i >= 0; i--) + { + if (EqualityComparer.Default.Equals(items[i], item)) + { + return i; + } + } + + return -1; + } + + /// Finds the last occurrence of a reference, preferring identity over equality. + /// The item type. + /// The list to search. + /// The occurrence to locate. + /// The matching index, or -1. + private static int FindLastReferenceIndex(IList items, T item) + { + var equalIndex = -1; + for (var i = items.Count - 1; i >= 0; i--) + { + var candidate = items[i]; + if (ReferenceEquals(candidate, item)) + { + return i; + } + + if (equalIndex < 0 && EqualityComparer.Default.Equals(candidate, item)) + { + equalIndex = i; + } + } + + return equalIndex; + } +} diff --git a/src/ReactiveList/Internal/ItemKey.cs b/src/ReactiveList/Internal/ItemKey.cs new file mode 100644 index 00000000..6975b7fc --- /dev/null +++ b/src/ReactiveList/Internal/ItemKey.cs @@ -0,0 +1,14 @@ +// 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 + +/// Wraps an item so it can key a dictionary without a non-null constraint. +/// The item type. +/// The wrapped item. +internal readonly record struct ItemKey(T Value); diff --git a/src/ReactiveList/Internal/KeyValueItemComparer.cs b/src/ReactiveList/Internal/KeyValueItemComparer.cs new file mode 100644 index 00000000..7ffe7565 --- /dev/null +++ b/src/ReactiveList/Internal/KeyValueItemComparer.cs @@ -0,0 +1,29 @@ +// 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 + +/// Compares dictionary entries by key and value without boxing, because the default equality of a pair that holds references allocates. +/// The key type. +/// The value type. +internal sealed class KeyValueItemComparer : IEqualityComparer> +{ + /// Gets the shared instance. + internal static KeyValueItemComparer Instance { get; } = new(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Equals(KeyValuePair x, KeyValuePair y) => + EqualityComparer.Default.Equals(x.Key, y.Key) && EqualityComparer.Default.Equals(x.Value, y.Value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int GetHashCode(KeyValuePair obj) => + unchecked(((obj.Key is null ? 0 : EqualityComparer.Default.GetHashCode(obj.Key)) * 397) + ^ (obj.Value is null ? 0 : EqualityComparer.Default.GetHashCode(obj.Value))); +} diff --git a/src/ReactiveList/Internal/ListChange.cs b/src/ReactiveList/Internal/ListChange.cs new file mode 100644 index 00000000..132cd8c7 --- /dev/null +++ b/src/ReactiveList/Internal/ListChange.cs @@ -0,0 +1,53 @@ +// 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 mutation recorded under the list lock and dispatched to observers outside it. +/// The item type. +/// What happened. +/// The list version after the change; it orders changes for lazily created mirrors. +/// The single item involved. +/// The replaced item for . +/// The added items of a range, replacement or edit. +/// The removed items of a range, clear, replacement or edit. +/// The position of the change, or -1 when unknown. +/// The previous position of a moved item. +/// The contents after the change when a mirror or stream observer needs them, otherwise . +internal readonly record struct ListChange( + ListChangeKind Kind, + long Sequence, + T? Item, + T? Previous, + T[]? Added, + T[]? Removed, + int Index, + int PreviousIndex, + T[]? Snapshot) +{ + /// Gets the contents before an edit when a stream observer needs them, otherwise . + public T[]? Before { get; init; } + + /// Gets whether a predicate was used to select the removed occurrences. + public bool IsPredicateRemoval { get; init; } + + /// Gets a value indicating whether the change replaces the added and removed history. + public bool AffectsAddedAndRemoved + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Kind is not (ListChangeKind.Updated or ListChangeKind.Moved or ListChangeKind.None + or ListChangeKind.ClearedSilent or ListChangeKind.Refresh or ListChangeKind.Complete); + } + + /// Gets a value indicating whether the change replaces the changed history. + public bool AffectsChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Kind is not (ListChangeKind.None or ListChangeKind.ClearedSilent or ListChangeKind.Refresh or ListChangeKind.Complete); + } +} diff --git a/src/ReactiveList/Internal/ListChangeKind.cs b/src/ReactiveList/Internal/ListChangeKind.cs new file mode 100644 index 00000000..32d0f93f --- /dev/null +++ b/src/ReactiveList/Internal/ListChangeKind.cs @@ -0,0 +1,58 @@ +// 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 a mutation of a so its observers can be notified after the list lock is released. +internal enum ListChangeKind +{ + /// No change; used for the default value. + None = 0, + + /// A single item was added. + Added = 1, + + /// Several items were added. + AddedRange = 2, + + /// A single item was removed. + Removed = 3, + + /// Several items were removed. + RemovedRange = 4, + + /// The list was cleared and observers are told. + Cleared = 5, + + /// The list was cleared without telling observers other than the items mirror. + ClearedSilent = 6, + + /// An empty list was cleared, which only resets the change history. + HistoryReset = 7, + + /// An item was replaced. + Updated = 8, + + /// An item was moved. + Moved = 9, + + /// The whole contents were replaced. + Replaced = 10, + + /// A batch edit changed the contents. + Edited = 11, + + /// The current-items observable needs a fresh snapshot. + Refresh = 12, + + /// The list was disposed and its streams must complete. + Complete = 13, + + /// Changes committed during a notification deferral. + Deferred = 14, +} diff --git a/src/ReactiveList/Internal/ListCompat.cs b/src/ReactiveList/Internal/ListCompat.cs new file mode 100644 index 00000000..dd7e075e --- /dev/null +++ b/src/ReactiveList/Internal/ListCompat.cs @@ -0,0 +1,88 @@ +// 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 + +/// Provides operations that need a different implementation on .NET Framework. +internal static class ListCompat +{ +#if NETFRAMEWORK + /// The capacity given to an empty list that must grow. + private const int MinimumGrowth = 4; + + /// The factor by which a full list grows. + private const int GrowthFactor = 2; +#endif + + /// Makes sure a list can hold at least a number of items, growing geometrically so repeated calls stay cheap. + /// The item type. + /// The list. + /// The number of items the list must be able to hold. + internal static void EnsureCapacity(List list, int capacity) + { +#if NETFRAMEWORK + var current = list.Capacity; + if (current >= capacity) + { + return; + } + + var doubled = current == 0 ? MinimumGrowth : current * GrowthFactor; + list.Capacity = Math.Max(capacity, doubled); +#else + _ = list.EnsureCapacity(capacity); +#endif + } + + /// Appends a span of items to a list without allocating. + /// The item type. + /// The list. + /// The items to append. + internal static void AddRange(List list, ReadOnlySpan items) + { +#if NETFRAMEWORK + EnsureCapacity(list, list.Count + items.Length); + for (var i = 0; i < items.Length; i++) + { + list.Add(items[i]); + } +#else + list.AddRange(items); +#endif + } + + /// Gets a span over the items, copying only if the backing storage is not accessible. + /// The item type. + /// The items to read. + /// A span over the items. Do not modify the source while using the span. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ReadOnlySpan AsSpanOrCopy(IEnumerable items) => items switch + { + T[] array => array, +#if !NETFRAMEWORK + List list => CollectionsMarshal.AsSpan(list), +#endif + _ => CopyToArray(items) + }; + + /// Copies a sequence to a new array. + /// The item type. + /// The items to copy. + /// The copied items. + private static T[] CopyToArray(IEnumerable items) + { + if (items is not ICollection collection) + { + return [.. items]; + } + + var copy = new T[collection.Count]; + collection.CopyTo(copy, 0); + return copy; + } +} diff --git a/src/ReactiveList/Internal/ListHistory.cs b/src/ReactiveList/Internal/ListHistory.cs new file mode 100644 index 00000000..c82da8e3 --- /dev/null +++ b/src/ReactiveList/Internal/ListHistory.cs @@ -0,0 +1,52 @@ +// 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 items of the last change that replaced a history, kept so a history mirror created later can show them. +/// The item type. +/// Only the fields a history needs are stored, and an unchanged array is not written again, so recording a single-item change costs no write barrier. +internal record struct ListHistory +{ + /// The kind of the recorded change. + private ListChangeKind _kind; + + /// The single item of the recorded change. + private T? _item; + + /// The items the recorded change added. + private T[]? _added; + + /// The items the recorded change removed. + private T[]? _removed; + + /// Gets the kind of the recorded change, or before any change was recorded. + public readonly ListChangeKind Kind => _kind; + + /// Records the history-relevant parts of a change. + /// The change. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void Record(in ListChange change) + { + _kind = change.Kind; + _item = change.Item; + if (_added is not null || change.Added is not null) + { + _added = change.Added; + } + + if (_removed is not null || change.Removed is not null) + { + _removed = change.Removed; + } + } + + /// Describes the recorded change again. + /// A change that carries the kind, item and arrays that were recorded. + internal readonly ListChange ToChange() => new(_kind, 0, _item, default, _added, _removed, -1, -1, null); +} diff --git a/src/ReactiveList/Internal/ListMultisetDifference.cs b/src/ReactiveList/Internal/ListMultisetDifference.cs new file mode 100644 index 00000000..d231a0d5 --- /dev/null +++ b/src/ReactiveList/Internal/ListMultisetDifference.cs @@ -0,0 +1,195 @@ +// 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 + +/// Computes which items a batch edit added and removed. +internal static class ListMultisetDifference +{ + /// Compares two orderings of a list and reports the items present in one but not the other, counting duplicates. + /// The item type. + /// The contents before the edit. + /// The contents after the edit. + /// Receives the items only present after the edit, in list order. + /// Receives the items only present before the edit, in list order. + /// when the two orderings differ at all. + internal static bool Compute(T[] before, List after, out T[] added, out T[] removed) + where T : notnull + { + var prefix = CommonPrefix(before, after); + var suffix = CommonSuffix(before, after, prefix); + var beforeLength = before.Length - prefix - suffix; + var afterLength = after.Count - prefix - suffix; + if (beforeLength == 0 && afterLength == 0) + { + added = []; + removed = []; + return false; + } + + if (beforeLength == 0 || afterLength == 0) + { + removed = SliceArray(before, prefix, beforeLength); + added = SliceList(after, prefix, afterLength); + return true; + } + + added = new DifferenceTable(before, prefix, beforeLength).Unmatched(after, prefix, afterLength); + removed = new DifferenceTable(after, prefix, afterLength).Unmatched(before, prefix, beforeLength); + return true; + } + + /// Counts the leading items that are equal in both orderings. + /// The item type. + /// The contents before the edit. + /// The contents after the edit. + /// The length of the common prefix. + private static int CommonPrefix(T[] before, List after) + { + var comparer = EqualityComparer.Default; + var limit = Math.Min(before.Length, after.Count); + var prefix = 0; + while (prefix < limit && comparer.Equals(before[prefix], after[prefix])) + { + prefix++; + } + + return prefix; + } + + /// Counts the trailing items that are equal in both orderings, outside the common prefix. + /// The item type. + /// The contents before the edit. + /// The contents after the edit. + /// The length of the common prefix. + /// The length of the common suffix. + private static int CommonSuffix(T[] before, List after, int prefix) + { + var comparer = EqualityComparer.Default; + var limit = Math.Min(before.Length, after.Count) - prefix; + var suffix = 0; + while (suffix < limit && comparer.Equals(before[before.Length - 1 - suffix], after[after.Count - 1 - suffix])) + { + suffix++; + } + + return suffix; + } + + /// Copies a window of an array. + /// The item type. + /// The source array. + /// The first index. + /// The number of items. + /// The copy. + private static T[] SliceArray(T[] source, int start, int length) + { + if (length == 0) + { + return []; + } + + var result = ArrayCompat.AllocateForFullOverwrite(length); + Array.Copy(source, start, result, 0, length); + return result; + } + + /// Copies a window of a list. + /// The item type. + /// The source list. + /// The first index. + /// The number of items. + /// The copy. + private static T[] SliceList(List source, int start, int length) + { + if (length == 0) + { + return []; + } + + var result = ArrayCompat.AllocateForFullOverwrite(length); + source.CopyTo(start, result, 0, length); + return result; + } + + /// Counts the items of one window so the other window can be matched against them. + /// The item type. + private sealed class DifferenceTable + where T : notnull + { + /// The number of unmatched occurrences of each non-null item. + private readonly Dictionary _counts; + + /// The number of unmatched null items. + private int _nulls; + + /// Initializes a new instance of the class. + /// The items to count. + /// The first index to count. + /// The number of items to count. + internal DifferenceTable(IList source, int start, int length) + { + _counts = [with(length)]; + for (var i = start; i < start + length; i++) + { + Count(source[i]); + } + } + + /// Gets the items of a window that cannot be matched against the remaining counts, consuming the counts as it goes. + /// The items. + /// The first index. + /// The number of items. + /// The unmatched items in order. + internal T[] Unmatched(IList source, int start, int length) + { + var result = new List(); + for (var i = start; i < start + length; i++) + { + if (!TryMatch(source[i])) + { + result.Add(source[i]); + } + } + + return [.. result]; + } + + /// Records one occurrence of an item. + /// The item. + private void Count(T item) + { + if (item is null) + { + _nulls++; + return; + } + + DictionaryCompat.Increment(_counts, item); + } + + /// Consumes one recorded occurrence of an item. + /// The item. + /// when an occurrence was recorded. + private bool TryMatch(T item) + { + if (item is null) + { + if (_nulls == 0) + { + return false; + } + + _nulls--; + return true; + } + + return DictionaryCompat.TryConsume(_counts, item); + } + } +} diff --git a/src/ReactiveList/Internal/MirrorRemoval.cs b/src/ReactiveList/Internal/MirrorRemoval.cs new file mode 100644 index 00000000..0be56986 --- /dev/null +++ b/src/ReactiveList/Internal/MirrorRemoval.cs @@ -0,0 +1,113 @@ +// 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 + +/// Finds and removes the earliest occurrence of each item of a batch from an ordered mirror with one pass over it. +internal static class MirrorRemoval +{ + /// Finds the earliest occurrence of every batch item by identity for reference types and by value for value types. + /// The item type. + /// The mirror. + /// The items to find. + /// Whether to report that a found item also occurs elsewhere in the mirror. + /// Receives the ascending mirror indices of the found occurrences. + /// Receives whether a found item occurs more than once in the mirror. + /// The number of occurrences found, which is smaller than the batch when an item is missing. + internal static int Find(List items, PooledBatch batch, bool trackRepeats, int[] removedAt, out bool repeated) + where T : notnull + { + var counts = Count(batch); + var seen = trackRepeats ? new Dictionary, int>(counts.Count, ItemComparison.SameItemComparer()) : null; + var found = 0; + for (var i = 0; i < items.Count && (trackRepeats || found < batch.Count); i++) + { + ItemKey key = new(items[i]); + if (!counts.ContainsKey(key)) + { + continue; + } + + if (seen is not null) + { + DictionaryCompat.Increment(seen, key); + } + + if (found >= batch.Count || !DictionaryCompat.TryConsume(counts, key)) + { + continue; + } + + removedAt[found] = i; + found++; + } + + repeated = seen is not null && HasRepeat(seen); + return found; + } + + /// Removes the items at the given ascending indices with one pass. + /// The item type. + /// The mirror. + /// The ascending indices to remove. + /// The number of indices. + /// The removed items in index order. + internal static T[] Compact(List items, int[] removedAt, int count) + { + var removed = new T[count]; + var write = 0; + var next = 0; + for (var read = 0; read < items.Count; read++) + { + if (next < count && removedAt[next] == read) + { + removed[next] = items[read]; + next++; + continue; + } + + items[write] = items[read]; + write++; + } + + items.RemoveRange(write, items.Count - write); + return removed; + } + + /// Counts how many times each item occurs in a batch. + /// The item type. + /// The batch. + /// The occurrence count of each item. + private static Dictionary, int> Count(PooledBatch batch) + { + var counts = new Dictionary, int>(batch.Count, ItemComparison.SameItemComparer()); + for (var i = 0; i < batch.Count; i++) + { + DictionaryCompat.Increment(counts, new(batch.Items[i])); + } + + return counts; + } + + /// Checks whether any counted item occurs more than once. + /// The item type. + /// The occurrence counts. + /// when an item occurs more than once. + private static bool HasRepeat(Dictionary, int> occurrences) + { + foreach (var pair in occurrences) + { + if (pair.Value > 1) + { + return true; + } + } + + return false; + } +} diff --git a/src/ReactiveList/Internal/NotificationDeferralState.cs b/src/ReactiveList/Internal/NotificationDeferralState.cs new file mode 100644 index 00000000..ba97d0b2 --- /dev/null +++ b/src/ReactiveList/Internal/NotificationDeferralState.cs @@ -0,0 +1,28 @@ +// 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 + +/// Shares one release across all copies of a deferral token. +internal sealed class NotificationDeferralState +{ + /// Releases the deferral under the source's mutation locks. + private Action? _release; + + /// Initializes a new instance of the class. + /// The source's release callback. + internal NotificationDeferralState(Action release) => _release = release; + + /// Asks the source to release this deferral. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void Release() => Volatile.Read(ref _release)?.Invoke(this); + + /// Claims the release after the source has entered its mutation locks. + /// Whether this is the first release. + internal bool TryRelease() => Interlocked.Exchange(ref _release, null) is not null; +} diff --git a/src/ReactiveList/Internal/Observable.cs b/src/ReactiveList/Internal/Observable.cs index ae93dbac..fefb1db4 100644 --- a/src/ReactiveList/Internal/Observable.cs +++ b/src/ReactiveList/Internal/Observable.cs @@ -16,7 +16,7 @@ internal static class Observable /// An observable sequence that defers invocation to subscription. internal static IObservable Defer(Func> factory) { - ThrowHelper.ThrowIfNull(factory); + ArgumentExceptionHelper.ThrowIfNull(factory); return Signal.Create(observer => { @@ -47,8 +47,8 @@ internal static IObservable> FromEventPattern>(observer => { diff --git a/src/ReactiveList/Internal/ObservableMixins.cs b/src/ReactiveList/Internal/ObservableMixins.cs index 7c56fe66..e7b6f718 100644 --- a/src/ReactiveList/Internal/ObservableMixins.cs +++ b/src/ReactiveList/Internal/ObservableMixins.cs @@ -21,8 +21,8 @@ internal static class ObservableMixins /// An observable sequence of flattened results. internal IObservable FlatMap(Func> selector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(selector); return Signal.Create(observer => source.Subscribe( @@ -36,33 +36,5 @@ internal IObservable FlatMap(FuncConverts an observable sequence to a materialized list. - /// A list containing all values from the source sequence. - internal IEnumerable ToEnumerable() - { - ThrowHelper.ThrowIfNull(source); - - var values = new List(); - Exception? error = null; - using var completed = new ManualResetEventSlim(); - using var subscription = source.Subscribe( - values.Add, - ex => - { - error = ex; - completed.Set(); - }, - completed.Set); - - completed.Wait(); - - if (error is not null) - { - ExceptionDispatchInfo.Capture(error).Throw(); - } - - return values; - } } } 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/PendingNotificationQueue.cs b/src/ReactiveList/Internal/PendingNotificationQueue.cs new file mode 100644 index 00000000..29ee3c2d --- /dev/null +++ b/src/ReactiveList/Internal/PendingNotificationQueue.cs @@ -0,0 +1,32 @@ +// 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 + +/// Takes retained notifications from the queue a view keeps for them. +internal static class PendingNotificationQueue +{ + /// Takes the oldest notification and republishes the number that remain. + /// The source item type. + /// The queue, or when nothing was ever retained. + /// The number of retained notifications, readable without the lock that guards the queue. + /// The oldest notification. + /// when a notification was taken; when the queue was emptied after the caller last read the count. + internal static bool TryDequeue(Queue>? pending, ref int pendingCount, out PendingNotification next) + { + if (pending is not { Count: > 0 }) + { + next = default; + return false; + } + + next = pending.Dequeue(); + Volatile.Write(ref pendingCount, pending.Count); + return true; + } +} diff --git a/src/ReactiveList/Internal/PooledItemCounts.cs b/src/ReactiveList/Internal/PooledItemCounts.cs new file mode 100644 index 00000000..dac8b900 --- /dev/null +++ b/src/ReactiveList/Internal/PooledItemCounts.cs @@ -0,0 +1,136 @@ +// 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 + +/// Counts how many copies of each item a removal still has to take, using pooled arrays so the count itself allocates nothing. +/// The item type. +/// Items are compared with . The capacity is fixed when the counts are created, so the +/// caller gives the number of items it will add. Call to return the arrays to the pool. +internal struct PooledItemCounts : IDisposable, IEquatable> +{ + /// The fewest buckets the counts use. + private const int MinimumBuckets = 4; + + /// The bucket heads; each holds the one-based position of the first entry in its chain, or zero. + private int[]? _buckets; + + /// The distinct items with the copies still to remove. + private Entry[]? _entries; + + /// The number of entries in use. + private int _used; + + /// The mask that turns a hash into a bucket position. + private int _mask; + + /// + public readonly bool Equals(PooledItemCounts other) => + ReferenceEquals(_buckets, other._buckets) && ReferenceEquals(_entries, other._entries) && _used == other._used; + + /// + public override readonly bool Equals(object? obj) => obj is PooledItemCounts other && Equals(other); + + /// + public override readonly int GetHashCode() => 0; + + /// Returns the arrays to the pool. + public void Dispose() + { + var buckets = _buckets; + var entries = _entries; + _buckets = null; + _entries = null; + if (buckets is not null) + { + ArrayPool.Shared.Return(buckets); + } + + if (entries is not null) + { + ArrayPool.Shared.Return(entries, clearArray: ArrayPoolClearHelper.IsReferenceOrContainsReferences()); + } + } + + /// Creates counts that can hold up to distinct items. + /// The largest number of items that will be added. + /// The empty counts. + internal static PooledItemCounts Create(int capacity) + { + var bucketCount = (int)BitOperationsCompat.RoundUpToPowerOf2((uint)Math.Max(capacity, MinimumBuckets)); + var buckets = ArrayPool.Shared.Rent(bucketCount); + buckets.AsSpan(0, bucketCount).Clear(); + + // The mask is taken from the requested size because a rented array can be longer than asked. + return new() { _buckets = buckets, _entries = ArrayPool.Shared.Rent(capacity), _mask = bucketCount - 1 }; + } + + /// Adds one copy to remove. + /// The item to remove. + internal void Add(T item) + { + var hash = GetHash(item); + var entries = _entries!; + ref var head = ref _buckets![hash & _mask]; + for (var position = head - 1; position >= 0; position = entries[position].Next) + { + ref var existing = ref entries[position]; + if (existing.Hash != hash || !EqualityComparer.Default.Equals(existing.Item, item)) + { + continue; + } + + existing.Remaining++; + return; + } + + entries[_used] = new(item, hash, 1, head - 1); + _used++; + head = _used; + } + + /// Takes one copy off the count when the item still has one to remove. + /// The item found in a shard. + /// when the item is to be removed. + internal readonly bool TryConsume(T item) + { + var hash = GetHash(item); + var entries = _entries!; + for (var position = _buckets![hash & _mask] - 1; position >= 0; position = entries[position].Next) + { + ref var entry = ref entries[position]; + if (entry.Hash != hash || !EqualityComparer.Default.Equals(entry.Item, item)) + { + continue; + } + + if (entry.Remaining == 0) + { + return false; + } + + entry.Remaining--; + return true; + } + + return false; + } + + /// Gets the non-negative hash of an item. + /// The item. + /// The hash, with the sign bit cleared. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int GetHash(T item) => item is null ? 0 : EqualityComparer.Default.GetHashCode(item) & int.MaxValue; + + /// Holds one distinct item and the copies still to remove. + /// The item. + /// The non-negative hash of the item. + /// The copies still to remove. + /// The position of the next entry in the chain, or -1. + private record struct Entry(T Item, int Hash, int Remaining, int Next); +} diff --git a/src/ReactiveList/Internal/PooledSnapshotEnumerator.cs b/src/ReactiveList/Internal/PooledSnapshotEnumerator.cs new file mode 100644 index 00000000..03020fe3 --- /dev/null +++ b/src/ReactiveList/Internal/PooledSnapshotEnumerator.cs @@ -0,0 +1,67 @@ +// 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 + +/// Enumerates a point-in-time copy held in a pooled array and returns the array when disposed. +/// The element type. +internal sealed class PooledSnapshotEnumerator : IEnumerator +{ + /// The number of valid elements in the buffer. + private readonly int _count; + + /// The pooled array holding the snapshot, or once disposed. + private T[]? _buffer; + + /// The index of the current element. + private int _index = -1; + + /// Initializes a new instance of the class. + /// A rented array that this enumerator owns. + /// The number of valid elements in . + internal PooledSnapshotEnumerator(T[] buffer, int count) + { + _buffer = buffer; + _count = count; + } + + /// + public T Current => _buffer is { } buffer && (uint)_index < (uint)_count ? buffer[_index] : default!; + + /// + object? IEnumerator.Current => Current; + + /// + public bool MoveNext() + { + if (_buffer is null || _index + 1 >= _count) + { + _index = _count; + return false; + } + + _index++; + return true; + } + + /// + public void Reset() => _index = -1; + + /// + public void Dispose() + { + var buffer = _buffer; + if (buffer is null) + { + return; + } + + _buffer = null; + ArrayPool.Shared.Return(buffer, clearArray: ArrayPoolClearHelper.IsReferenceOrContainsReferences()); + } +} diff --git a/src/ReactiveList/Internal/ProjectionRules.cs b/src/ReactiveList/Internal/ProjectionRules.cs new file mode 100644 index 00000000..7b916ab8 --- /dev/null +++ b/src/ReactiveList/Internal/ProjectionRules.cs @@ -0,0 +1,23 @@ +// 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. +/// Tells whether two items are the same source entry, or when updates always name the replaced item. +/// Whether the source names the replaced item in update notifications. Keyed sources do not, so their notifications carry a default value there. +internal sealed record ProjectionRules( + Func Matches, + Func>? Snapshot, + Func? ExpectedCount, + Func? SameEntry = null, + bool PreviousIsReliable = true); diff --git a/src/ReactiveList/Internal/QuaternaryCore.cs b/src/ReactiveList/Internal/QuaternaryCore.cs new file mode 100644 index 00000000..fd490c29 --- /dev/null +++ b/src/ReactiveList/Internal/QuaternaryCore.cs @@ -0,0 +1,495 @@ +// 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 + +/// Provides the stateless counting, versioning, publishing, index and lifecycle helpers shared by the sharded collections. +/// Every method works on the it is given. Shard locks are always taken in ascending +/// order and released in reverse order, and notifications are queued while the shard lock is held and delivered by a single reader. +internal static class QuaternaryCore +{ + /// The fixed number of shards used by every sharded collection. + internal const int FixedShardCount = 4; + + /// Cached property-change arguments for the count. + private static readonly PropertyChangedEventArgs CountPropertyChangedEventArgs = new("Count"); + + /// Cached property-change arguments for the collection indexer. + private static readonly PropertyChangedEventArgs ItemArrayPropertyChangedEventArgs = new("Item[]"); + + /// Creates the state for a collection with the given shard containers. + /// The item type. + /// The secondary index value type. + /// The four shard containers. + /// The name of the collection type, reported when it is used after disposal. + /// The new collection state. + internal static QuaternaryState CreateState(IQuad[] quads, string objectName) + where TItem : notnull => + new( + quads, + [ + new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion), + new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion), + new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion), + new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion) + ], + new ShardCounter[FixedShardCount], + SynchronizationContext.Current, + objectName); + + /// Gets the change-detection version, which grows with every modification. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The observed-change counter plus the per-shard unobserved-change counters. + internal static long Version(QuaternaryState state) + where TItem : notnull + { + var shards = state.Shards; + var last = shards[3].UnobservedVersion; + return Interlocked.Read(ref state.Version) + shards[0].UnobservedVersion + shards[1].UnobservedVersion + + shards[2].UnobservedVersion + last; + } + + /// Throws when the collection has been disposed. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The collection is disposed. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void ThrowIfDisposed(QuaternaryState state) + where TItem : notnull + { + if (Volatile.Read(ref state.Disposed) != 0) + { + ThrowObjectDisposed(state.ObjectName); + } + } + + /// Gets a value indicating whether the collection has observable or legacy subscribers. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// when change notifications need to be materialized. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool HasChangeObservers(QuaternaryState state) + where TItem : notnull => + (Volatile.Read(ref state.SubscriberCount) != 0 || Volatile.Read(ref state.CollectionChanged) is not null) + && state.DeferralDepth == 0; + + /// Sums the item counts of every shard; call while the shard locks are held. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The total number of items stored in the shards. + internal static int SumShardCounts(QuaternaryState state) + where TItem : notnull + { + var quads = state.Quads; + var total = 0; + for (var i = 0; i < FixedShardCount; i++) + { + total += quads[i].Count; + } + + return total; + } + + /// Queues a single-item notification and advances the version; call while the shard lock is held. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The shard whose write lock the caller holds, or a negative value when no shard lock is held. + /// The cache action type. + /// The item associated with the action. + /// The previous item value for updates. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void PublishLocked( + QuaternaryState state, + int shard, + CacheAction action, + TItem? item, + TItem? previous = default) + where TItem : notnull + { + if (!BeginPublish(state, shard, out var version)) + { + return; + } + + QuaternaryEvents.Enqueue(state, new(action, item, null, -1, -1, previous), version); + } + + /// Queues a batch notification that copies ; call while the shard locks are held. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The shard whose write lock the caller holds, or a negative value when no shard lock is held. + /// The cache action type. + /// The items to include; they are copied only when someone is listening. + /// Whether the batch can replace existing entries. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void PublishBatchLocked( + QuaternaryState state, + int shard, + CacheAction action, + ReadOnlySpan items, + bool includesReplacements = false) + where TItem : notnull + { + if (!BeginPublish(state, shard, out var version)) + { + return; + } + + var copy = items.ToArray(); + var batch = new PooledBatch(copy, copy.Length, ReturnToPool: false); + QuaternaryEvents.Enqueue(state, new(action, default, batch), version, requiresSnapshot: includesReplacements); + } + + /// Advances the version without queuing anything; call while the shard write lock is held. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The shard whose write lock the caller holds. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void AdvanceVersion(QuaternaryState state, int shard) + where TItem : notnull => + state.Shards[shard].BumpVersion(); + + /// Advances the version and queues an owned batch when someone is listening; call while the shard lock is held. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The shard whose write lock the caller holds. + /// The cache action type. + /// The buffer holding the items. + /// The number of valid items in . + internal static void PublishOwnedBatchLocked( + QuaternaryState state, + int shard, + CacheAction action, + TItem[] items, + int count) + where TItem : notnull + { + if (!BeginPublish(state, shard, out var version)) + { + return; + } + + var owned = count == items.Length ? items : items.AsSpan(0, count).ToArray(); + QuaternaryEvents.Enqueue(state, new(action, default, new(owned, owned.Length, ReturnToPool: false)), version); + } + + /// Advances the version without a payload; call while every shard write lock is held. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The cache action type. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void PublishMarkerLocked(QuaternaryState state, CacheAction action) + where TItem : notnull => + PublishLocked(state, 0, action, default); + + /// Raises the property change events for the count and the indexer; call after releasing locks. + /// The collection's property-changed handlers. + /// The collection raising the events. + /// Whether the mutation committed outside a deferral. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void RaisePropertyChanged(PropertyChangedEventHandler? handler, object sender, bool notify) + { + if (!notify || handler is null) + { + return; + } + + handler(sender, CountPropertyChangedEventArgs); + handler(sender, ItemArrayPropertyChangedEventArgs); + } + + /// Registers an index; call while every shard write lock is held. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The index name. + /// The populated index. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void RegisterIndex(QuaternaryState state, string name, ISecondaryIndex index) + where TItem : notnull => + Volatile.Write(ref state.Indexes, QuaternaryIndexTable.With(state.Indexes, name, index)); + + /// Gets a value indicating whether any secondary index is registered. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// when at least one index is registered. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool HasIndexes(QuaternaryState state) + where TItem : notnull => + state.Indexes is not null; + + /// Finds a registered index by name without taking a lock. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The index name. + /// Receives the index when one is registered under the name. + /// when an index with that name exists. + internal static bool TryGetIndex( + QuaternaryState state, + string name, + [MaybeNullWhen(false)] out ISecondaryIndex index) + where TItem : notnull + { + var table = Volatile.Read(ref state.Indexes); + if (table is null) + { + index = default; + return false; + } + + return QuaternaryIndexTable.TryGet(table, name, out index); + } + + /// Notifies every index of an added value without allocating. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The value that was added. + /// The first exception a key selector threw, or ; the caller commits and announces the change and then rethrows it. + /// An index whose selector throws does not hold the value, and the other indexes are still updated. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static Exception? IndexAdded(QuaternaryState state, TValue item) + where TItem : notnull + { + var table = state.Indexes; + return table is null ? null : IndexAddedSlow(table, item); + } + + /// Notifies every index of a removed value without allocating. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The value that was removed. + /// The first exception a key selector threw, or ; the caller commits and announces the change and then rethrows it. + /// An index whose selector throws keeps its entry, and the other indexes are still updated. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static Exception? IndexRemoved(QuaternaryState state, TValue item) + where TItem : notnull + { + var table = state.Indexes; + return table is null ? null : IndexRemovedSlow(table, item); + } + + /// Notifies every index that one value replaced another. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The value that was replaced. + /// The value that replaced it. + /// The first exception a key selector threw, or ; the caller commits and announces the change and then rethrows it. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static Exception? IndexReplaced(QuaternaryState state, TValue previous, TValue item) + where TItem : notnull + { + var table = state.Indexes; + return table is null ? null : IndexReplacedSlow(table, previous, item); + } + + /// Throws a captured exception, keeping its original stack trace; does nothing for . + /// The captured exception, if any. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void RethrowIfFailed(Exception? failure) + { + if (failure is not null) + { + Rethrow(failure); + } + } + + /// Clears every registered index. + /// The item type. + /// The secondary index value type. + /// The collection state. + internal static void ClearIndices(QuaternaryState state) + where TItem : notnull + { + var indexes = state.Indexes; + if (indexes is null) + { + return; + } + + for (var i = 0; i < indexes.Length; i++) + { + indexes[i].Index.Clear(); + } + } + + /// Removes every item while holding all shard write locks, then publishes a cleared notification. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// Whether to raise property changes for the clear. + internal static bool Clear(QuaternaryState state) + where TItem : notnull + { + var locks = state.Locks; + QuaternaryShardHelpers.EnterAllWriteLocks(locks); + try + { + ThrowIfDisposed(state); + for (var i = 0; i < FixedShardCount; i++) + { + state.Quads[i].Clear(); + } + + ClearIndices(state); + PublishLocked(state, 0, CacheAction.Cleared, default); + return state.DeferralDepth == 0; + } + finally + { + QuaternaryShardHelpers.ExitAllWriteLocks(locks); + } + } + + /// Disposes the shards and completes the notification stream once; later calls do nothing. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// when this call performed the disposal. + internal static bool Dispose(QuaternaryState state) + where TItem : notnull + { + if (Interlocked.Exchange(ref state.Disposed, 1) != 0) + { + return false; + } + + var locks = state.Locks; + QuaternaryShardHelpers.EnterAllWriteLocks(locks); + try + { + for (var i = 0; i < FixedShardCount; i++) + { + state.Quads[i].Dispose(); + } + + ClearIndices(state); + } + finally + { + QuaternaryShardHelpers.ExitAllWriteLocks(locks); + } + + _ = Volatile.Read(ref state.EventChannel)?.Writer.TryComplete(); + return true; + } + + /// Advances the version for one change and reports whether the change must be queued for observers. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The shard whose write lock the caller holds, or a negative value when no shard lock is held. + /// Receives the observed-change version to stamp on the notification; zero when nobody is listening. + /// when someone is listening and a notification must be queued. + /// Changes nobody observes are counted on the shard's own cache line, so writers on different shards share no + /// written memory. Changes someone observes take a number from the shared counter, which gives notifications a total order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool BeginPublish(QuaternaryState state, int shard, out long version) + where TItem : notnull + { + var observed = HasChangeObservers(state); + if (observed || shard < 0) + { + version = Interlocked.Increment(ref state.Version); + } + else + { + state.Shards[shard].BumpVersion(); + version = 0; + } + + return observed; + } + + /// Rethrows a captured exception with its original stack trace. + /// The captured exception. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Rethrow(Exception failure) => ExceptionDispatchInfo.Capture(failure).Throw(); + + /// Adds a value to every index, continuing past an index whose key selector throws. + /// The secondary index value type. + /// The registered indexes. + /// The value that was added. + /// The first exception thrown, or . + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception? IndexAddedSlow(IndexEntry[] indexes, TValue item) + { + Exception? failure = null; + for (var i = 0; i < indexes.Length; i++) + { + try + { + indexes[i].Index.OnAdded(item); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + failure ??= ex; + } + } + + return failure; + } + + /// Removes a value from every index, continuing past an index whose key selector throws. + /// The secondary index value type. + /// The registered indexes. + /// The value that was removed. + /// The first exception thrown, or . + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception? IndexRemovedSlow(IndexEntry[] indexes, TValue item) + { + Exception? failure = null; + for (var i = 0; i < indexes.Length; i++) + { + try + { + indexes[i].Index.OnRemoved(item); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + failure ??= ex; + } + } + + return failure; + } + + /// Replaces a value in every index, continuing past an index whose key selector throws. + /// The secondary index value type. + /// The registered indexes. + /// The value that was replaced. + /// The value that replaced it. + /// The first exception thrown, or . + [MethodImpl(MethodImplOptions.NoInlining)] + private static Exception? IndexReplacedSlow(IndexEntry[] indexes, TValue previous, TValue item) + { + var removal = IndexRemovedSlow(indexes, previous); + var addition = IndexAddedSlow(indexes, item); + return removal ?? addition; + } + + /// Throws the exception for use after disposal. + /// The name of the disposed collection type. + /// Always thrown. + [MethodImpl(MethodImplOptions.NoInlining)] + private static void ThrowObjectDisposed(string objectName) => throw new ObjectDisposedException(objectName); +} diff --git a/src/ReactiveList/Internal/QuaternaryDeferrals.cs b/src/ReactiveList/Internal/QuaternaryDeferrals.cs new file mode 100644 index 00000000..b653cb6a --- /dev/null +++ b/src/ReactiveList/Internal/QuaternaryDeferrals.cs @@ -0,0 +1,102 @@ +// 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 + +/// Coordinates collection-wide notification deferrals across every shard. +internal static class QuaternaryDeferrals +{ + /// Opens a scope at the boundary between committed writes. + /// The item type. + /// The index value type. + /// The source state. + /// The source's release callback. + /// The token for this scope. + internal static NotificationDeferral Begin( + QuaternaryState state, + Action resume) + where TItem : notnull + { + var release = new NotificationDeferralState(resume); + EnterWriteLocks(state.Locks); + try + { + QuaternaryCore.ThrowIfDisposed(state); + if (state.DeferralDepth == 0) + { + state.DeferralVersion = QuaternaryCore.Version(state); + } + + state.DeferralDepth++; + } + finally + { + QuaternaryShardHelpers.ExitAllWriteLocks(state.Locks); + } + + return new(release); + } + + /// Releases a scope and queues its reset before any following write can publish. + /// The item type. + /// The index value type. + /// The source state. + /// The token's shared state. + /// Copies the contents with the write locks held. + /// Whether the source should raise property changes. + internal static bool End( + QuaternaryState state, + NotificationDeferralState release, + Func copyLocked) + where TItem : notnull + { + EnterWriteLocks(state.Locks); + try + { + if (!release.TryRelease() || Volatile.Read(ref state.Disposed) != 0) + { + return false; + } + + state.DeferralDepth--; + if (state.DeferralDepth != 0 || state.DeferralVersion == QuaternaryCore.Version(state)) + { + return false; + } + + if (QuaternaryCore.HasChangeObservers(state)) + { + var items = copyLocked(); + var version = Interlocked.Increment(ref state.Version); + QuaternaryEvents.Enqueue(state, new(CacheAction.Reset, default, new(items, items.Length, ReturnToPool: false)), version); + } + + return true; + } + finally + { + QuaternaryShardHelpers.ExitAllWriteLocks(state.Locks); + } + } + + /// Enters the write locks without risking lock-order inversion from a source callback. + /// The collection's shard locks. + /// The current thread holds a shard lock. + private static void EnterWriteLocks(ReaderWriterLockSlim[] locks) + { + for (var i = 0; i < locks.Length; i++) + { + if (locks[i].IsWriteLockHeld || locks[i].IsReadLockHeld) + { + throw new InvalidOperationException("Open and release deferrals outside callbacks that run under a shard lock."); + } + } + + QuaternaryShardHelpers.EnterAllWriteLocks(locks); + } +} diff --git a/src/ReactiveList/Internal/QuaternaryEvents.cs b/src/ReactiveList/Internal/QuaternaryEvents.cs new file mode 100644 index 00000000..2bba7d75 --- /dev/null +++ b/src/ReactiveList/Internal/QuaternaryEvents.cs @@ -0,0 +1,347 @@ +// 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 + +/// Provides the stateless notification queue, observer pipeline and legacy event helpers shared by the sharded collections. +/// Notifications are queued while the shard lock is held and delivered by one background reader, so observers see changes in +/// the order they happened and never run under an internal lock. +internal static class QuaternaryEvents +{ + /// Cached arguments reported for every legacy collection change. + private static readonly NotifyCollectionChangedEventArgs ResetEventArgs = new(NotifyCollectionChangedAction.Reset); + + /// Gets the cached observable of notifications, creating it on first use. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The notification observable. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static IObservable> GetStream(QuaternaryState state) + where TItem : notnull => + Volatile.Read(ref state.Stream) ?? CreateStream(state); + + /// Gets the cached observable of versioned notifications, creating it on first use. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The versioned notification observable. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static IObservable> GetVersionedStream(QuaternaryState state) + where TItem : notnull => + Volatile.Read(ref state.VersionedStream) ?? CreateVersionedStream(state); + + /// Queues a notification for the background reader. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The notification to queue. + /// The collection version the change produced. + /// Whether versioned observers must read a snapshot instead of applying the payload. + internal static void Enqueue( + QuaternaryState state, + CacheNotify notification, + long version, + bool requiresSnapshot = false) + where TItem : notnull + { + var channel = Volatile.Read(ref state.EventChannel); + _ = channel?.Writer.TryWrite(new(notification, version, requiresSnapshot)); + } + + /// Connects an observer to a pipeline and counts it as a subscriber. + /// The item type. + /// The secondary index value type. + /// The element type of the pipeline. + /// The collection state. + /// The observer to connect. + /// The pipeline to subscribe to. + /// A handle that unsubscribes the observer. + internal static QuaternarySubscription Attach( + QuaternaryState state, + IObserver observer, + IObservable pipeline) + where TItem : notnull + { + var subscription = new QuaternarySubscription(state, observer); + _ = Interlocked.Increment(ref state.SubscriberCount); + try + { + subscription.Attach(pipeline.Subscribe(subscription)); + } + catch (ObjectDisposedException) when (Volatile.Read(ref state.Disposed) != 0) + { + subscription.OnCompleted(); + } + catch + { + subscription.Dispose(); + throw; + } + + return subscription; + } + + /// Starts the event processor on first use. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// when the processor is running; when the collection is disposed. + internal static bool EnsureEventProcessorStarted(QuaternaryState state) + where TItem : notnull => + Volatile.Read(ref state.EventProcessorStarted) != 0 || StartEventProcessor(state); + + /// Adds a collection-changed handler without losing concurrent additions. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The collection, which becomes the sender of the legacy events. + /// The handler to add. + internal static void AddCollectionChangedHandler(QuaternaryState state, object owner, NotifyCollectionChangedEventHandler? value) + where TItem : notnull + { + // The processor can already be running when the collection is disposed, so the disposed flag is checked after starting it. + if (value is null || !EnsureEventProcessorStarted(state) || Volatile.Read(ref state.Disposed) != 0) + { + return; + } + + _ = Interlocked.CompareExchange(ref state.Owner, owner, null); + var current = Volatile.Read(ref state.CollectionChanged); + while (!TryCombine(ref state.CollectionChanged, ref current, value)) + { + // Another thread changed the handler list first; try again against the list it left. + } + } + + /// Adds a handler to a handler list once, unless another thread changed the list since it was read. + /// The handler list field. + /// The list as last read; replaced with the list now stored when the swap loses. + /// The handler to add. + /// when the handler was added; when was stale. + internal static bool TryCombine(ref NotifyCollectionChangedEventHandler? field, ref NotifyCollectionChangedEventHandler? current, NotifyCollectionChangedEventHandler? value) + { + var combined = (NotifyCollectionChangedEventHandler?)Delegate.Combine(current, value); + var original = Interlocked.CompareExchange(ref field, combined, current); + if (ReferenceEquals(original, current)) + { + return true; + } + + current = original; + return false; + } + + /// Removes a handler from a handler list once, unless another thread changed the list since it was read. + /// The handler list field. + /// The list as last read; replaced with the list now stored when the swap loses. + /// The handler to remove. + /// when the handler was removed; when was stale. + internal static bool TryRemove(ref NotifyCollectionChangedEventHandler? field, ref NotifyCollectionChangedEventHandler? current, NotifyCollectionChangedEventHandler? value) + { + var remaining = (NotifyCollectionChangedEventHandler?)Delegate.Remove(current, value); + var original = Interlocked.CompareExchange(ref field, remaining, current); + if (ReferenceEquals(original, current)) + { + return true; + } + + current = original; + return false; + } + + /// Removes a collection-changed handler without losing concurrent changes. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The handler to remove. + internal static void RemoveCollectionChangedHandler(QuaternaryState state, NotifyCollectionChangedEventHandler? value) + where TItem : notnull + { + var current = Volatile.Read(ref state.CollectionChanged); + while (current is not null && !TryRemove(ref state.CollectionChanged, ref current, value)) + { + // Another thread changed the handler list first; try again against the list it left. + } + } + + /// Delivers one queued notification to the stream observers. + /// The element type of the pipeline. + /// The signal feeding the observers. + /// The notification to deliver. + internal static void DeliverToObservers(Signal pipeline, TPayload notification) + { + try + { + pipeline.OnNext(notification); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // Observers are wrapped so they cannot throw here; this guards the pipeline itself. + } + } + + /// Creates and caches the notification observable. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The notification observable. + private static QuaternaryStreamSource CreateStream(QuaternaryState state) + where TItem : notnull + { + var created = new QuaternaryStreamSource(state); + return Interlocked.CompareExchange(ref state.Stream, created, null) ?? created; + } + + /// Creates and caches the versioned notification observable. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The versioned notification observable. + private static QuaternaryVersionedStreamSource CreateVersionedStream(QuaternaryState state) + where TItem : notnull + { + var created = new QuaternaryVersionedStreamSource(state); + return Interlocked.CompareExchange(ref state.VersionedStream, created, null) ?? created; + } + + /// Creates the channel and pipelines and starts the reader under the startup gate. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// when the processor is running; when the collection is disposed. + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool StartEventProcessor(QuaternaryState state) + where TItem : notnull + { + var gate = Volatile.Read(ref state.EventGate); + if (gate is null) + { + var created = new Lock(); + gate = Interlocked.CompareExchange(ref state.EventGate, created, null) ?? created; + } + + lock (gate) + { + if (state.EventProcessorStarted != 0) + { + return true; + } + + if (Volatile.Read(ref state.Disposed) != 0) + { + return false; + } + + var channel = Channel.CreateUnbounded>( + new UnboundedChannelOptions { SingleReader = true, SingleWriter = false, AllowSynchronousContinuations = false }); + Signal> pipeline = new(); + Signal> versionedPipeline = new(); + Volatile.Write(ref state.Pipeline, pipeline); + Volatile.Write(ref state.VersionedPipeline, versionedPipeline); + Volatile.Write(ref state.EventChannel, channel); + _ = ProcessEventsAsync(state, channel, pipeline, versionedPipeline); + + // Disposal can complete before the channel is published. Once published, either side can close it. + if (Volatile.Read(ref state.Disposed) != 0) + { + _ = channel.Writer.TryComplete(); + return false; + } + + Volatile.Write(ref state.EventProcessorStarted, 1); + return true; + } + } + + /// Reads queued notifications until the channel completes, then completes the pipelines. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The channel to drain. + /// The signal feeding the observers. + /// The signal feeding the observers that also want each notification's version. + /// A task that completes when the collection is disposed and the queue is drained. + private static async Task ProcessEventsAsync( + QuaternaryState state, + Channel> channel, + Signal> pipeline, + Signal> versionedPipeline) + where TItem : notnull + { + var reader = channel.Reader; + while (await reader.WaitToReadAsync(CancellationToken.None).ConfigureAwait(false)) + { + while (reader.TryRead(out var queued)) + { + DeliverToObservers(pipeline, queued.Notification); + + // Keep the existing upsert payload on Stream. A versioned snapshot consumer cannot apply it as appends. + var notification = queued.RequiresSnapshot ? new(CacheAction.BatchOperation, default) : queued.Notification; + DeliverToObservers(versionedPipeline, new(notification, queued.Version)); + + var handler = Volatile.Read(ref state.CollectionChanged); + if (handler is not null) + { + InvokeLegacyHandler(state, handler); + } + } + } + + pipeline.OnCompleted(); + pipeline.Dispose(); + versionedPipeline.OnCompleted(); + versionedPipeline.Dispose(); + } + + /// Raises the CollectionChanged event using legacy INotifyCollectionChanged semantics. + /// The item type. + /// The secondary index value type. + /// The collection state. + /// The handlers to invoke. + /// Every change is reported as a Reset because a sharded collection has no stable item index. The event is + /// dispatched on the captured synchronization context if available, and a handler that throws does not stop later events. + private static void InvokeLegacyHandler(QuaternaryState state, NotifyCollectionChangedEventHandler handler) + where TItem : notnull + { + var owner = Volatile.Read(ref state.Owner); + if (state.SyncContext is null) + { + InvokeHandlerSafely(owner, handler); + return; + } + + state.SyncContext.Post( + static dispatch => + { + var target = (LegacyDispatch)dispatch!; + InvokeHandlerSafely(target.Owner, target.Handler); + }, + new LegacyDispatch(owner, handler)); + } + + /// Invokes a collection-changed handler and swallows its exceptions. + /// The collection raising the event. + /// The handler to invoke. + private static void InvokeHandlerSafely(object? owner, NotifyCollectionChangedEventHandler handler) + { + try + { + handler(owner, ResetEventArgs); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // A faulty handler must not stop later notifications. + } + } + + /// Carries a legacy handler invocation to the captured synchronization context. + /// The collection raising the event. + /// The handlers to invoke. + private sealed record LegacyDispatch(object? Owner, NotifyCollectionChangedEventHandler Handler); +} diff --git a/src/ReactiveList/Internal/QuaternaryIndexTable.cs b/src/ReactiveList/Internal/QuaternaryIndexTable.cs new file mode 100644 index 00000000..6726c6db --- /dev/null +++ b/src/ReactiveList/Internal/QuaternaryIndexTable.cs @@ -0,0 +1,72 @@ +// 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 + +/// Finds and registers the secondary indexes of a sharded collection, which keeps them in one array of named entries. +/// An array is never changed after it is published. Registering an index builds a new array, so readers that hold one +/// need no lock and a collection without indexes pays for no array at all. +internal static class QuaternaryIndexTable +{ + /// Creates the array that results from registering an index, replacing an index of the same name. + /// The secondary index value type. + /// The array before the registration, or when no index exists. + /// The index name. + /// The index to register. + /// The new array. + internal static IndexEntry[] With(IndexEntry[]? current, string name, ISecondaryIndex index) + { + if (current is null) + { + return [new(name, index)]; + } + + var position = IndexOf(current, name); + var entries = new IndexEntry[position >= 0 ? current.Length : current.Length + 1]; + current.CopyTo(entries, 0); + entries[position >= 0 ? position : current.Length] = new(name, index); + return entries; + } + + /// Finds the index registered under a name. + /// The secondary index value type. + /// The registered indexes. + /// The index name. + /// Receives the index when one is registered under the name. + /// when an index with that name exists. + internal static bool TryGet(IndexEntry[] entries, string name, [MaybeNullWhen(false)] out ISecondaryIndex index) + { + var position = IndexOf(entries, name); + if (position < 0) + { + index = default; + return false; + } + + index = entries[position].Index; + return true; + } + + /// Gets the position of an index name. + /// The secondary index value type. + /// The registered indexes. + /// The index name. + /// The position, or -1 when the name is not registered. + private static int IndexOf(IndexEntry[] entries, string name) + { + for (var i = 0; i < entries.Length; i++) + { + if (string.Equals(entries[i].Name, name, StringComparison.Ordinal)) + { + return i; + } + } + + return -1; + } +} diff --git a/src/ReactiveList/Internal/QuaternaryShardHelpers.cs b/src/ReactiveList/Internal/QuaternaryShardHelpers.cs index a597786c..0ba70c6e 100644 --- a/src/ReactiveList/Internal/QuaternaryShardHelpers.cs +++ b/src/ReactiveList/Internal/QuaternaryShardHelpers.cs @@ -13,14 +13,23 @@ internal static class QuaternaryShardHelpers { /// Acquires write locks on every shard in strict ascending index order. /// The shard locks to enter. - [MethodImpl(MethodImplOptions.AggressiveInlining)] + /// If a lock cannot be taken, the locks already held are released before the exception propagates. internal static void EnterAllWriteLocks(ReaderWriterLockSlim[] locks) { - ThrowHelper.ThrowIfNull(locks); + ArgumentExceptionHelper.ThrowIfNull(locks); - for (var i = 0; i < locks.Length; i++) + var acquired = 0; + try + { + for (; acquired < locks.Length; acquired++) + { + locks[acquired].EnterWriteLock(); + } + } + catch { - locks[i].EnterWriteLock(); + ExitWriteLocks(locks, acquired); + throw; } } @@ -29,14 +38,43 @@ internal static void EnterAllWriteLocks(ReaderWriterLockSlim[] locks) [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void ExitAllWriteLocks(ReaderWriterLockSlim[] locks) { - ThrowHelper.ThrowIfNull(locks); + ArgumentExceptionHelper.ThrowIfNull(locks); + + ExitWriteLocks(locks, locks.Length); + } + + /// Acquires read locks on every shard in strict ascending index order. + /// The shard locks to enter. + /// If a lock cannot be taken, the locks already held are released before the exception propagates. + internal static void EnterAllReadLocks(ReaderWriterLockSlim[] locks) + { + ArgumentExceptionHelper.ThrowIfNull(locks); - for (var i = locks.Length - 1; i >= 0; i--) + var acquired = 0; + try { - locks[i].ExitWriteLock(); + for (; acquired < locks.Length; acquired++) + { + locks[acquired].EnterReadLock(); + } + } + catch + { + ExitReadLocks(locks, acquired); + throw; } } + /// Releases read locks on every shard in reverse index order. + /// The shard locks to exit. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void ExitAllReadLocks(ReaderWriterLockSlim[] locks) + { + ArgumentExceptionHelper.ThrowIfNull(locks); + + ExitReadLocks(locks, locks.Length); + } + /// Appends an item to a lazily rented pooled buffer, growing the buffer when full. /// The element type stored in the buffer. /// The rented array reference, initialized on first append. @@ -70,7 +108,7 @@ internal static void AppendPooled( [MethodImpl(MethodImplOptions.NoInlining)] internal static void GrowPooledBuffer(ref T[] buffer, int activeCount, int growthFactor) { - ThrowHelper.ThrowIfNull(buffer); + ArgumentExceptionHelper.ThrowIfNull(buffer); var nextCapacity = Math.Max(1, buffer.Length * growthFactor); var expanded = ArrayPool.Shared.Rent(nextCapacity); @@ -93,9 +131,9 @@ internal static List CollectFromShardsReadLocked( int initialCapacity, Action> copyShard) { - ThrowHelper.ThrowIfNull(locks); - ThrowHelper.ThrowIfNull(shards); - ThrowHelper.ThrowIfNull(copyShard); + ArgumentExceptionHelper.ThrowIfNull(locks); + ArgumentExceptionHelper.ThrowIfNull(shards); + ArgumentExceptionHelper.ThrowIfNull(copyShard); var result = new List(Math.Max(0, initialCapacity)); for (var i = 0; i < shards.Length; i++) @@ -126,8 +164,8 @@ internal static List CollectFromShardsUnsafe( int initialCapacity, Action> copyShard) { - ThrowHelper.ThrowIfNull(shards); - ThrowHelper.ThrowIfNull(copyShard); + ArgumentExceptionHelper.ThrowIfNull(shards); + ArgumentExceptionHelper.ThrowIfNull(copyShard); var result = new List(Math.Max(0, initialCapacity)); for (var i = 0; i < shards.Length; i++) @@ -151,7 +189,7 @@ internal static ShardPartitionSummary PartitionSpan( Span shardCounts, Func getShard) { - ThrowHelper.ThrowIfNull(getShard); + ArgumentExceptionHelper.ThrowIfNull(getShard); shardCounts.Clear(); var mask = 0; @@ -181,8 +219,8 @@ internal static ShardPartitionSummary PartitionList( Span shardCounts, Func getShard) { - ThrowHelper.ThrowIfNull(items); - ThrowHelper.ThrowIfNull(getShard); + ArgumentExceptionHelper.ThrowIfNull(items); + ArgumentExceptionHelper.ThrowIfNull(getShard); shardCounts.Clear(); var mask = 0; @@ -196,4 +234,26 @@ internal static ShardPartitionSummary PartitionList( return new(count, mask); } + + /// Releases the first read locks in reverse index order. + /// The shard locks. + /// The number of leading locks that are held. + internal static void ExitReadLocks(ReaderWriterLockSlim[] locks, int held) + { + for (var i = held - 1; i >= 0; i--) + { + locks[i].ExitReadLock(); + } + } + + /// Releases the first write locks in reverse index order. + /// The shard locks. + /// The number of leading locks that are held. + private static void ExitWriteLocks(ReaderWriterLockSlim[] locks, int held) + { + for (var i = held - 1; i >= 0; i--) + { + locks[i].ExitWriteLock(); + } + } } diff --git a/src/ReactiveList/Internal/QuaternaryState.cs b/src/ReactiveList/Internal/QuaternaryState.cs new file mode 100644 index 00000000..a06f5c6a --- /dev/null +++ b/src/ReactiveList/Internal/QuaternaryState.cs @@ -0,0 +1,120 @@ +// 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 everything one sharded collection shares between its public methods and the static helpers. +/// The item type. +/// The secondary index value type. +/// The shard containers. +/// The per-shard reader-writer locks. +/// The per-shard counters. +/// The synchronization context captured when the collection was created. +/// The name of the collection type, reported by . +/// The mutable members are exposed as properties because they are changed through +/// and . The static helpers in and +/// are the only code that works on them. +[System.Diagnostics.DebuggerDisplay("Disposed = {_disposed}")] +internal sealed record QuaternaryState( + IQuad[] Quads, + ReaderWriterLockSlim[] Locks, + ShardCounter[] Shards, + SynchronizationContext? SyncContext, + string ObjectName) + where TItem : notnull +{ + /// The collection that owns this state; it is the sender of legacy change events. + private object? _owner; + + /// The channel used to queue collection notifications. + private Channel>? _eventChannel; + + /// The lazily created gate protecting event processor startup. + private Lock? _eventGate; + + /// The signal that publishes queued notifications. + private Signal>? _pipeline; + + /// The signal that publishes queued notifications together with their versions. + private Signal>? _versionedPipeline; + + /// The cached observable of notifications. + private QuaternaryStreamSource? _stream; + + /// The cached observable of versioned notifications. + private QuaternaryVersionedStreamSource? _versionedStream; + + /// The currently registered collection-change handlers. + private NotifyCollectionChangedEventHandler? _collectionChanged; + + /// The registered indexes, or while the collection has none. + private IndexEntry[]? _indexes; + + /// Indicates whether the event processor has started. + private int _eventProcessorStarted; + + /// The number of active stream subscribers. + private int _subscriberCount; + + /// Set to one once the collection is disposed. + private int _disposed; + + /// The version incremented by each change that someone observes. + private long _version; + + /// The number of notification deferrals currently open. + private int _deferralDepth; + + /// The version recorded when the first deferral started. + private long _deferralVersion; + + /// Gets a reference to the collection that owns this state. + internal ref object? Owner => ref _owner; + + /// Gets a reference to the channel used to queue collection notifications. + internal ref Channel>? EventChannel => ref _eventChannel; + + /// Gets a reference to the gate protecting event processor startup. + internal ref Lock? EventGate => ref _eventGate; + + /// Gets a reference to the signal that publishes queued notifications. + internal ref Signal>? Pipeline => ref _pipeline; + + /// Gets a reference to the signal that publishes notifications together with their versions. + internal ref Signal>? VersionedPipeline => ref _versionedPipeline; + + /// Gets a reference to the cached observable of notifications. + internal ref QuaternaryStreamSource? Stream => ref _stream; + + /// Gets a reference to the cached observable of versioned notifications. + internal ref QuaternaryVersionedStreamSource? VersionedStream => ref _versionedStream; + + /// Gets a reference to the registered collection-change handlers. + internal ref NotifyCollectionChangedEventHandler? CollectionChanged => ref _collectionChanged; + + /// Gets a reference to the registered indexes. + internal ref IndexEntry[]? Indexes => ref _indexes; + + /// Gets a reference to the flag that says whether the event processor has started. + internal ref int EventProcessorStarted => ref _eventProcessorStarted; + + /// Gets a reference to the number of active stream subscribers. + internal ref int SubscriberCount => ref _subscriberCount; + + /// Gets a reference to the flag that is set to one once the collection is disposed. + internal ref int Disposed => ref _disposed; + + /// Gets a reference to the version incremented by each change that someone observes. + internal ref long Version => ref _version; + + /// Gets the number of active deferrals, written only while every shard lock is held. + internal ref int DeferralDepth => ref _deferralDepth; + + /// Gets the collection version at the start of the first active deferral. + internal ref long DeferralVersion => ref _deferralVersion; +} diff --git a/src/ReactiveList/Internal/QuaternaryStreamSource.cs b/src/ReactiveList/Internal/QuaternaryStreamSource.cs new file mode 100644 index 00000000..dacebf15 --- /dev/null +++ b/src/ReactiveList/Internal/QuaternaryStreamSource.cs @@ -0,0 +1,32 @@ +// 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 observable of change notifications for one sharded collection. +/// The item type. +/// The secondary index value type. +/// The state of the collection that publishes the notifications. +[System.Diagnostics.DebuggerDisplay("QuaternaryStreamSource")] +internal sealed class QuaternaryStreamSource(QuaternaryState state) : IObservable> + where TItem : notnull +{ + /// + public IDisposable Subscribe(IObserver> observer) + { + ArgumentExceptionHelper.ThrowIfNull(observer); + + if (Volatile.Read(ref state.Disposed) != 0 || !QuaternaryEvents.EnsureEventProcessorStarted(state)) + { + observer.OnCompleted(); + return Scope.Empty; + } + + return QuaternaryEvents.Attach(state, observer, Volatile.Read(ref state.Pipeline)!); + } +} diff --git a/src/ReactiveList/Internal/QuaternarySubscription.cs b/src/ReactiveList/Internal/QuaternarySubscription.cs new file mode 100644 index 00000000..9da29123 --- /dev/null +++ b/src/ReactiveList/Internal/QuaternarySubscription.cs @@ -0,0 +1,126 @@ +// 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 + +/// Wraps one observer so its faults and its disposal are accounted for exactly once. +/// The item type. +/// The secondary index value type. +/// The element type the observer receives. +[System.Diagnostics.DebuggerDisplay("QuaternarySubscription")] +internal sealed class QuaternarySubscription : IObserver, IDisposable + where TItem : notnull +{ + /// The collection state whose observer count this subscription holds. + private readonly QuaternaryState _state; + + /// The observer receiving notifications. + private readonly IObserver _downstream; + + /// The subscription to the shared pipeline. + private IDisposable? _inner; + + /// Set to one once this subscription is disposed. + private int _disposed; + + /// Initializes a new instance of the class. + /// The collection state whose observer count this subscription holds. + /// The observer receiving notifications. + internal QuaternarySubscription(QuaternaryState state, IObserver downstream) + { + _state = state; + _downstream = downstream; + } + + /// + public void OnNext(TPayload value) + { + if (Volatile.Read(ref _disposed) != 0) + { + return; + } + + try + { + _downstream.OnNext(value); + } + catch (Exception ex) + { + Fault(ex); + } + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnError(Exception error) => Fault(error); + + /// + public void OnCompleted() + { + if (Volatile.Read(ref _disposed) != 0) + { + return; + } + + try + { + _downstream.OnCompleted(); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // A faulty observer must not affect the others. + } + finally + { + Dispose(); + } + } + + /// + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + Volatile.Read(ref _inner)?.Dispose(); + _ = Interlocked.Decrement(ref _state.SubscriberCount); + } + + /// Stores the pipeline subscription, disposing it at once if this subscription already ended. + /// The pipeline subscription. + internal void Attach(IDisposable inner) + { + Volatile.Write(ref _inner, inner); + if (Volatile.Read(ref _disposed) != 0) + { + inner.Dispose(); + } + } + + /// Ends this subscription and reports the exception to its observer. + /// The exception to report. + private void Fault(Exception error) + { + if (Volatile.Read(ref _disposed) != 0) + { + return; + } + + Dispose(); + try + { + _downstream.OnError(error); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // The observer already failed; nothing more can be done. + } + } +} diff --git a/src/ReactiveList/Internal/QuaternaryVersionedStreamSource.cs b/src/ReactiveList/Internal/QuaternaryVersionedStreamSource.cs new file mode 100644 index 00000000..cb17421d --- /dev/null +++ b/src/ReactiveList/Internal/QuaternaryVersionedStreamSource.cs @@ -0,0 +1,32 @@ +// 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 observable of versioned change notifications for one sharded collection. +/// The item type. +/// The secondary index value type. +/// The state of the collection that publishes the notifications. +[System.Diagnostics.DebuggerDisplay("QuaternaryVersionedStreamSource")] +internal sealed class QuaternaryVersionedStreamSource(QuaternaryState state) : IObservable> + where TItem : notnull +{ + /// + public IDisposable Subscribe(IObserver> observer) + { + ArgumentExceptionHelper.ThrowIfNull(observer); + + if (Volatile.Read(ref state.Disposed) != 0 || !QuaternaryEvents.EnsureEventProcessorStarted(state)) + { + observer.OnCompleted(); + return Scope.Empty; + } + + return QuaternaryEvents.Attach(state, observer, Volatile.Read(ref state.VersionedPipeline)!); + } +} diff --git a/src/ReactiveList/Internal/QueuedNotification.cs b/src/ReactiveList/Internal/QueuedNotification.cs new file mode 100644 index 00000000..71497755 --- /dev/null +++ b/src/ReactiveList/Internal/QueuedNotification.cs @@ -0,0 +1,17 @@ +// 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 queued notification together with the collection version its change produced. +/// The item type. +/// The notification. +/// The version after the change. +/// Whether a versioned observer must read a new snapshot instead of applying this payload. +[System.Diagnostics.DebuggerDisplay("Version = {Version}")] +internal readonly record struct QueuedNotification(CacheNotify Notification, long Version, bool RequiresSnapshot = false); diff --git a/src/ReactiveList/Internal/RangeObservableCollection.cs b/src/ReactiveList/Internal/RangeObservableCollection.cs new file mode 100644 index 00000000..1620d6ea --- /dev/null +++ b/src/ReactiveList/Internal/RangeObservableCollection.cs @@ -0,0 +1,111 @@ +// 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 applies range changes with a single reset notification. +/// The item type. +internal sealed class RangeObservableCollection : ObservableCollection +{ + /// The cached property-change arguments for count updates. + private static readonly PropertyChangedEventArgs CountChangedEventArgs = new(nameof(Count)); + + /// The cached property-change arguments for indexed item updates. + private static readonly PropertyChangedEventArgs ItemArrayChangedEventArgs = new("Item[]"); + + /// The cached collection-reset event arguments. + private static readonly NotifyCollectionChangedEventArgs ResetEventArgs = new(NotifyCollectionChangedAction.Reset); + + /// Initializes a new instance of the class. + public RangeObservableCollection() + { + } + + /// Initializes a new instance of the class with a copy of . + /// The initial items. + public RangeObservableCollection(List items) + : base(new List(items)) + { + } + + /// Gets or sets the list sequence number of the last change applied; changes at or below it are skipped. + public long AppliedSequence { get; set; } + + /// Gets the backing list; both constructors store the items in a . + private List Backing => (List)Items; + + /// Inserts items at an index and raises one reset. + /// The insertion index. + /// The items to insert. + internal void InsertRange(int index, T[] items) + { + if (items.Length == 0) + { + return; + } + + CheckReentrancy(); + var list = Backing; + ListCompat.EnsureCapacity(list, list.Count + items.Length); + list.InsertRange(index, items); + RaiseReset(); + } + + /// Replaces the contents and raises one reset, unless both the old and new contents are empty. + /// The new contents. + internal void ReplaceAll(T[] items) + { + if (items.Length == 0 && Items.Count == 0) + { + return; + } + + CheckReentrancy(); + var list = Backing; + list.Clear(); + ListCompat.EnsureCapacity(list, items.Length); + list.AddRange(items); + RaiseReset(); + } + + /// Empties the collection and raises a reset when it held items. + internal void ClearIfNotEmpty() + { + if (Items.Count == 0) + { + return; + } + + CheckReentrancy(); + Items.Clear(); + RaiseReset(); + } + + /// Removes a contiguous range and raises one reset. + /// The first index to remove. + /// The number of items to remove. + internal void RemoveRange(int index, int count) + { + if (count == 0) + { + return; + } + + CheckReentrancy(); + Backing.RemoveRange(index, count); + RaiseReset(); + } + + /// Raises the count, indexer and reset notifications. + private void RaiseReset() + { + OnPropertyChanged(CountChangedEventArgs); + OnPropertyChanged(ItemArrayChangedEventArgs); + OnCollectionChanged(ResetEventArgs); + } +} diff --git a/src/ReactiveList/Internal/ReactiveListScheduler.cs b/src/ReactiveList/Internal/ReactiveListScheduler.cs index 43bb69a9..bbe5f9f6 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 @@ -34,8 +43,8 @@ internal static class ReactiveListScheduler /// The scheduled action disposable. internal static IDisposable Schedule(ISequencer scheduler, TimeSpan dueTime, Action action) { - ThrowHelper.ThrowIfNull(scheduler); - ThrowHelper.ThrowIfNull(action); + ArgumentExceptionHelper.ThrowIfNull(scheduler); + ArgumentExceptionHelper.ThrowIfNull(action); #if REACTIVELIST_REACTIVE return System.Reactive.Concurrency.Scheduler.Schedule(scheduler, dueTime, action); diff --git a/src/ReactiveList/Internal/ReactiveViewHelpers.cs b/src/ReactiveList/Internal/ReactiveViewHelpers.cs index 7f6b409f..0d65dfda 100644 --- a/src/ReactiveList/Internal/ReactiveViewHelpers.cs +++ b/src/ReactiveList/Internal/ReactiveViewHelpers.cs @@ -11,6 +11,17 @@ namespace ReactiveList.Internal; /// Provides stateless helpers shared across reactive view facades and view factory extensions. internal static class ReactiveViewHelpers { + /// Checks a batch reset limit a caller assigns to a view. + /// The assigned limit. + /// The limit. + /// is negative. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int CheckedResetLimit(int value) + { + ArgumentOutOfRangeExceptionHelper.ThrowIfNegative(value); + return value; + } + /// Validates view factory arguments and resolves the effective sequencer and throttle window. /// The source collection type. /// The required selector, comparer, or filter argument type. @@ -32,8 +43,8 @@ internal static ViewDispatchOptions ResolveListViewOptions( where TSource : class where TArgument : class { - ThrowHelper.ThrowIfNull(source, sourceParamName); - ThrowHelper.ThrowIfNull(argument, argumentParamName); + ArgumentExceptionHelper.ThrowIfNull(source, sourceParamName); + ArgumentExceptionHelper.ThrowIfNull(argument, argumentParamName); return new(scheduler ?? ReactiveListScheduler.CurrentThread, TimeSpan.FromMilliseconds(throttleMs)); } @@ -44,7 +55,7 @@ internal static ViewDispatchOptions ResolveListViewOptions( /// An describing whether an initial value was captured. internal static InitialEmission ProbeInitialValue(IObservable source) { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); var hasValue = false; T? captured = default; @@ -77,100 +88,60 @@ internal static TView BindToProperty( ReadOnlyObservableCollection items, Action> propertySetter) { - ThrowHelper.ThrowIfNull(propertySetter); + ArgumentExceptionHelper.ThrowIfNull(propertySetter); propertySetter(items); return view; } - /// Subscribes to source change sets with optional throttling and sequencer observation. - /// The non-nullable element type carried by the list. - /// The reactive source list. - /// The throttle duration, or to disable throttling. - /// The sequencer on which change sets are observed. - /// The callback invoked for each observed change set. - /// The active subscription. - internal static IDisposable SubscribeChangeSets( - IReactiveList source, - TimeSpan throttle, - ISequencer scheduler, - Action> onNext) - where T : notnull + /// Creates the property-change signal of a view, or returns the one another thread installed first. + /// The field that holds the signal. + /// The disposal flag of the view, non-zero once disposed. + /// The signal in the slot. + internal static Signal CreateSignal(ref Signal? slot, ref int disposed) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(scheduler); - ThrowHelper.ThrowIfNull(onNext); - - var updates = source.Stream.ToChangeSets(); - if (throttle != TimeSpan.Zero) + Signal created = new(); + if (Interlocked.CompareExchange(ref slot, created, null) is { } existing) { - updates = updates.Throttle(throttle); + created.Dispose(); + return existing; } - return updates - .ObserveOn(scheduler) - .Subscribe(onNext); - } - - /// Appends an item to when it is non-null and satisfies . - /// The non-nullable element type stored in the collection. - /// The mutable target collection. - /// The candidate item. - /// The membership predicate. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static void AddMatchingItem( - ObservableCollection target, - T? item, - Func filter) - where T : notnull - { - if (item is null || !filter(item)) + // A signal created after disposal is disposed at once, the way a signal that was disposed with the view behaves. + if (Volatile.Read(ref disposed) != 0) { - return; + created.Dispose(); } - target.Add(item); + return created; } - /// Appends every item from that satisfies . - /// The non-nullable element type stored in the collection. - /// The mutable target collection. - /// The optional pooled batch of candidate items. - /// The membership predicate. - internal static void AddMatchingBatch( - ObservableCollection target, - PooledBatch? batch, - Func filter) - where T : notnull + /// Publishes a property change to the observers of a view, tolerating a disposal that races with the publication. + /// The signal that has observers. + /// The gate that disposal closes; the publication runs inside it, so disposal waits for it. + /// The change to publish. + /// The disposal flag of the view, non-zero once disposed. + internal static void PublishChange(Signal signal, DisposalGate gate, PropertyChangedEventArgs args, ref int disposed) { - if (batch is null) + if (!gate.TryEnter()) { return; } - for (var i = 0; i < batch.Count; i++) + try { - AddMatchingItem(target, batch.Items[i], filter); + if (signal.HasObservers) + { + signal.OnNext(args); + } } - } - - /// Removes every item present in from . - /// The non-nullable element type stored in the collection. - /// The mutable target collection. - /// The optional pooled batch of removed items. - internal static void RemoveBatch( - ObservableCollection target, - PooledBatch? batch) - where T : notnull - { - if (batch is null) + catch (ObjectDisposedException) when (Volatile.Read(ref disposed) != 0) { - return; + // The view was disposed while this drain was publishing, so nobody is listening any more. } - - for (var i = 0; i < batch.Count; i++) + finally { - _ = target.Remove(batch.Items[i]); + gate.Exit(); } } } diff --git a/src/ReactiveList/Internal/ScheduledHandle.cs b/src/ReactiveList/Internal/ScheduledHandle.cs new file mode 100644 index 00000000..cf01eebf --- /dev/null +++ b/src/ReactiveList/Internal/ScheduledHandle.cs @@ -0,0 +1,14 @@ +// 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 scheduled drain handle numbered in the order the drains were requested. +/// The request number. +/// The handle returned by the scheduler. +internal sealed record ScheduledHandle(long Ticket, IDisposable Handle); diff --git a/src/ReactiveList/Internal/SerializedObserver.cs b/src/ReactiveList/Internal/SerializedObserver.cs new file mode 100644 index 00000000..0511303c --- /dev/null +++ b/src/ReactiveList/Internal/SerializedObserver.cs @@ -0,0 +1,134 @@ +// 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 + +/// +/// Forwards notifications from several threads to one observer so the observer sees a serialized sequence. Notifications queue while another thread is +/// delivering, are delivered outside any lock, and stop after the first terminal notification or after . +/// +/// The notification value type. +/// The observer that receives the serialized notifications. +internal sealed class SerializedObserver(IObserver observer) : IObserver +{ + /// Guards the queue and the flags. + private readonly Lock _gate = new(); + + /// The notifications waiting for the delivering thread. + private readonly Queue _pending = []; + + /// Whether a thread is currently delivering. + private bool _delivering; + + /// Whether a terminal notification was queued or the observer was stopped. + private bool _done; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnNext(T value) => Enqueue(new(value, null, false), terminal: false); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnError(Exception error) => Enqueue(new(default, error, false), terminal: true); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted() => Enqueue(new(default, null, true), terminal: true); + + /// Drops queued notifications and ignores later ones. + internal void Stop() + { + lock (_gate) + { + _done = true; + _pending.Clear(); + } + } + + /// Queues a notification and delivers when no other thread is. + /// The notification. + /// Whether it ends the sequence. + private void Enqueue(in Pending notification, bool terminal) + { + lock (_gate) + { + if (_done) + { + return; + } + + _done = terminal; + _pending.Enqueue(notification); + if (_delivering) + { + return; + } + + _delivering = true; + } + + Drain(); + } + + /// Delivers queued notifications until none remain; the delivery flag is released even when the observer throws. + private void Drain() + { + while (true) + { + Pending next; + lock (_gate) + { + if (_pending.Count == 0) + { + _delivering = false; + return; + } + + next = _pending.Dequeue(); + } + + try + { + Deliver(in next); + } + catch + { + lock (_gate) + { + _delivering = false; + } + + throw; + } + } + } + + /// Sends one notification to the observer. + /// The notification. + private void Deliver(in Pending notification) + { + if (notification.Error is not null) + { + observer.OnError(notification.Error); + } + else if (notification.Completed) + { + observer.OnCompleted(); + } + else + { + observer.OnNext(notification.Value!); + } + } + + /// A notification waiting to be delivered. + /// The value of a value notification. + /// The error of an error notification. + /// Whether this is the completion notification. + private readonly record struct Pending(T? Value, Exception? Error, bool Completed); +} diff --git a/src/ReactiveList/Internal/ShardCounter.cs b/src/ReactiveList/Internal/ShardCounter.cs new file mode 100644 index 00000000..7940f8a3 --- /dev/null +++ b/src/ReactiveList/Internal/ShardCounter.cs @@ -0,0 +1,41 @@ +// 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 unobserved-change count of one shard on a cache line of its own. +/// The counter is written while the owning shard lock is held, so shards that are written at the same time do not +/// share a cache line. Four of these live in one array, and the 64 byte size keeps each shard's counter on a separate line. +[System.Diagnostics.DebuggerDisplay("UnobservedVersion = {_unobservedVersion}")] +[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit, Size = 64)] +internal struct ShardCounter : IEquatable +{ + /// The number of changes made while nobody observed the collection. + [System.Runtime.InteropServices.FieldOffset(0)] + private long _unobservedVersion; + + /// Gets the number of changes made while nobody observed the collection. + internal long UnobservedVersion + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Volatile.Read(ref _unobservedVersion); + } + + /// + public readonly bool Equals(ShardCounter other) => _unobservedVersion == other._unobservedVersion; + + /// + public override readonly bool Equals(object? obj) => obj is ShardCounter other && Equals(other); + + /// + public override readonly int GetHashCode() => 0; + + /// Records one unobserved change; call while the shard write lock is held. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void BumpVersion() => Volatile.Write(ref _unobservedVersion, Volatile.Read(ref _unobservedVersion) + 1); +} diff --git a/src/ReactiveList/Internal/SignalSubscription.cs b/src/ReactiveList/Internal/SignalSubscription.cs new file mode 100644 index 00000000..399b4668 --- /dev/null +++ b/src/ReactiveList/Internal/SignalSubscription.cs @@ -0,0 +1,31 @@ +// 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 + +/// Subscribes observers to a collection's signals while tolerating disposal of the collection. +internal static class SignalSubscription +{ + /// Subscribes to a signal, treating a failure caused by disposal of the collection as the end of the stream. + /// The notification type. + /// The signal to subscribe to. + /// The subscriber. + /// The collection's disposal flag. + /// The subscription, or when disposal completed the signal before the subscriber attached. + internal static IDisposable? TrySubscribe(IObservable source, IObserver observer, ref int disposed) + { + try + { + return source.Subscribe(observer); + } + catch (ObjectDisposedException) when (Volatile.Read(ref disposed) != 0) + { + return null; + } + } +} diff --git a/src/ReactiveList/Internal/SkipLocalsInitAttribute.cs b/src/ReactiveList/Internal/SkipLocalsInitAttribute.cs deleted file mode 100644 index 880e1fa7..00000000 --- a/src/ReactiveList/Internal/SkipLocalsInitAttribute.cs +++ /dev/null @@ -1,29 +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 NETFRAMEWORK -namespace System.Runtime.CompilerServices; - -/// Indicates that local variables should not be zero-initialized. -[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Module)] -internal sealed class SkipLocalsInitAttribute : Attribute; -#elif REACTIVELIST_REACTIVE -namespace ReactiveList.Reactive.Internal; - -/// Marks the runtime-provided local-initialization compatibility path. -file enum SkipLocalsInitAttribute -{ - /// Indicates that the target runtime provides the attribute. - RuntimeProvided = 0, -} -#else -namespace ReactiveList.Internal; - -/// Marks the runtime-provided local-initialization compatibility path. -file enum SkipLocalsInitAttribute -{ - /// Indicates that the target runtime provides the attribute. - RuntimeProvided = 0, -} -#endif diff --git a/src/ReactiveList/Internal/SnapshotArrayEnumerator.cs b/src/ReactiveList/Internal/SnapshotArrayEnumerator.cs new file mode 100644 index 00000000..81d1ec22 --- /dev/null +++ b/src/ReactiveList/Internal/SnapshotArrayEnumerator.cs @@ -0,0 +1,68 @@ +// 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 + +/// Enumerates an immutable snapshot array; the exact sealed type lets the JIT devirtualize and inline the calls of a . +/// The element type. +internal sealed class SnapshotArrayEnumerator : IEnumerator +{ + /// The snapshot, which is never modified. + private readonly T[] _snapshot; + + /// The index of the current element, or -1 before the first and the length after the last. + private int _index = -1; + + /// Initializes a new instance of the class. + /// The immutable snapshot to enumerate. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal SnapshotArrayEnumerator(T[] snapshot) => _snapshot = snapshot; + + /// + public T Current + { + get + { + var snapshot = _snapshot; + var index = _index; + return (uint)index < (uint)snapshot.Length ? snapshot[index] : ThrowNotPositioned(); + } + } + + /// + object? IEnumerator.Current => Current; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool MoveNext() + { + var next = _index + 1; + if ((uint)next < (uint)_snapshot.Length) + { + _index = next; + return true; + } + + _index = _snapshot.Length; + return false; + } + + /// + public void Reset() => _index = -1; + + /// + public void Dispose() + { + } + + /// Throws the exception for reading the current element before the first or after the last. + /// Never returns. + /// Always thrown. + [MethodImpl(MethodImplOptions.NoInlining)] + private static T ThrowNotPositioned() => throw new InvalidOperationException("The enumerator is not positioned on an element."); +} diff --git a/src/ReactiveList/Internal/SortedViewEngine.cs b/src/ReactiveList/Internal/SortedViewEngine.cs new file mode 100644 index 00000000..9cbe9dd7 --- /dev/null +++ b/src/ReactiveList/Internal/SortedViewEngine.cs @@ -0,0 +1,242 @@ +// 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; + + /// The observable stream of collection-change notifications, created when something first asks for it. + private IObservable? _collectionChanges; + + /// Initializes a new instance of the class. + /// The source to project. + /// The comparer that orders the projection. + internal SortedViewEngine(IReactiveSource source, IComparer comparer) + { + ArgumentExceptionHelper.ThrowIfNull(comparer); + + _comparer = comparer; + _pump = new(source); + Sorted = new() { Gate = _pump.Gate }; + Items = new(Sorted); + try + { + // Nobody can listen yet, so the first fill raises no events. + Sorted.Populate(SortMirror()); + } + catch + { + // The constructor throws, so nobody else can dispose the source subscription. + _pump.Dispose(); + throw; + } + } + + /// Gets the observable stream of collection-change notifications. + internal IObservable CollectionChanges => + _collectionChanges ??= FacadeNotificationHelper.ObserveCollectionChanges(Sorted); + + /// 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(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void BatchStarted(int size) => Sorted.BeginBatch(size); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void BatchEnded() => Sorted.EndBatch(); + + /// + public void ItemsInserted(int index, int count) + { + if (count > Sorted.ResetLimit) + { + 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 && FitsAt(position, current)) + { + 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(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void MirrorReset() => Sorted.ReconcileTo([.. SortMirror()]); + + /// 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, coverSubscriptionGap: true); + + /// Rebuilds the projection from the live source on the calling thread. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void Refresh() => _pump.Refresh(); + + /// Copies the mirror and sorts the copy. + /// The mirror items in order. + private T[] SortMirror() + { + var items = Buffer.Items.ToArray(); + StableMergeSort.Sort(items, _comparer); + return items; + } + + /// Checks whether an item can occupy a position without breaking the order against its neighbours. + /// The position whose current item is being replaced. + /// The item that would take the position. + /// when the neighbours still compare in order. + private bool FitsAt(int position, T item) => + (position == 0 || _comparer.Compare(Sorted[position - 1], item) <= 0) + && (position + 1 >= Sorted.Count || _comparer.Compare(item, Sorted[position + 1]) <= 0); + + /// 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 (ItemComparison.SameItem(Sorted[i], item)) + { + return i; + } + } + + for (var i = 0; i < Sorted.Count; i++) + { + if (ItemComparison.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..7e579a24 --- /dev/null +++ b/src/ReactiveList/Internal/SourceSnapshot.cs @@ -0,0 +1,16 @@ +// 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. +/// The source revision the copy corresponds to. +internal readonly record struct SourceSnapshot(List Items, int SourceCount, long Version); 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/StreamProjection.cs b/src/ReactiveList/Internal/StreamProjection.cs new file mode 100644 index 00000000..11830802 --- /dev/null +++ b/src/ReactiveList/Internal/StreamProjection.cs @@ -0,0 +1,1097 @@ +// 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 + +/// +/// Projects an unordered notification stream into a collection. Incremental changes are applied as they arrive and the +/// projection is rebuilt from the source whenever a notification cannot be applied exactly or the projection drifts. +/// +/// The notification item type. +/// The projected element type. +internal sealed class StreamProjection : IDisposable, IObserver>, IObserver> + where TSource : notnull +{ + /// The cached property-change notification for the Items property. + private static readonly PropertyChangedEventArgs ItemsChangedArgs = new(nameof(Items)); + + /// The cached property-change notification for the Count property. + private static readonly PropertyChangedEventArgs CountChangedArgs = new("Count"); + + /// Synchronizes notification producers with the draining consumer. + private readonly Lock _gate = new(); + + /// Converts a notification item to a projected element. + private readonly Func _select; + + /// The source used for size checks, or when the projection cannot rebuild itself. + private readonly IReactiveSource? _source; + + /// Whether the source declares that items cannot change in place. + private readonly bool _ignoreRefreshes; + + /// The comparer that finds an element by value, or for the default search. + private readonly IEqualityComparer? _itemComparer; + + /// The cached property-change notification. + private readonly PropertyChangedEventArgs _changedArgs; + + /// Stops the target collection once the projection is disposed. + private readonly DisposalGate _closeGate = new(); + + /// The retained notifications, created when the first one has to wait. + private Queue>? _pending; + + /// Publishes property-change notifications, created when something first asks for them. + private Signal? _propertyChanges; + + /// The observable stream of collection-change notifications, created when something first asks for it. + private IObservable? _collectionChanges; + + /// The subscription to the stream. + private IDisposable? _subscription; + + /// Applies work queued by the owner inside the drain, or . + private Func? _applyQueued; + + /// Reports whether the owner has queued work, or . + private Func? _hasQueued; + + /// The handler for stream failures, or to rethrow them. + private Action? _onError; + + /// The handler for stream completion, or to ignore it. + private Action? _onCompleted; + + /// The dispatcher that coalesces drains. + private ViewDispatcher? _dispatcher; + + /// The active rules. + private ProjectionRules _rules; + + /// The rules waiting to be applied by the next drain. + private ProjectionRules? _pendingRules; + + /// The number of retained notifications, readable without the lock. + private int _pendingCount; + + /// The notification handed straight to the drain that owns the projection, or . Only the draining thread touches it. + private CacheNotify? _inline; + + /// The version of . + private long _inlineVersion; + + /// Whether the first build of the target raises no events because nobody can listen yet. + private bool _quietFirstFill; + + /// Whether a request drains on the calling thread at once, so the projection has no dispatcher. + private bool _immediate; + + /// Whether notifications are applied on the calling thread at once, so they can skip the queue. + private bool _runsInline; + + /// The number of source items implied by the notifications applied since the last rebuild. + private int _sourceCount; + + /// The source revision when the stream was subscribed, used to number notifications from sources that do not stamp them. + private long _sequenceBase; + + /// The number of notifications received from the stream. + private long _received; + + /// Notifications numbered up to this revision are already reflected in the last source copy. + private long _covered; + + /// Whether a source copy still has to be confirmed once the notifications that raced with it have arrived. + private bool _settlePending; + + /// Whether a notification was discarded because a source copy already contained it. + private bool _droppedCovered; + + /// Whether a notification was applied since the last source copy. + private bool _appliedSinceCopy; + + /// The number of full source copies made, for tests. + private int _resyncCount; + + /// Non-zero while a drain owns the projection. + private int _draining; + + /// Non-zero when a rebuild from the source was requested. + private int _resyncRequested; + + /// Non-zero once disposed. + private int _disposed; + + /// Non-zero once a read failed because the source was disposed. + private int _sourceGone; + + /// Initializes a new instance of the class. + /// The source, or for a bare stream. + /// Converts a notification item to a projected element. + /// The initial rules. + /// The property name raised after each applied drain. + /// Whether the facade reads the collection independently of the dispatcher. + /// Finds an element by value for element types whose default equality allocates, or . + internal StreamProjection( + IReactiveSource? source, + Func select, + ProjectionRules rules, + string changedProperty, + bool synchronizeReads = false, + IEqualityComparer? itemComparer = null) + { + ArgumentExceptionHelper.ThrowIfNull(select); + ArgumentExceptionHelper.ThrowIfNull(rules); + + _source = source; + _itemComparer = itemComparer; + _ignoreRefreshes = source is IReactiveSourceWithOptions { Options.ItemsAreImmutable: true }; + _select = select; + _rules = rules; + _changedArgs = changedProperty switch + { + "Items" => ItemsChangedArgs, + "Count" => CountChangedArgs, + _ => new(changedProperty) + }; + Target = new(synchronizeReads) { Gate = _closeGate }; + Items = new(Target); + } + + /// Gets the observable stream of collection-change notifications. + internal IObservable CollectionChanges => + _collectionChanges ??= FacadeNotificationHelper.ObserveCollectionChanges(Target); + + /// Gets the observable stream of property-change notifications. + internal IObservable PropertyChanges => Volatile.Read(ref _propertyChanges) ?? CreatePropertyChanges(); + + /// Gets the read-only projection. + internal ReadOnlyObservableCollection Items { get; } + + /// Gets the mutable projection. + internal BatchObservableCollection Target { get; } + + /// Gets the number of full source copies made so far. + internal int ResyncCount => Volatile.Read(ref _resyncCount); + + /// Gets a value indicating whether the projection was disposed or stopped because its source was disposed. + private bool IsDisposed => Volatile.Read(ref _disposed) != 0 || Volatile.Read(ref _sourceGone) != 0; + + /// Stops observing and releases retained notifications. + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + // Closing the gate stops the target collection from changing or raising anything more, including a drain that is + // blocked in user code right now. It does not wait, so disposing from a handler or the scheduler thread is safe. + _closeGate.Close(); + _dispatcher?.Dispose(); + ReleaseSubscription(); + DropPending(); + Interlocked.Exchange(ref _propertyChanges, null)?.Dispose(); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnNext(VersionedNotification value) => Enqueue(value.Notification, value.Version); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnNext(CacheNotify value) => Enqueue(value, null); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnError(Exception error) => (_onError ?? Rethrow)(error); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted() => _onCompleted?.Invoke(); + + /// Populates the projection from a snapshot taken before subscribing, then observes the stream. + /// The notification stream. + /// The items to filter into the projection. + /// The coalescing window. + /// The scheduler that applies changes. + internal void StartFromSnapshot( + IObservable> stream, + IEnumerable? initial, + TimeSpan throttle, + ISequencer scheduler) + { + if (initial is not null) + { + List matching = []; + foreach (var item in initial) + { + if (_rules.Matches(item)) + { + matching.Add(item); + } + } + + // This runs inside the owner's constructor, before anyone can listen, so it needs no events. + Target.Populate(matching); + } + + Subscribe(stream, throttle, scheduler); + } + + /// Observes the stream first and then builds the projection from the source so no change is lost. + /// The coalescing window. + /// The scheduler that applies changes. + /// An optional handler for stream failures. + /// An optional handler for stream completion. + /// Whether the owner guarantees nobody listens to the target yet, so the first build raises no events. + /// Applies work the owner queued, such as a window change, inside the drain without rebuilding from the source, or . + /// Reports whether the owner has queued work, or . + internal void StartFromSource( + TimeSpan throttle, + ISequencer scheduler, + Action? onError = null, + Action? onCompleted = null, + bool quietFirstFill = false, + Func? applyQueued = null, + Func? hasQueued = null) + { + _quietFirstFill = quietFirstFill; + _applyQueued = applyQueued; + _hasQueued = hasQueued; + Subscribe(null, throttle, scheduler, onError, onCompleted); + try + { + Refresh(); + } + catch + { + // The owner's constructor throws, so nobody else can dispose the subscription. + Dispose(); + throw; + } + } + + /// Queues new rules and rebuilds the projection from the source. + /// The new rules. + internal void SetRules(ProjectionRules rules) + { + Volatile.Write(ref _pendingRules, rules); + RequestDrain(); + } + + /// Asks the next drain to rebuild the projection from the source. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void RequestResync() => Volatile.Write(ref _resyncRequested, 1); + + /// Rebuilds the projection from the source on the calling thread. + internal void Refresh() + { + RequestResync(); + Drain(); + } + + /// Asks for a drain, on the calling thread when the view applies changes immediately and otherwise on the view scheduler. + internal void RequestDrain() + { + if (_immediate) + { + Drain(); + return; + } + + Volatile.Read(ref _dispatcher)?.Notify(); + } + + /// Applies queued work on the calling thread. + internal void Drain() + { + while (!IsDisposed) + { + if (Interlocked.Exchange(ref _draining, 1) != 0) + { + return; + } + + if (!RunOwned()) + { + return; + } + } + } + + /// Creates the property-change signal, or returns the one another thread created first. + /// The signal. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Signal CreatePropertyChanges() => ReactiveViewHelpers.CreateSignal(ref _propertyChanges, ref _disposed); + + /// Checks whether an item that was not found in the projection still belongs in it. + /// The batch occurrence counts after the found items were consumed. + /// when an item that should have been present was not. + internal bool AnyLeftoverMatches(Dictionary, int> leftovers) + { + foreach (var pair in leftovers) + { + if (pair.Value > 0 && _rules.Matches(pair.Key.Value)) + { + return true; + } + } + + return false; + } + + /// Throws a source failure again with its original stack, for a projection that has no error handler. + /// The failure. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Rethrow(Exception error) => ExceptionDispatchInfo.Capture(error).Throw(); + + /// Applies queued work and then gives up ownership of the projection. + /// when more work arrived and the caller must drain again. + private bool RunOwned() + { + try + { + // Dispose closes the gate of the target collection, so a drain that is still running cannot change it or raise from it. + if (!IsDisposed && DrainOrStop() && !IsDisposed) + { + NotifyChanged(); + } + } + finally + { + ReleaseInline(); + + // The exchange is a full fence, so the work check below cannot read a value older than the release. + _ = Interlocked.Exchange(ref _draining, 0); + } + + return HasWork(); + } + + /// Returns the pooled batch of a notification that was handed to the drain but never applied. + private void ReleaseInline() + { + _inline?.Batch?.Dispose(); + _inline = null; + } + + /// Subscribes to the stream and prepares the dispatcher. + /// The notification stream for a projection without a source. + /// The coalescing window. + /// The scheduler that applies changes. + /// An optional handler for stream failures. + /// An optional handler for stream completion. + private void Subscribe( + IObservable>? stream, + TimeSpan throttle, + ISequencer scheduler, + Action? onError = null, + Action? onCompleted = null) + { + ArgumentExceptionHelper.ThrowIfNull(scheduler); + + // Applying on the calling thread needs no dispatcher, so the view does not allocate one. + _immediate = ViewDispatcher.IsImmediate(scheduler, throttle); + if (!_immediate) + { + _dispatcher = new(scheduler, throttle, Drain); + } + + _onError = onError; + _onCompleted = onCompleted; + if (_source is IVersionedSnapshotSource versioned) + { + _runsInline = _immediate; + KeepSubscription(versioned.VersionedStream.Subscribe((IObserver>)this)); + return; + } + + _sequenceBase = _source?.Version ?? 0; + stream ??= _source?.Stream; + ArgumentExceptionHelper.ThrowIfNull(stream); + KeepSubscription(stream.Subscribe((IObserver>)this)); + } + + /// Remembers the stream subscription, releasing it at once when the projection already stopped. + /// The stream subscription. + private void KeepSubscription(IDisposable subscription) + { + Volatile.Write(ref _subscription, subscription); + if (IsDisposed) + { + ReleaseSubscription(); + } + } + + /// Releases the stream subscription once. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ReleaseSubscription() => Interlocked.Exchange(ref _subscription, null)?.Dispose(); + + /// Retains a notification and asks for a drain. + /// The notification. + /// The version the source published with the notification, or to derive it. + private void Enqueue(CacheNotify notification, long? knownVersion) + { + if (knownVersion is { } version && TryApplyInline(notification, version)) + { + return; + } + + EnqueueRetained(notification, knownVersion); + } + + /// + /// Applies a notification on the calling thread without queueing it, when the view applies changes immediately and nobody + /// else is draining. The projection's own queue is skipped, so this costs no lock. + /// + /// The notification. + /// The version the source published with the notification. + /// when the notification was handed to a drain owned by the caller. + private bool TryApplyInline(CacheNotify notification, long version) + { + if (!_runsInline || (_ignoreRefreshes && notification.Action == CacheAction.Refreshed) || Interlocked.CompareExchange(ref _draining, 1, 0) != 0) + { + return false; + } + + // Retained notifications arrived earlier, so this one is queued behind them to keep the delivery order. + if (HasWork()) + { + EnqueueRetained(notification, version); + } + else + { + _inline = notification; + _inlineVersion = version; + } + + if (RunOwned()) + { + Drain(); + } + + return true; + } + + /// Retains a notification and asks for a drain. + /// The notification. + /// The version the source published with the notification, or to derive it. + private void EnqueueRetained(CacheNotify notification, long? knownVersion) + { + bool accepted; + lock (_gate) + { + accepted = !IsDisposed; + if (accepted) + { + // A versioned source supplies the committed revision. For other sources, preserve the legacy sequence estimate. + _received++; + accepted = !_ignoreRefreshes || notification.Action != CacheAction.Refreshed; + if (accepted) + { + var version = knownVersion ?? (_source is IReactiveList ? _source.Version : _sequenceBase + _received); + var pending = _pending ??= new(); + pending.Enqueue(new(notification, version)); + Volatile.Write(ref _pendingCount, pending.Count); + } + } + } + + if (!accepted) + { + notification.Batch?.Dispose(); + return; + } + + RequestDrain(); + } + + /// Gets whether more work arrived while draining. + /// when another drain pass is needed. + private bool HasWork() => + Volatile.Read(ref _resyncRequested) != 0 + || Volatile.Read(ref _pendingRules) is not null + || Volatile.Read(ref _pendingCount) != 0 + || _hasQueued?.Invoke() == true; + + /// Takes the notification handed straight to the drain, or else the next retained one. + /// The notification. + /// when one was available. + private bool TakeNext(out CacheNotify notification) + { + if (_inline is not { } inline) + { + return TryTake(out notification); + } + + notification = inline; + _inline = null; + if (_inlineVersion > _covered) + { + return true; + } + + // The last source copy already includes this change, but listeners still hear that the source changed. + notification.Batch?.Dispose(); + _droppedCovered = true; + return TryTake(out notification); + } + + /// Takes the next retained notification. + /// The notification. + /// when one was available. + private bool TryTake(out CacheNotify notification) + { + while (TryDequeueRetained(out var next)) + { + if (next.Version > _covered) + { + notification = next.Notification; + return true; + } + + // The last source copy already includes this change, but listeners still hear that the source changed. + next.Notification.Batch?.Dispose(); + _droppedCovered = true; + } + + notification = null!; + return false; + } + + /// Takes the oldest retained notification, skipping the lock when none is retained. + /// The oldest retained notification. + /// when one was taken. + private bool TryDequeueRetained(out PendingNotification next) + { + if (Volatile.Read(ref _pendingCount) == 0) + { + next = default; + return false; + } + + lock (_gate) + { + return PendingNotificationQueue.TryDequeue(_pending, ref _pendingCount, out next); + } + } + + /// Publishes the change notification, tolerating a disposal that races with the publication. + private void NotifyChanged() + { + if (Volatile.Read(ref _propertyChanges) is not { HasObservers: true } signal) + { + return; + } + + // Publishing inside the gate means Dispose waits for it, so nothing is raised after Dispose returns. + ReactiveViewHelpers.PublishChange(signal, _closeGate, _changedArgs, ref _disposed); + } + + /// Applies every queued change, and stops quietly when a read of the source fails because the source was disposed. + /// when the projection may have changed. + private bool DrainOrStop() + { + try + { + return DrainCore(); + } + catch (ObjectDisposedException) when (_source?.IsDisposed == true) + { + // The view keeps its last items. Nothing more can be read, so release the subscription and drop what is queued. + Volatile.Write(ref _sourceGone, 1); + Volatile.Read(ref _dispatcher)?.Dispose(); + ReleaseSubscription(); + DropPending(); + return false; + } + catch (ObjectDisposedException) when (Volatile.Read(ref _disposed) != 0) + { + // Disposal closed the target collection part way through this drain, so the rest of it is abandoned. + return false; + } + } + + /// Returns the pooled batches of every retained notification. + private void DropPending() + { + lock (_gate) + { + while (_pending is { Count: > 0 } pending) + { + pending.Dequeue().Notification.Batch?.Dispose(); + } + + Volatile.Write(ref _pendingCount, 0); + } + } + + /// Applies every queued change. + /// when the projection may have changed. + private bool DrainCore() + { + var changed = false; + do + { + AdoptPendingRules(); + changed |= _applyQueued?.Invoke() == true; + var anomaly = ApplyPending(ref changed); + var settle = _settlePending && _appliedSinceCopy; + if (anomaly || Volatile.Read(ref _resyncRequested) != 0 || NeedsVerificationRebuild() || settle) + { + _ = Interlocked.Exchange(ref _resyncRequested, 0); + Resync(settle && !anomaly, anomaly); + changed = true; + } + } + while (!IsDisposed && HasWork()); + + return changed; + } + + /// Switches to rules queued by and asks for a rebuild with them. + private void AdoptPendingRules() + { + // The plain read keeps the exchange, which is a full fence, off the path where no rules were queued. + if (Volatile.Read(ref _pendingRules) is null || Interlocked.Exchange(ref _pendingRules, null) is not { } rules) + { + return; + } + + _rules = rules; + Volatile.Write(ref _resyncRequested, 1); + } + + /// Applies the retained notifications in arrival order. + /// Set when a notification was applied. + /// when a notification could not be applied exactly. + private bool ApplyPending(ref bool changed) + { + var anomaly = false; + while (!IsDisposed && TakeNext(out var notification)) + { + try + { + anomaly |= Apply(notification); + } + finally + { + notification.Batch?.Dispose(); + } + + changed = true; + _appliedSinceCopy = true; + + // Later changes cannot be published against an invalid projection. Their versions tell us which + // ones are already covered by the replacement snapshot. + if (anomaly && _source is IVersionedSnapshotSource) + { + return true; + } + } + + if (_droppedCovered) + { + _droppedCovered = false; + changed = true; + } + + return anomaly; + } + + /// Checks the projection against the source size once the retained notifications are applied. + /// when the projection has drifted and must be rebuilt. + /// A mismatch can also mean later notifications are still in flight. A rebuild is then harmless because the + /// next notification triggers another check, so the projection settles once the source goes quiet. + private bool NeedsVerificationRebuild() + { + // A versioned source applies every change exactly once on top of a consistent copy, so a size difference only + // means later changes have not arrived yet and never needs a copy to settle. + if (_source is null or IVersionedSnapshotSource || _rules.Snapshot is null) + { + return false; + } + + return _rules.ExpectedCount is { } expected + ? Target.Count != expected() + : _sourceCount != _source.Count; + } + + /// Rebuilds the projection from the source. + /// Whether this copy only confirms an earlier one. + /// Whether a notification could not be applied exactly. + private void Resync(bool confirming, bool anomaly) + { + if (_rules.Snapshot is not { } snapshot) + { + return; + } + + var result = snapshot(); + if (anomaly && _source is IVersionedSnapshotSource) + { + // A rebuild after a change that could not be applied is published as one atomic replacement, so no listener sees a half-rebuilt view. + Target.ReplaceAll(result.Items); + } + else if (_quietFirstFill && _resyncCount == 0 && Target.Count == 0) + { + // The owner said nobody can listen before its constructor returns, so the first build needs no events. + Target.Populate(result.Items); + } + else + { + Target.ReconcileTo(result.Items); + } + + _sourceCount = result.SourceCount; + _covered = result.Version; + _appliedSinceCopy = false; + _resyncCount++; + + // A write that landed in the source but had not yet been announced when the copy was taken is announced later and + // applied on top of the copy. One confirming copy after those announcements settles that for legacy sources. + _settlePending = !confirming && _source is not IReactiveList and not IVersionedSnapshotSource; + } + + /// Applies one notification to the projection. + /// The notification. + /// when the projection can no longer be trusted and must be rebuilt. + private bool Apply(CacheNotify notification) => + notification.Action switch + { + CacheAction.Added => ApplyAdded(notification), + CacheAction.Removed => ApplyRemoved(notification), + CacheAction.Updated => ApplyUpdated(notification), + CacheAction.Refreshed => ApplyRefreshed(notification), + CacheAction.Cleared => ApplyCleared(), + CacheAction.Reset => ApplyReset(notification.Batch), + CacheAction.BatchAdded => ApplyBatch(notification, adding: true), + CacheAction.BatchRemoved => ApplyBatch(notification, adding: false), + CacheAction.BatchOperation => ApplyBatchOperation(notification), + _ => false + }; + + /// Applies an added item. + /// The notification. + /// Whether a rebuild is needed. + private bool ApplyAdded(CacheNotify notification) + { + if (notification.Item is not { } raw) + { + return false; + } + + _sourceCount++; + var item = _select(raw); + if (_rules.Matches(item)) + { + Target.Add(item); + } + + return false; + } + + /// Applies a removed item. + /// The notification. + /// Whether a rebuild is needed. + private bool ApplyRemoved(CacheNotify notification) + { + if (notification.Item is not { } raw) + { + return false; + } + + _sourceCount--; + return !RemoveOne(_select(raw)) && _source is not null && _rules.Matches(_select(raw)); + } + + /// Applies an updated item. + /// The notification. + /// Whether a rebuild is needed. + private bool ApplyUpdated(CacheNotify notification) + { + var hasPrevious = _rules.PreviousIsReliable && notification.Previous is not null; + if (!hasPrevious && _source is not null && _rules.SameEntry is null) + { + // Nothing says which element was replaced. + return true; + } + + var current = notification.Item is { } raw ? _select(raw) : default(T?); + if (!hasPrevious) + { + return StoreUpdate(FindEntry(current), current, mayAdd: _rules.SameEntry is not null, previousMatched: false); + } + + var previous = _select(notification.Previous!); + return StoreUpdate(IndexOf(previous), current, mayAdd: true, _rules.Matches(previous)); + } + + /// Finds the element for the same entry as when the rules can identify entries. + /// The updated element. + /// The index, or -1. + private int FindEntry(T? current) + { + if (current is null) + { + return -1; + } + + if (_rules.SameEntry is not { } sameEntry) + { + return IndexOf(current); + } + + for (var i = 0; i < Target.Count; i++) + { + if (sameEntry(Target[i], current)) + { + return i; + } + } + + return -1; + } + + /// Stores the outcome of an update. + /// The index of the replaced occurrence, or -1. + /// The new item, or when the update carried none. + /// Whether an item that is not yet present may be added, which needs the update to identify what it replaced. + /// Whether the replaced item belonged in the projection, so it should have been found. + /// Whether a rebuild is needed. + private bool StoreUpdate(int index, T? current, bool mayAdd, bool previousMatched) + { + if (current is null || !_rules.Matches(current)) + { + if (index >= 0) + { + Target.RemoveAt(index); + } + + return index < 0 && previousMatched && _source is not null; + } + + if (index >= 0) + { + Target[index] = current; + return false; + } + + if (mayAdd) + { + Target.Add(current); + } + + return previousMatched && _source is not null; + } + + /// Applies an in-place refresh. + /// The notification. + /// Whether a rebuild is needed. + private bool ApplyRefreshed(CacheNotify notification) + { + if (notification.Item is not { } raw) + { + return false; + } + + var item = _select(raw); + var index = IndexOf(item); + var matches = _rules.Matches(item); + if (index < 0 && matches) + { + Target.Add(item); + } + else if (index >= 0 && !matches) + { + Target.RemoveAt(index); + } + + return false; + } + + /// Applies a clear. + /// Always . + private bool ApplyCleared() + { + _sourceCount = 0; + Target.Clear(); + return false; + } + + /// Applies a batch of added or removed items. + /// The notification. + /// Whether the items were added. + /// Whether a rebuild is needed. + private bool ApplyBatch(CacheNotify notification, bool adding) + { + if (notification.Batch is not { } batch) + { + return _source is not null; + } + + if (!adding && batch.Count > Target.ResetLimit) + { + var countedAnomaly = RemoveBatchByCounting(batch); + _sourceCount -= batch.Count; + return countedAnomaly; + } + + var anomaly = ApplyBatchItems(batch, adding); + _sourceCount += adding ? batch.Count : -batch.Count; + return anomaly; + } + + /// Adds or removes each item of a batch one at a time inside one batch scope. + /// The batch. + /// Whether the items were added. + /// Whether a removed item that belonged in the projection was not there. + private bool ApplyBatchItems(PooledBatch batch, bool adding) + { + var anomaly = false; + Target.BeginBatch(batch.Count); + try + { + for (var i = 0; i < batch.Count; i++) + { + var item = _select(batch.Items[i]); + if (adding) + { + if (_rules.Matches(item)) + { + Target.Add(item); + } + } + else if (!RemoveOne(item) && _source is not null && _rules.Matches(item)) + { + anomaly = true; + } + } + } + finally + { + Target.EndBatch(); + } + + return anomaly; + } + + /// + /// Removes a large batch in one pass over the projection instead of one search per item, and replaces the projection + /// with one reset. Every item of the batch is removed wherever it is, whether or not the rules still accept it, the + /// way a single removal does. + /// + /// The removed items. + /// Whether a removed item that belonged in the projection was not there. + private bool RemoveBatchByCounting(PooledBatch batch) + { + var counts = new Dictionary, int>(batch.Count, ItemComparison.SameItemComparer()); + for (var i = 0; i < batch.Count; i++) + { + DictionaryCompat.Increment(counts, new(_select(batch.Items[i]))); + } + + // Walk from the end so the last occurrences leave, the same ones a removal of a single item takes. + var survivors = new List(Target.Count); + var remaining = batch.Count; + for (var i = Target.Count - 1; i >= 0; i--) + { + var item = Target[i]; + if (remaining > 0 && DictionaryCompat.TryConsume(counts, new(item))) + { + remaining--; + continue; + } + + survivors.Add(item); + } + + if (remaining < batch.Count) + { + survivors.Reverse(); + Target.ReplaceAll(survivors); + } + + return remaining > 0 && _source is not null && AnyLeftoverMatches(counts); + } + + /// Applies a whole-collection operation, which carries no usable detail when the source is known. + /// The notification. + /// Whether a rebuild is needed. + private bool ApplyBatchOperation(CacheNotify notification) + { + if (_source is not null) + { + return true; + } + + if (notification.Batch is not { } batch) + { + return false; + } + + for (var i = 0; i < batch.Count; i++) + { + var item = _select(batch.Items[i]); + if (_rules.Matches(item)) + { + Target.Add(item); + } + } + + return false; + } + + /// Replaces the projection with the contents of a reset batch. + /// The source snapshot. + /// Whether the source must be read again. + private bool ApplyReset(PooledBatch? batch) + { + if (batch is null) + { + return _source is not null; + } + + _sourceCount = batch.Count; + List items = [with(batch.Count)]; + for (var i = 0; i < batch.Count; i++) + { + var item = _select(batch.Items[i]); + if (_rules.Matches(item)) + { + items.Add(item); + } + } + + Target.ReplaceAll(items); + return false; + } + + /// Removes the first occurrence of an item, preferring reference identity. + /// The item to remove. + /// when an occurrence was removed. + private bool RemoveOne(T item) + { + var index = IndexOf(item); + if (index < 0) + { + return false; + } + + Target.RemoveAt(index); + return true; + } + + /// Finds an occurrence, preferring reference identity over value equality. + /// The item to find. + /// The index, or -1. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private int IndexOf(T item) => _itemComparer is null ? Target.FindLast(item) : Target.FindLast(item, _itemComparer); +} diff --git a/src/ReactiveList/Internal/ThrowHelper.cs b/src/ReactiveList/Internal/ThrowHelper.cs deleted file mode 100644 index b88f2a13..00000000 --- a/src/ReactiveList/Internal/ThrowHelper.cs +++ /dev/null @@ -1,37 +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 -/// Provides target-framework-compatible guard helpers. -internal static class ThrowHelper -{ - /// Throws when the supplied argument is null. - /// The argument type. - /// The argument value. - /// The parameter name, supplied by the compiler. - /// Thrown when is . - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#if NETFRAMEWORK - internal static void ThrowIfNull( - T? argument, - [CallerArgumentExpression(nameof(argument))] string? paramName = null) - { - if (argument is not null) - { - return; - } - - throw new ArgumentNullException(paramName); - } -#else - internal static void ThrowIfNull( - T? argument, - [CallerArgumentExpression(nameof(argument))] string? paramName = null) => - ArgumentNullException.ThrowIfNull(argument, paramName); -#endif -} diff --git a/src/ReactiveList/Internal/ViewDispatcher.cs b/src/ReactiveList/Internal/ViewDispatcher.cs new file mode 100644 index 00000000..58986e66 --- /dev/null +++ b/src/ReactiveList/Internal/ViewDispatcher.cs @@ -0,0 +1,162 @@ +// 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, created when a request first has to be scheduled. + private Action? _run; + + /// The callback run when the coalescing window elapses, created when a request first has to be scheduled. + private 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; + + /// The handle of the drain or coalescing timer that is waiting to run, or . + private ScheduledHandle? _pending; + + /// The number of drains requested so far. + private long _tickets; + + /// 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) + { + ArgumentExceptionHelper.ThrowIfNull(scheduler); + ArgumentExceptionHelper.ThrowIfNull(drain); + + _scheduler = scheduler; + _throttle = throttle; + _drain = drain; + _immediate = ReferenceEquals(scheduler, ReactiveListScheduler.Immediate); + } + + /// Gets a value indicating whether a request drains on the calling thread at once, with no timer and no scheduling, so no dispatcher is needed. + /// The scheduler that would run the drain. + /// The coalescing window. + /// when requests drain on the calling thread. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool IsImmediate(ISequencer scheduler, TimeSpan throttle) => + throttle <= TimeSpan.Zero && ReferenceEquals(scheduler, ReactiveListScheduler.Immediate); + + /// 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; + } + + // Numbered before scheduling so a handle that reaches Track late can tell it is older than one already recorded. + var ticket = Interlocked.Increment(ref _tickets); + Track( + ticket, + _throttle <= TimeSpan.Zero + ? ReactiveListScheduler.Schedule(_scheduler, TimeSpan.Zero, _run ??= Run) + : ReactiveListScheduler.Schedule(ReactiveListScheduler.Default, _throttle, _onWindowElapsed ??= OnWindowElapsed)); + } + + /// Stops scheduling and cancels any drain or coalescing timer that has not run yet, so a scheduler does not keep the view alive. + internal void Dispose() + { + Volatile.Write(ref _disposed, 1); + Interlocked.Exchange(ref _pending, null)?.Handle.Dispose(); + } + + /// Hands the elapsed coalescing window to the view scheduler. + internal void OnWindowElapsed() + { + if (Volatile.Read(ref _disposed) != 0) + { + return; + } + + Track(Interlocked.Increment(ref _tickets), ReactiveListScheduler.Schedule(_scheduler, TimeSpan.Zero, _run ??= Run)); + } + + /// Clears the pending flag, then drains. + internal void Run() + { + _ = Interlocked.Exchange(ref _scheduled, 0); + if (Volatile.Read(ref _disposed) != 0) + { + return; + } + + _drain(); + } + + /// Remembers the scheduled work so disposal can cancel it. + /// The request number of the scheduled work. + /// The handle of the scheduled work. + private void Track(long ticket, IDisposable handle) + { + Install(new(ticket, handle)); + if (Volatile.Read(ref _disposed) == 0) + { + return; + } + + Interlocked.Exchange(ref _pending, null)?.Handle.Dispose(); + } + + /// Records a handle unless a newer request is already recorded. + /// The numbered handle. + private void Install(ScheduledHandle entry) + { + while (true) + { + var current = Volatile.Read(ref _pending); + + // A newer request can only exist once this one has run, so this handle is finished and must not cancel the newer one. + if (current is not null && current.Ticket > entry.Ticket) + { + return; + } + + if (!ReferenceEquals(Interlocked.CompareExchange(ref _pending, entry, current), current)) + { + continue; + } + + current?.Handle.Dispose(); + return; + } + } +} diff --git a/src/ReactiveList/Internal/ViewMirrorPump.cs b/src/ReactiveList/Internal/ViewMirrorPump.cs new file mode 100644 index 00000000..d5e56cbb --- /dev/null +++ b/src/ReactiveList/Internal/ViewMirrorPump.cs @@ -0,0 +1,393 @@ +// 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, IObserver>, IObserver> + 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, created when something first asks for them. + private Signal? _propertyChanges; + + /// The subscription to the source stream. + private IDisposable? _subscription; + + /// 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; + + /// Whether a request drains on the calling thread at once, so the pump has no dispatcher. + private bool _immediate; + + /// Whether notifications are applied on the calling thread at once, so they can skip the queue. + private bool _runsInline; + + /// 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; + + /// Non-zero once a read failed because the source was disposed. + private int _sourceGone; + + /// Initializes a new instance of the class. + /// The source to mirror. + internal ViewMirrorPump(IReactiveSource source) + { + ArgumentExceptionHelper.ThrowIfNull(source); + + _source = source; + if (source is IVersionedSnapshotSource versioned) + { + // Subscribe before copying so every change after the copy is delivered with a version above the copy's. + Buffer = new(source, takeSnapshot: false); + Volatile.Write(ref _subscription, versioned.VersionedStream.Subscribe((IObserver>)this)); + try + { + Buffer.Reset(); + } + catch + { + // A constructor that throws leaves nobody to dispose the subscription. + ReleaseSubscription(); + throw; + } + + return; + } + + Buffer = new(source); + } + + /// Gets the observable stream of property-change notifications. + internal IObservable PropertyChanges => Volatile.Read(ref _propertyChanges) ?? CreatePropertyChanges(); + + /// Gets the retained notifications and ordered source mirror. + internal ViewChangeBuffer Buffer { get; } + + /// Gets the gate that stops the sink collections once the pump is disposed. + internal DisposalGate Gate { get; } = new(); + + /// Gets a value indicating whether the pump was disposed. + internal bool IsDisposed => Volatile.Read(ref _disposed) != 0; + + /// Gets a value indicating whether the pump was disposed or stopped because its source was disposed. + private bool IsStopped => Volatile.Read(ref _disposed) != 0 || Volatile.Read(ref _sourceGone) != 0; + + /// Stops observing and releases retained notifications. + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + // Closing the gate stops the sink collections from changing or raising anything more, including a drain that is + // blocked in user code right now. It does not wait, so disposing from a handler or the scheduler thread is safe. + Gate.Close(); + Volatile.Read(ref _dispatcher)?.Dispose(); + ReleaseSubscription(); + Buffer.Dispose(); + Interlocked.Exchange(ref _propertyChanges, null)?.Dispose(); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnNext(VersionedNotification value) + { + if (TryApplyInline(value.Notification, value.Version)) + { + return; + } + + if (Buffer.Capture(value.Notification, value.Version)) + { + Notify(); + } + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnNext(CacheNotify value) + { + if (Buffer.Capture(value, _source.Version)) + { + Notify(); + } + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnError(Exception error) => ExceptionDispatchInfo.Capture(error).Throw(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted() + { + } + + /// 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 . + /// Whether to rebuild from the source after subscribing a source that was copied before it could be subscribed, so a change in between is not lost. + internal void Start( + IViewMirrorSink sink, + TimeSpan throttle, + ISequencer scheduler, + Func? applyQueued = null, + Func? hasQueued = null, + bool coverSubscriptionGap = false) + { + ArgumentExceptionHelper.ThrowIfNull(sink); + ArgumentExceptionHelper.ThrowIfNull(scheduler); + _sink = sink; + _applyQueued = applyQueued; + _hasQueued = hasQueued; + + // Applying on the calling thread needs no dispatcher, so the view does not allocate one. + var immediate = ViewDispatcher.IsImmediate(scheduler, throttle); + Volatile.Write(ref _immediate, immediate); + + // The exchange is a full fence, so a request that saw neither the flag nor a dispatcher is seen by the work check below. + _ = Interlocked.Exchange(ref _dispatcher, immediate ? null : new ViewDispatcher(scheduler, throttle, Drain)); + + // Set after the sink, so a notification applied inline always finds it. + Volatile.Write(ref _runsInline, immediate && _source is IVersionedSnapshotSource); + if (_source is IVersionedSnapshotSource) + { + // Already subscribed by the constructor; changes and requests that arrived since then are waiting. + if (HasWork()) + { + Notify(); + } + + return; + } + + KeepSubscription(_source.Stream.Subscribe((IObserver>)this)); + if (coverSubscriptionGap) + { + Refresh(); + } + } + + /// 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. + internal void RequestDrain() + { + // Pairs with the fence in Start: either this sees the dispatcher or Start sees the work that was queued first. + Interlocked.MemoryBarrier(); + Notify(); + } + + /// Applies queued work on the calling thread. + internal void Drain() + { + while (!IsStopped) + { + if (Interlocked.Exchange(ref _draining, 1) != 0) + { + return; + } + + if (!RunOwned()) + { + return; + } + } + } + + /// Applies queued work and then gives up ownership of the projection. + /// when more work arrived and the caller must drain again. + private bool RunOwned() + { + try + { + // Dispose closes the gate of the sink collections, so a drain that is still running cannot change them or raise from them. + if (!IsStopped && DrainOrStop() && !IsStopped) + { + NotifyCountChanged(); + } + } + finally + { + Buffer.ReleaseInline(); + + // The exchange is a full fence, so the work check below cannot read a value older than the release. + _ = Interlocked.Exchange(ref _draining, 0); + } + + return HasWork(); + } + + /// + /// Applies a notification on the calling thread without queueing it, when the view applies changes immediately and nobody + /// else is draining. The buffer's queue is skipped, so this costs no lock. + /// + /// The notification. + /// The version the source published with the notification. + /// when the notification was handed to a drain owned by the caller. + private bool TryApplyInline(CacheNotify notification, long version) + { + if (!Volatile.Read(ref _runsInline) || Interlocked.CompareExchange(ref _draining, 1, 0) != 0) + { + return false; + } + + // Retained notifications arrived earlier, so this one is queued behind them to keep the delivery order. + if (HasWork()) + { + _ = Buffer.Capture(notification, version); + } + else + { + Buffer.SetInline(notification, version); + } + + if (RunOwned()) + { + Drain(); + } + + return true; + } + + /// Publishes a count change, tolerating a disposal that races with the publication. + private void NotifyCountChanged() + { + if (Volatile.Read(ref _propertyChanges) is not { HasObservers: true } signal) + { + return; + } + + // Publishing inside the gate means Dispose waits for it, so nothing is raised after Dispose returns. + ReactiveViewHelpers.PublishChange(signal, Gate, CountChangedArgs, ref _disposed); + } + + /// Remembers the source subscription, releasing it at once when the pump already stopped. + /// The source subscription. + private void KeepSubscription(IDisposable subscription) + { + Volatile.Write(ref _subscription, subscription); + if (IsStopped) + { + ReleaseSubscription(); + } + } + + /// Releases the source subscription once. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ReleaseSubscription() => Interlocked.Exchange(ref _subscription, null)?.Dispose(); + + /// Creates the property-change signal, or returns the one another thread created first. + /// The signal. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private Signal CreatePropertyChanges() => ReactiveViewHelpers.CreateSignal(ref _propertyChanges, ref _disposed); + + /// Asks for a drain, on the calling thread when the view applies changes immediately and otherwise on the view scheduler. + private void Notify() + { + if (Volatile.Read(ref _immediate)) + { + Drain(); + return; + } + + Volatile.Read(ref _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, and stops quietly when a read of the source fails because the source was disposed. + /// when the sink may have changed. + private bool DrainOrStop() + { + try + { + return DrainCore(); + } + catch (ObjectDisposedException) when (_source.IsDisposed) + { + // The view keeps its last items. Nothing more can be read, so release the subscription and drop what is queued. + Volatile.Write(ref _sourceGone, 1); + Volatile.Read(ref _dispatcher)?.Dispose(); + ReleaseSubscription(); + Buffer.Dispose(); + return false; + } + catch (ObjectDisposedException) when (IsDisposed) + { + // Disposal closed the sink collections part way through this drain, so the rest of it is abandoned. + return false; + } + } + + /// Applies every queued change. + /// when the sink may have changed. + private bool DrainCore() + { + if (_sink is not { } sink) + { + return false; + } + + var changed = _applyQueued?.Invoke() == true; + if (Interlocked.Exchange(ref _resetRequested, 0) != 0) + { + Buffer.Reset(); + sink.MirrorReset(); + changed = true; + } + + while (!IsStopped && Buffer.ApplyNext(sink)) + { + changed = true; + } + + // Owner work queued before one of the changes above is applied with it, so a listener never sees that change without it. + if (!IsStopped && _applyQueued?.Invoke() == true) + { + changed = true; + } + + Buffer.VerifyAtHead(sink); + return changed; + } +} diff --git a/src/ReactiveList/Internal/ViewSourceRules.cs b/src/ReactiveList/Internal/ViewSourceRules.cs new file mode 100644 index 00000000..78514815 --- /dev/null +++ b/src/ReactiveList/Internal/ViewSourceRules.cs @@ -0,0 +1,140 @@ +// 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 + +/// Builds projection rules that filter a whole source. +internal static class ViewSourceRules +{ + /// The number of times a source copy is attempted before the failure is allowed to surface. + private const int CopyAttempts = 64; + + /// Creates rules that rebuild a projection by filtering every source item. + /// The item type. + /// The source to read. + /// The membership predicate. + /// Tells whether two items are the same source entry, when updates do not name the replaced item. + /// The rules. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ProjectionRules Create(IReactiveSource source, Func filter, Func? sameEntry = null) + where T : notnull => + Create(source, static item => item, filter, sameEntry, previousIsReliable: sameEntry is null); + + /// Creates rules that rebuild a projection of selected source items by filtering every source item. + /// The source item type. + /// The projected element type. + /// The source to read. + /// Converts a source item to a projected element. + /// The membership predicate over projected elements. + /// Tells whether two elements are the same source entry, when updates do not name the replaced item. + /// Whether the source names the replaced item in update notifications. + /// The rules. + internal static ProjectionRules Create( + IReactiveSource source, + Func select, + Func filter, + Func? sameEntry = null, + bool previousIsReliable = true) + where TSource : notnull => + new(filter, () => Snapshot(source, select, filter), null, sameEntry, previousIsReliable); + + /// Copies a source, retrying when a concurrent mutation makes the copy fail. + /// The item type. + /// The source to copy. + /// The copied items. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static T[] ReadSource(IReactiveSource source) + where T : notnull => + CopyWithRetry(source, static current => current.ToArray()); + + /// Runs a copy, retrying when a concurrent mutation makes it fail, and lets the failure surface on the last attempt. + /// The state the copy reads. + /// The item type. + /// The state passed to . + /// Copies the items. + /// The copied items. + internal static T[] CopyWithRetry(TState state, Func copy) + { + for (var attempt = 1; attempt < CopyAttempts; attempt++) + { + try + { + return copy(state); + } + catch (ArgumentException) + { + // The source changed size while it was being copied. + } + catch (InvalidOperationException) + { + // The source was modified while it was being enumerated. + } + catch (IndexOutOfRangeException) + { + // The source shrank between sizing the copy and filling it. + } + } + + return copy(state); + } + + /// Copies a source and the revision it had, retrying while the revision moves during the copy. + /// The item type. + /// The source to copy. + /// The copied items and their revision. + internal static (T[] Items, long Version) ReadVersioned(IReactiveSource source) + where T : notnull + { + if (source is IVersionedSnapshotSource versioned) + { + // The copy and its version come from one consistent read, so no retry or later confirmation is needed. + var copy = versioned.CopyVersioned(out var copyVersion); + return (copy, copyVersion); + } + + var items = Array.Empty(); + var version = 0L; + for (var attempt = 0; attempt < CopyAttempts; attempt++) + { + // Reporting the earlier revision when it keeps moving errs towards re-applying a change, which the + // projection's size check repairs, rather than skipping one. + version = source.Version; + items = ReadSource(source); + if (version == source.Version) + { + break; + } + } + + return (items, version); + } + + /// Reads the matching items of a source together with its size. + /// The source item type. + /// The projected element type. + /// The source to read. + /// Converts a source item to a projected element. + /// The membership predicate. + /// The matching items and the source size. + private static SourceSnapshot Snapshot(IReactiveSource source, Func select, Func filter) + where TSource : notnull + { + var (all, version) = ReadVersioned(source); + var matching = new List(all.Length); + for (var i = 0; i < all.Length; i++) + { + var item = select(all[i]); + if (filter(item)) + { + matching.Add(item); + } + } + + return new(matching, all.Length, version); + } +} diff --git a/src/ReactiveList/PublicAPI/net10.0/PublicAPI.txt b/src/ReactiveList/PublicAPI/net10.0/PublicAPI.txt index c4a56103..45a3b89b 100644 --- a/src/ReactiveList/PublicAPI/net10.0/PublicAPI.txt +++ b/src/ReactiveList/PublicAPI/net10.0/PublicAPI.txt @@ -166,7 +166,7 @@ namespace ReactiveList.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -180,14 +180,14 @@ namespace ReactiveList.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -225,6 +225,21 @@ namespace ReactiveList.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] [System.Runtime.CompilerServices.SkipLocalsInit] public sealed class QuadDictionary : ReactiveList.Collections.IQuad> @@ -324,64 +339,23 @@ namespace ReactiveList.Collections public static bool operator !=(ReactiveList.Collections.QuadList.Enumerator left, ReactiveList.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + [System.Runtime.CompilerServices.SkipLocalsInit] + public sealed class QuaternaryDictionary : ReactiveList.Collections.IQuaternaryDictionary, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item, ReactiveList.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - [System.Runtime.CompilerServices.SkipLocalsInit] - public class QuaternaryDictionary : ReactiveList.Collections.QuaternaryBase, TValue>, ReactiveList.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -389,17 +363,22 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) where TIndexKey : notnull { } public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -409,64 +388,183 @@ namespace ReactiveList.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] [System.Runtime.CompilerServices.SkipLocalsInit] - public class QuaternaryList : ReactiveList.Collections.QuaternaryBase, ReactiveList.Collections.IQuaternaryList where T : notnull + public sealed class QuaternaryList : ReactiveList.Collections.IQuaternaryList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Collections.IReactiveList>, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Collections.ReactiveList item, ReactiveList.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Collections.IReactiveList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -483,11 +581,13 @@ namespace ReactiveList.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -500,6 +600,7 @@ namespace ReactiveList.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -510,9 +611,11 @@ namespace ReactiveList.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -524,7 +627,6 @@ namespace ReactiveList.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -551,6 +653,19 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Core { @@ -565,6 +680,7 @@ namespace ReactiveList.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -782,7 +898,7 @@ namespace ReactiveList.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -795,12 +911,180 @@ namespace ReactiveList.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.IObservable> filterObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -818,19 +1102,20 @@ namespace ReactiveList.Views public ReactiveList.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Collections.IReactiveSource source, System.IObservable> filterObservable, in System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -851,6 +1136,7 @@ namespace ReactiveList.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -871,6 +1157,7 @@ namespace ReactiveList.Views public sealed class FilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.Func filter, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -891,6 +1178,7 @@ namespace ReactiveList.Views public sealed class GroupedReactiveView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Collections.IReactiveList source, System.Func keySelector, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -921,19 +1209,20 @@ namespace ReactiveList.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, in System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, in System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -954,6 +1243,7 @@ namespace ReactiveList.Views public sealed class SortedReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList/PublicAPI/net11.0/PublicAPI.txt b/src/ReactiveList/PublicAPI/net11.0/PublicAPI.txt index c4a56103..45a3b89b 100644 --- a/src/ReactiveList/PublicAPI/net11.0/PublicAPI.txt +++ b/src/ReactiveList/PublicAPI/net11.0/PublicAPI.txt @@ -166,7 +166,7 @@ namespace ReactiveList.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -180,14 +180,14 @@ namespace ReactiveList.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -225,6 +225,21 @@ namespace ReactiveList.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] [System.Runtime.CompilerServices.SkipLocalsInit] public sealed class QuadDictionary : ReactiveList.Collections.IQuad> @@ -324,64 +339,23 @@ namespace ReactiveList.Collections public static bool operator !=(ReactiveList.Collections.QuadList.Enumerator left, ReactiveList.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + [System.Runtime.CompilerServices.SkipLocalsInit] + public sealed class QuaternaryDictionary : ReactiveList.Collections.IQuaternaryDictionary, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item, ReactiveList.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - [System.Runtime.CompilerServices.SkipLocalsInit] - public class QuaternaryDictionary : ReactiveList.Collections.QuaternaryBase, TValue>, ReactiveList.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -389,17 +363,22 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) where TIndexKey : notnull { } public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -409,64 +388,183 @@ namespace ReactiveList.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] [System.Runtime.CompilerServices.SkipLocalsInit] - public class QuaternaryList : ReactiveList.Collections.QuaternaryBase, ReactiveList.Collections.IQuaternaryList where T : notnull + public sealed class QuaternaryList : ReactiveList.Collections.IQuaternaryList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Collections.IReactiveList>, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Collections.ReactiveList item, ReactiveList.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Collections.IReactiveList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -483,11 +581,13 @@ namespace ReactiveList.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -500,6 +600,7 @@ namespace ReactiveList.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -510,9 +611,11 @@ namespace ReactiveList.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -524,7 +627,6 @@ namespace ReactiveList.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -551,6 +653,19 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Core { @@ -565,6 +680,7 @@ namespace ReactiveList.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -782,7 +898,7 @@ namespace ReactiveList.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -795,12 +911,180 @@ namespace ReactiveList.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.IObservable> filterObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -818,19 +1102,20 @@ namespace ReactiveList.Views public ReactiveList.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Collections.IReactiveSource source, System.IObservable> filterObservable, in System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -851,6 +1136,7 @@ namespace ReactiveList.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -871,6 +1157,7 @@ namespace ReactiveList.Views public sealed class FilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.Func filter, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -891,6 +1178,7 @@ namespace ReactiveList.Views public sealed class GroupedReactiveView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Collections.IReactiveList source, System.Func keySelector, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -921,19 +1209,20 @@ namespace ReactiveList.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, in System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, in System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -954,6 +1243,7 @@ namespace ReactiveList.Views public sealed class SortedReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList/PublicAPI/net47/PublicAPI.txt b/src/ReactiveList/PublicAPI/net47/PublicAPI.txt index 6258bb8a..082db88e 100644 --- a/src/ReactiveList/PublicAPI/net47/PublicAPI.txt +++ b/src/ReactiveList/PublicAPI/net47/PublicAPI.txt @@ -166,7 +166,7 @@ namespace ReactiveList.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -180,14 +180,14 @@ namespace ReactiveList.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -225,6 +225,21 @@ namespace ReactiveList.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] public sealed class QuadDictionary : ReactiveList.Collections.IQuad> { @@ -322,63 +337,22 @@ namespace ReactiveList.Collections public static bool operator !=(ReactiveList.Collections.QuadList.Enumerator left, ReactiveList.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + public sealed class QuaternaryDictionary : ReactiveList.Collections.IQuaternaryDictionary, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item, ReactiveList.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - public class QuaternaryDictionary : ReactiveList.Collections.QuaternaryBase, TValue>, ReactiveList.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -386,17 +360,22 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) where TIndexKey : notnull { } public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -406,63 +385,182 @@ namespace ReactiveList.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] - public class QuaternaryList : ReactiveList.Collections.QuaternaryBase, ReactiveList.Collections.IQuaternaryList where T : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] + public sealed class QuaternaryList : ReactiveList.Collections.IQuaternaryList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Collections.IReactiveList>, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Collections.ReactiveList item, ReactiveList.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Collections.IReactiveList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -479,11 +577,13 @@ namespace ReactiveList.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -496,6 +596,7 @@ namespace ReactiveList.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -506,9 +607,11 @@ namespace ReactiveList.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -520,7 +623,6 @@ namespace ReactiveList.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -547,6 +649,19 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Core { @@ -561,6 +676,7 @@ namespace ReactiveList.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -778,7 +894,7 @@ namespace ReactiveList.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -791,12 +907,180 @@ namespace ReactiveList.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.IObservable> filterObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -814,19 +1098,20 @@ namespace ReactiveList.Views public ReactiveList.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Collections.IReactiveSource source, System.IObservable> filterObservable, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -847,6 +1132,7 @@ namespace ReactiveList.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -867,6 +1153,7 @@ namespace ReactiveList.Views public sealed class FilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.Func filter, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -887,6 +1174,7 @@ namespace ReactiveList.Views public sealed class GroupedReactiveView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Collections.IReactiveList source, System.Func keySelector, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -917,19 +1205,20 @@ namespace ReactiveList.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -950,6 +1239,7 @@ namespace ReactiveList.Views public sealed class SortedReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList/PublicAPI/net471/PublicAPI.txt b/src/ReactiveList/PublicAPI/net471/PublicAPI.txt index 6258bb8a..082db88e 100644 --- a/src/ReactiveList/PublicAPI/net471/PublicAPI.txt +++ b/src/ReactiveList/PublicAPI/net471/PublicAPI.txt @@ -166,7 +166,7 @@ namespace ReactiveList.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -180,14 +180,14 @@ namespace ReactiveList.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -225,6 +225,21 @@ namespace ReactiveList.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] public sealed class QuadDictionary : ReactiveList.Collections.IQuad> { @@ -322,63 +337,22 @@ namespace ReactiveList.Collections public static bool operator !=(ReactiveList.Collections.QuadList.Enumerator left, ReactiveList.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + public sealed class QuaternaryDictionary : ReactiveList.Collections.IQuaternaryDictionary, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item, ReactiveList.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - public class QuaternaryDictionary : ReactiveList.Collections.QuaternaryBase, TValue>, ReactiveList.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -386,17 +360,22 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) where TIndexKey : notnull { } public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -406,63 +385,182 @@ namespace ReactiveList.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] - public class QuaternaryList : ReactiveList.Collections.QuaternaryBase, ReactiveList.Collections.IQuaternaryList where T : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] + public sealed class QuaternaryList : ReactiveList.Collections.IQuaternaryList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Collections.IReactiveList>, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Collections.ReactiveList item, ReactiveList.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Collections.IReactiveList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -479,11 +577,13 @@ namespace ReactiveList.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -496,6 +596,7 @@ namespace ReactiveList.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -506,9 +607,11 @@ namespace ReactiveList.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -520,7 +623,6 @@ namespace ReactiveList.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -547,6 +649,19 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Core { @@ -561,6 +676,7 @@ namespace ReactiveList.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -778,7 +894,7 @@ namespace ReactiveList.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -791,12 +907,180 @@ namespace ReactiveList.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.IObservable> filterObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -814,19 +1098,20 @@ namespace ReactiveList.Views public ReactiveList.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Collections.IReactiveSource source, System.IObservable> filterObservable, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -847,6 +1132,7 @@ namespace ReactiveList.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -867,6 +1153,7 @@ namespace ReactiveList.Views public sealed class FilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.Func filter, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -887,6 +1174,7 @@ namespace ReactiveList.Views public sealed class GroupedReactiveView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Collections.IReactiveList source, System.Func keySelector, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -917,19 +1205,20 @@ namespace ReactiveList.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -950,6 +1239,7 @@ namespace ReactiveList.Views public sealed class SortedReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList/PublicAPI/net472/PublicAPI.txt b/src/ReactiveList/PublicAPI/net472/PublicAPI.txt index 6258bb8a..082db88e 100644 --- a/src/ReactiveList/PublicAPI/net472/PublicAPI.txt +++ b/src/ReactiveList/PublicAPI/net472/PublicAPI.txt @@ -166,7 +166,7 @@ namespace ReactiveList.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -180,14 +180,14 @@ namespace ReactiveList.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -225,6 +225,21 @@ namespace ReactiveList.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] public sealed class QuadDictionary : ReactiveList.Collections.IQuad> { @@ -322,63 +337,22 @@ namespace ReactiveList.Collections public static bool operator !=(ReactiveList.Collections.QuadList.Enumerator left, ReactiveList.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + public sealed class QuaternaryDictionary : ReactiveList.Collections.IQuaternaryDictionary, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item, ReactiveList.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - public class QuaternaryDictionary : ReactiveList.Collections.QuaternaryBase, TValue>, ReactiveList.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -386,17 +360,22 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) where TIndexKey : notnull { } public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -406,63 +385,182 @@ namespace ReactiveList.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] - public class QuaternaryList : ReactiveList.Collections.QuaternaryBase, ReactiveList.Collections.IQuaternaryList where T : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] + public sealed class QuaternaryList : ReactiveList.Collections.IQuaternaryList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Collections.IReactiveList>, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Collections.ReactiveList item, ReactiveList.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Collections.IReactiveList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -479,11 +577,13 @@ namespace ReactiveList.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -496,6 +596,7 @@ namespace ReactiveList.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -506,9 +607,11 @@ namespace ReactiveList.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -520,7 +623,6 @@ namespace ReactiveList.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -547,6 +649,19 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Core { @@ -561,6 +676,7 @@ namespace ReactiveList.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -778,7 +894,7 @@ namespace ReactiveList.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -791,12 +907,180 @@ namespace ReactiveList.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.IObservable> filterObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -814,19 +1098,20 @@ namespace ReactiveList.Views public ReactiveList.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Collections.IReactiveSource source, System.IObservable> filterObservable, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -847,6 +1132,7 @@ namespace ReactiveList.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -867,6 +1153,7 @@ namespace ReactiveList.Views public sealed class FilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.Func filter, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -887,6 +1174,7 @@ namespace ReactiveList.Views public sealed class GroupedReactiveView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Collections.IReactiveList source, System.Func keySelector, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -917,19 +1205,20 @@ namespace ReactiveList.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -950,6 +1239,7 @@ namespace ReactiveList.Views public sealed class SortedReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList/PublicAPI/net48/PublicAPI.txt b/src/ReactiveList/PublicAPI/net48/PublicAPI.txt index 6258bb8a..082db88e 100644 --- a/src/ReactiveList/PublicAPI/net48/PublicAPI.txt +++ b/src/ReactiveList/PublicAPI/net48/PublicAPI.txt @@ -166,7 +166,7 @@ namespace ReactiveList.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -180,14 +180,14 @@ namespace ReactiveList.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -225,6 +225,21 @@ namespace ReactiveList.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] public sealed class QuadDictionary : ReactiveList.Collections.IQuad> { @@ -322,63 +337,22 @@ namespace ReactiveList.Collections public static bool operator !=(ReactiveList.Collections.QuadList.Enumerator left, ReactiveList.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + public sealed class QuaternaryDictionary : ReactiveList.Collections.IQuaternaryDictionary, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item, ReactiveList.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - public class QuaternaryDictionary : ReactiveList.Collections.QuaternaryBase, TValue>, ReactiveList.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -386,17 +360,22 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) where TIndexKey : notnull { } public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -406,63 +385,182 @@ namespace ReactiveList.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] - public class QuaternaryList : ReactiveList.Collections.QuaternaryBase, ReactiveList.Collections.IQuaternaryList where T : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] + public sealed class QuaternaryList : ReactiveList.Collections.IQuaternaryList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Collections.IReactiveList>, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Collections.ReactiveList item, ReactiveList.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Collections.IReactiveList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -479,11 +577,13 @@ namespace ReactiveList.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -496,6 +596,7 @@ namespace ReactiveList.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -506,9 +607,11 @@ namespace ReactiveList.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -520,7 +623,6 @@ namespace ReactiveList.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -547,6 +649,19 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Core { @@ -561,6 +676,7 @@ namespace ReactiveList.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -778,7 +894,7 @@ namespace ReactiveList.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -791,12 +907,180 @@ namespace ReactiveList.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.IObservable> filterObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -814,19 +1098,20 @@ namespace ReactiveList.Views public ReactiveList.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Collections.IReactiveSource source, System.IObservable> filterObservable, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -847,6 +1132,7 @@ namespace ReactiveList.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -867,6 +1153,7 @@ namespace ReactiveList.Views public sealed class FilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.Func filter, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -887,6 +1174,7 @@ namespace ReactiveList.Views public sealed class GroupedReactiveView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Collections.IReactiveList source, System.Func keySelector, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -917,19 +1205,20 @@ namespace ReactiveList.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -950,6 +1239,7 @@ namespace ReactiveList.Views public sealed class SortedReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList/PublicAPI/net481/PublicAPI.txt b/src/ReactiveList/PublicAPI/net481/PublicAPI.txt index 6258bb8a..082db88e 100644 --- a/src/ReactiveList/PublicAPI/net481/PublicAPI.txt +++ b/src/ReactiveList/PublicAPI/net481/PublicAPI.txt @@ -166,7 +166,7 @@ namespace ReactiveList.Collections bool IsReadOnly { get; } void AddOrUpdate(TKey key, TValue value) { } void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator> GetEnumerator() { } System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } @@ -180,14 +180,14 @@ namespace ReactiveList.Collections { int Count { get; } bool IsReadOnly { get; } - void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } void AddRange(System.Collections.Generic.IEnumerable collection) { } void Edit(System.Action> editAction) { } System.Collections.Generic.IEnumerator GetEnumerator() { } - System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } + System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } int RemoveMany(System.Func predicate) { } void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } } public interface IReactiveList : ReactiveList.Collections.IReactiveSource, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.IList, System.ComponentModel.INotifyPropertyChanged where T : notnull { @@ -225,6 +225,21 @@ namespace ReactiveList.Collections System.Collections.Generic.IEnumerator GetEnumerator() { } T[] ToArray() { } } + public interface IReactiveSourceWithOptions + { + ReactiveList.Collections.ReactiveSourceOptions Options { get; } + } + public interface IVersionedSnapshotSource where T : notnull + { + System.IObservable> VersionedStream { get; } + T[] CopyVersioned(out long version) { } + } + [System.Diagnostics.DebuggerDisplay("Notification deferral")] + public readonly record struct NotificationDeferral : System.IDisposable, System.IEquatable + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly void Dispose() { } + } [System.Diagnostics.DebuggerDisplay("QuadDictionary: {Count}")] public sealed class QuadDictionary : ReactiveList.Collections.IQuad> { @@ -322,63 +337,22 @@ namespace ReactiveList.Collections public static bool operator !=(ReactiveList.Collections.QuadList.Enumerator left, ReactiveList.Collections.QuadList.Enumerator right) { } } } - [System.Diagnostics.DebuggerDisplay("QuaternaryBase: {Count}")] - public abstract class QuaternaryBase : ReactiveList.Collections.IReactiveSource, System.ComponentModel.INotifyPropertyChanged where TItem : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Count}")] + public sealed class QuaternaryDictionary : ReactiveList.Collections.IQuaternaryDictionary, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource>, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { - protected QuaternaryBase() { } - protected static readonly int ShardCount; - protected abstract System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public QuaternaryDictionary() { } public int Count { get; } - protected System.Collections.Concurrent.ConcurrentDictionary> Indices { get; } public bool IsDisposed { get; } public bool IsReadOnly { get; } - protected System.Threading.ReaderWriterLockSlim[] Locks { get; } - public System.IObservable> Stream { get; } - public long Version { get; } - public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; - public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void AddToCount(int value) { } - public void Clear() { } - public void Dispose() { } - protected virtual void Dispose(bool disposing) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void Emit(ReactiveList.Core.CacheAction action, TItem? item, ReactiveList.Core.PooledBatch? batch) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchAddedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchDirect(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemoved(TItem[] items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitBatchRemovedFromList(System.Collections.Generic.IList items, int count) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void EmitOwnedBatchRemoved(TItem[] items, int count) { } - public abstract System.Collections.Generic.IEnumerator GetEnumerator() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected bool HasChangeObservers() { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesAdded(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void NotifyIndicesRemoved(TValue item) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - protected void SetCount(int value) { } - [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } - public TItem[] ToArray() { } - } - [System.Diagnostics.DebuggerDisplay("QuaternaryDictionary: {Keys}")] - public class QuaternaryDictionary : ReactiveList.Collections.QuaternaryBase, TValue>, ReactiveList.Collections.IQuaternaryDictionary where TKey : notnull - { - public QuaternaryDictionary() { } - protected override System.Collections.Generic.IReadOnlyList>> BaseQuads { get; } public System.Collections.Generic.ICollection Keys { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Stream { get; } public System.Collections.Generic.ICollection Values { get; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } public TValue this[TKey key] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] @@ -386,17 +360,22 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddOrUpdate(TKey key, TValue value) { } public void AddRange(System.Collections.Generic.IEnumerable> pairs) { } - public void AddValueIndex(string name, System.Func keySelector) where TIndexKey : notnull { } + public void AddValueIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(System.Collections.Generic.KeyValuePair item) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) { } public void CopyTo(System.Collections.Generic.KeyValuePair[] array, int arrayIndex) { } + public System.Collections.Generic.KeyValuePair[] CopyVersioned(out long version) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) where TIndexKey : notnull { } public ReactiveList.Views.SecondaryIndexReactiveView CreateViewBySecondaryIndex(string indexName, TIndexKey key, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, int throttleMs) where TIndexKey : notnull { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator> GetEnumerator() { } + public System.Collections.Generic.IEnumerator> GetEnumerator() { } public System.Collections.Generic.IEnumerable GetValuesBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public (bool HasValue, TValue? Value) Lookup(TKey key) { } @@ -406,63 +385,182 @@ namespace ReactiveList.Collections public void RemoveKeys(System.Collections.Generic.IEnumerable keys) { } public int RemoveMany(System.Func, bool> predicate) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public System.Collections.Generic.KeyValuePair[] ToArray() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) { } public bool ValueMatchesSecondaryIndex(string indexName, TValue value, TIndexKey key) where TIndexKey : notnull { } } - [System.Diagnostics.DebuggerDisplay("QuaternaryList: {BaseQuads}")] - public class QuaternaryList : ReactiveList.Collections.QuaternaryBase, ReactiveList.Collections.IQuaternaryList where T : notnull + [System.Diagnostics.DebuggerDisplay("QuaternaryList: {Count}")] + public sealed class QuaternaryList : ReactiveList.Collections.IQuaternaryList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource, System.ComponentModel.INotifyPropertyChanged where T : notnull { public QuaternaryList() { } - protected override System.Collections.Generic.IReadOnlyList> BaseQuads { get; } + public int Count { get; } + public bool IsDisposed { get; } + public bool IsReadOnly { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable> Stream { get; } + public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Add(T item) { } - public void AddIndex(string name, System.Func keySelector) where TKey : notnull { } + public void AddIndex(string indexName, System.Func keySelector) where TIndexKey : notnull { } public void AddRange(System.Collections.Generic.IEnumerable collection) { } + public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } public void Edit(System.Action> editAction) { } - public override System.Collections.Generic.IEnumerator GetEnumerator() { } - public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TKey key) where TKey : notnull { } - public bool ItemMatchesSecondaryIndex(string indexName, T item, TKey key) where TKey : notnull { } + public System.Collections.Generic.IEnumerator GetEnumerator() { } + public System.Collections.Generic.IEnumerable GetItemsBySecondaryIndex(string indexName, TIndexKey key) where TIndexKey : notnull { } + public bool ItemMatchesSecondaryIndex(string indexName, T item, TIndexKey key) where TIndexKey : notnull { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } public int RemoveMany(System.Func predicate) { } public void RemoveRange(System.Collections.Generic.IEnumerable collection) { } - public void ReplaceAll(System.Collections.Generic.IEnumerable items) { } + public void ReplaceAll(System.Collections.Generic.IEnumerable collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IReadOnlyList Snapshot() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public T[] ToArray() { } } - public class Reactive2DList : ReactiveList.Collections.ReactiveList> where T : notnull + [System.Diagnostics.DebuggerDisplay("Rows = {Count}")] + public sealed class Reactive2DList : ReactiveList.Collections.IReactiveList>, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource> where T : notnull { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public Reactive2DList(T item) { } + public System.IObservable>> Added { get; } + public System.IObservable>> Changed { get; } + public int Count { get; } + public System.IObservable>> CurrentItems { get; } + public bool IsDisposed { get; } + public bool IsFixedSize { get; } + public bool IsReadOnly { get; } + public bool IsSynchronized { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsAdded { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsChanged { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } + public System.IObservable>> Removed { get; } + public System.IObservable>> Stream { get; } + public object SyncRoot { get; } + object? this[int index] { get; set; } + public long Version { get; } + public System.IObservable>> VersionedStream { get; } + public ReactiveList.Collections.ReactiveList this[int index] { get; set; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Add(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int Add(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable> items) { } public void AddRange(System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void AddRange(System.ReadOnlySpan> items) { } public void AddToInner(int outerIndex, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void AddToInner(int outerIndex, T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlyMemory> AsMemory() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.ReadOnlySpan> AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Clear() { } public void ClearInner(int outerIndex) { } - protected override void Dispose(bool disposing) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ClearWithoutDeallocation(bool notifyChange) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Contains(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Span> destination) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(ReactiveList.Collections.ReactiveList[] array, int arrayIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void CopyTo(System.Array array, int index) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] CopyVersioned(out long version) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Edit(System.Action>> editAction) { } public System.Collections.Generic.IEnumerable Flatten() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public T GetItem(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int IndexOf(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, ReactiveList.Collections.ReactiveList item) { } public void Insert(int index, T item) { } - public void Insert(int index, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Insert(int index, object? value) { } + public void Insert(int outerIndex, System.Collections.Generic.IEnumerable items, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, System.Collections.Generic.IEnumerable> items) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool Remove(ReactiveList.Collections.ReactiveList item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(System.Collections.Generic.IEnumerable> items) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Remove(object? value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) { } public void RemoveFromInner(int outerIndex, int innerIndex) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public int RemoveMany(System.Func, bool> predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(System.Collections.Generic.IEnumerable> items) { } public void SetItem(int outerIndex, int innerIndex, T value) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.IDisposable Subscribe(System.IObserver>> observer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public ReactiveList.Collections.ReactiveList[] ToArray() { } public int TotalCount() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Update(ReactiveList.Collections.ReactiveList item, ReactiveList.Collections.ReactiveList newValue) { } } [System.Diagnostics.DebuggerDisplay("Count = {Count}")] [System.Serializable] - public class ReactiveList : ReactiveList.Collections.IReactiveList where T : notnull + public sealed class ReactiveList : ReactiveList.Collections.IReactiveList, ReactiveList.Collections.IReactiveSourceWithOptions, ReactiveList.Collections.IVersionedSnapshotSource where T : notnull { public ReactiveList() { } public ReactiveList(System.Collections.Generic.IEnumerable items) { } @@ -479,11 +577,13 @@ namespace ReactiveList.Collections public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsAdded { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsChanged { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection ItemsRemoved { get; } + public ReactiveList.Collections.ReactiveSourceOptions Options { get; init; } public System.IObservable> Removed { get; } public System.IObservable> Stream { get; } public object SyncRoot { get; } object? this[int index] { get; set; } public long Version { get; } + public System.IObservable> VersionedStream { get; } public T this[int index] { get; set; } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; @@ -496,6 +596,7 @@ namespace ReactiveList.Collections public System.ReadOnlyMemory AsMemory() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.ReadOnlySpan AsSpan() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Clear() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void ClearWithoutDeallocation() { } @@ -506,9 +607,11 @@ namespace ReactiveList.Collections public void CopyTo(System.Span destination) { } public void CopyTo(System.Array array, int index) { } public void CopyTo(T[] array, int arrayIndex) { } + public T[] CopyVersioned(out long version) { } + public ReactiveList.Collections.NotificationDeferral DeferNotifications() { } public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public void Edit(System.Action> editAction) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public System.Collections.Generic.IEnumerator GetEnumerator() { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public int IndexOf(T item) { } @@ -520,7 +623,6 @@ namespace ReactiveList.Collections public void InsertRange(int index, System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Move(int oldIndex, int newIndex) { } - protected virtual void OnPropertyChanged(string propertyName) { } public void Remove(System.Collections.Generic.IEnumerable items) { } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { } @@ -547,6 +649,19 @@ namespace ReactiveList.Collections [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Update(T item, T newValue) { } } + [System.Diagnostics.DebuggerDisplay("ItemsAreImmutable = {ItemsAreImmutable}")] + public sealed class ReactiveSourceOptions + { + public ReactiveSourceOptions() { } + public bool ItemsAreImmutable { get; init; } + } + [System.Diagnostics.DebuggerDisplay("Version = {Version}")] + public readonly record struct VersionedNotification : System.IEquatable> + { + public VersionedNotification(ReactiveList.Core.CacheNotify Notification, long Version) { } + public ReactiveList.Core.CacheNotify Notification { get; init; } + public long Version { get; init; } + } } namespace ReactiveList.Core { @@ -561,6 +676,7 @@ namespace ReactiveList.Core BatchOperation = 6, BatchAdded = 7, BatchRemoved = 8, + Reset = 9, } [System.Diagnostics.DebuggerDisplay("CacheNotify: {ToString(),nq}")] public record CacheNotify : System.IEquatable> @@ -778,7 +894,7 @@ namespace ReactiveList.Core System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndex: {_shards}")] - public class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull + public sealed class SecondaryIndex : ReactiveList.Core.ISecondaryIndex where TKey : notnull { public SecondaryIndex(System.Func selector) { } public void Clear() { } @@ -791,12 +907,180 @@ namespace ReactiveList.Core public void OnUpdated(T oldItem, T newItem) { } } } +namespace ReactiveList.Queries +{ + [System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] + public readonly record struct GroupedLiveQuery : System.IEquatable> where TKey : notnull where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveGroupView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } + [System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] + public sealed class LiveGroupView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } + public System.Collections.Generic.IEnumerable Keys { get; } + public System.Collections.Generic.IEnumerable> Values { get; } + public System.Collections.Generic.IReadOnlyList this[TKey key] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator>> GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveGroupView ToProperty(System.Action>> propertySetter) { } + public ReactiveList.Queries.LiveGroupView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection> collection) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out System.Collections.Generic.IReadOnlyList value) { } + } + [System.Diagnostics.DebuggerDisplay("LiveQuery")] + public readonly record struct LiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + public readonly System.IObservable Any(System.Func predicate) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly System.IObservable Count(System.Func predicate) { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery OrderByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.LiveQuery Where(System.Func predicate) { } + } + public static class LiveQueryExtensions + { + extension(ReactiveList.Collections.IReactiveSource source) where T : notnull + { + public ReactiveList.Queries.LiveQuery Live { get; } + } + extension(ReactiveList.Collections.IQuaternaryDictionary dictionary) where TKey : notnull + { + public ReactiveList.Queries.LiveQuery> Live { get; } + } + extension(ReactiveList.Queries.LiveQuery> query) where TKey : notnull + { + public System.IObservable> ObserveValue(TKey key) { } + } + } + [System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] + public readonly record struct LiveValue : System.IEquatable> + { + public LiveValue(bool Found, TValue? Value) { } + public bool Found { get; init; } + public TValue? Value { get; init; } + } + [System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] + public sealed class LiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull + { + public int BatchResetLimit { get; set; } + public int Count { get; } + public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } + public T this[int index] { get; } + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler? CollectionChanged; + public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Dispose() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public System.Collections.Generic.IEnumerator GetEnumerator() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public void Refresh() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { } + public ReactiveList.Queries.LiveView ToProperty(System.Action> propertySetter) { } + public ReactiveList.Queries.LiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } + } + [System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] + public readonly record struct OrderedLiveQuery : System.IEquatable> where T : notnull + { + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Any() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Contains(T item) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly System.IObservable Count() { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector) where TKey : notnull { } + public readonly ReactiveList.Queries.GroupedLiveQuery GroupBy(System.Func keySelector, System.Func elementSelector) where TKey : notnull where TElement : notnull { } + public readonly ReactiveList.Queries.LiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly System.IObservable SelectMany(System.Func> selector) { } + public readonly System.IObservable SelectMany(System.Func> collectionSelector, System.Func resultSelector) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenBy(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector) { } + public readonly ReactiveList.Queries.OrderedLiveQuery ThenByDescending(System.Func keySelector, System.Collections.Generic.IComparer comparer) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + public readonly ReactiveList.Queries.OrderedLiveQuery Where(System.Func predicate) { } + } + [System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] + public readonly record struct WindowedLiveQuery : System.IEquatable> where T : notnull + { + public readonly ReactiveList.Queries.WindowedLiveQuery Select(System.Func selector) where TResult : notnull { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Skip(int count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(System.IObservable count) { } + public readonly ReactiveList.Queries.WindowedLiveQuery Take(int count) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView() { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(int throttleMs) { } + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + public readonly ReactiveList.Queries.LiveView ToView(ReactiveUI.Primitives.Concurrency.ISequencer? scheduler, int throttleMs) { } + } +} namespace ReactiveList.Views { [System.Diagnostics.DebuggerDisplay("DynamicFilteredReactiveView: {Count}")] public sealed class DynamicFilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicFilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.IObservable> filterObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -814,19 +1098,20 @@ namespace ReactiveList.Views public ReactiveList.Views.DynamicFilteredReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] - public class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class DynamicReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { public DynamicReactiveView(ReactiveList.Collections.IReactiveSource source, System.IObservable> filterObservable, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.DynamicReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.DynamicReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("DynamicSecondaryIndexDictionaryReactiveView: {Count}")] public sealed class DynamicSecondaryIndexDictionaryReactiveView : ReactiveList.Views.IReactiveView, System.Collections.Generic.KeyValuePair>, System.Collections.Generic.IReadOnlyList>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } public System.Collections.Generic.KeyValuePair this[int index] { get; } @@ -847,6 +1132,7 @@ namespace ReactiveList.Views public sealed class DynamicSecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public DynamicSecondaryIndexReactiveView(ReactiveList.Collections.QuaternaryList source, string indexName, System.IObservable keysObservable, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -867,6 +1153,7 @@ namespace ReactiveList.Views public sealed class FilteredReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public FilteredReactiveView(ReactiveList.Collections.IReactiveList source, System.Func filter, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } @@ -887,6 +1174,7 @@ namespace ReactiveList.Views public sealed class GroupedReactiveView : ReactiveList.Views.IReactiveView, ReactiveList.Core.ReactiveGroup>, System.Collections.Generic.IReadOnlyDictionary>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull where TKey : notnull { public GroupedReactiveView(ReactiveList.Collections.IReactiveList source, System.Func keySelector, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Groups { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection> Items { get; } @@ -917,19 +1205,20 @@ namespace ReactiveList.Views TView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] - public class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull + public sealed class ReactiveView : ReactiveList.Views.IReactiveView, T>, System.ComponentModel.INotifyPropertyChanged where T : notnull { - public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer sheduler) { } + public ReactiveView(System.IObservable> stream, System.Collections.Generic.IEnumerable snapshot, System.Func filter, System.TimeSpan throttle, ReactiveUI.Primitives.Concurrency.ISequencer scheduler) { } + public int BatchResetLimit { get; set; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged; public void Dispose() { } - protected virtual void Dispose(bool disposing) { } public ReactiveList.Views.ReactiveView ToProperty(System.Action> propertySetter) { } public ReactiveList.Views.ReactiveView ToProperty(out System.Collections.ObjectModel.ReadOnlyObservableCollection collection) { } } [System.Diagnostics.DebuggerDisplay("SecondaryIndexReactiveView: {Count}")] public sealed class SecondaryIndexReactiveView : ReactiveList.Views.IReactiveView, TValue>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where TKey : notnull { + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public TValue this[int index] { get; } @@ -950,6 +1239,7 @@ namespace ReactiveList.Views public sealed class SortedReactiveView : ReactiveList.Views.IReactiveView, T>, System.Collections.Generic.IReadOnlyList, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged where T : notnull { public SortedReactiveView(ReactiveList.Collections.IReactiveList source, System.Collections.Generic.IComparer comparer, ReactiveUI.Primitives.Concurrency.ISequencer scheduler, System.TimeSpan throttle) { } + public int BatchResetLimit { get; set; } public int Count { get; } public System.Collections.ObjectModel.ReadOnlyObservableCollection Items { get; } public T this[int index] { get; } diff --git a/src/ReactiveList/QuaternaryExtensions.cs b/src/ReactiveList/QuaternaryExtensions.cs index c633157d..d1d6e797 100644 --- a/src/ReactiveList/QuaternaryExtensions.cs +++ b/src/ReactiveList/QuaternaryExtensions.cs @@ -40,9 +40,9 @@ public static class QuaternaryExtensions public IObservable>> FilterBySecondaryIndex(QuaternaryDictionary dict, string indexName, TIndexKey indexKey) where TIndexKey : notnull { - ThrowHelper.ThrowIfNull(stream); - ThrowHelper.ThrowIfNull(dict); - ThrowHelper.ThrowIfNull(indexName); + ArgumentExceptionHelper.ThrowIfNull(stream); + ArgumentExceptionHelper.ThrowIfNull(dict); + ArgumentExceptionHelper.ThrowIfNull(indexName); var request = new SecondaryIndexFilterRequest, TIndexKey>(dict, indexName, indexKey, null); return BatchFilterHelper.FilterNotificationStream( @@ -63,10 +63,10 @@ public IObservable>> FilterBySecondaryInd public IObservable>> FilterBySecondaryIndex(QuaternaryDictionary dict, string indexName, params TIndexKey[] indexKeys) where TIndexKey : notnull { - ThrowHelper.ThrowIfNull(stream); - ThrowHelper.ThrowIfNull(dict); - ThrowHelper.ThrowIfNull(indexName); - ThrowHelper.ThrowIfNull(indexKeys); + ArgumentExceptionHelper.ThrowIfNull(stream); + ArgumentExceptionHelper.ThrowIfNull(dict); + ArgumentExceptionHelper.ThrowIfNull(indexName); + ArgumentExceptionHelper.ThrowIfNull(indexKeys); var request = new SecondaryIndexFilterRequest, TIndexKey>(dict, indexName, default, indexKeys); return BatchFilterHelper.FilterNotificationStream(stream, request, MatchesAnyDictionaryKey); @@ -88,9 +88,9 @@ public IObservable>> FilterBySecondaryInd public IObservable> FilterBySecondaryIndex(QuaternaryList list, string indexName, TKey key) where TKey : notnull { - ThrowHelper.ThrowIfNull(stream); - ThrowHelper.ThrowIfNull(list); - ThrowHelper.ThrowIfNull(indexName); + ArgumentExceptionHelper.ThrowIfNull(stream); + ArgumentExceptionHelper.ThrowIfNull(list); + ArgumentExceptionHelper.ThrowIfNull(indexName); var request = new SecondaryIndexFilterRequest, TKey>(list, indexName, key, null); return BatchFilterHelper.FilterNotificationStream( @@ -109,10 +109,10 @@ public IObservable> FilterBySecondaryIndex(QuaternaryList> FilterBySecondaryIndex(QuaternaryList list, string indexName, params TKey[] keys) where TKey : notnull { - ThrowHelper.ThrowIfNull(stream); - ThrowHelper.ThrowIfNull(list); - ThrowHelper.ThrowIfNull(indexName); - ThrowHelper.ThrowIfNull(keys); + ArgumentExceptionHelper.ThrowIfNull(stream); + ArgumentExceptionHelper.ThrowIfNull(list); + ArgumentExceptionHelper.ThrowIfNull(indexName); + ArgumentExceptionHelper.ThrowIfNull(keys); var request = new SecondaryIndexFilterRequest, TKey>(list, indexName, default, keys); return BatchFilterHelper.FilterNotificationStream(stream, request, MatchesAnyListKey); @@ -154,30 +154,16 @@ public ReactiveView> CreateViewBySecondaryIndex> CreateViewBySecondaryIndex(string indexName, TIndexKey indexKey, ISequencer scheduler, int throttleMs) where TIndexKey : notnull { - ThrowHelper.ThrowIfNull(dict); - ThrowHelper.ThrowIfNull(indexName); - - // Get initial snapshot from the secondary index - map values back to key-value pairs - var matchingValues = new HashSet(dict.GetValuesBySecondaryIndex(indexName, indexKey)); - - IEnumerable> GetSnapshot() - { - foreach (var item in dict) - { - if (matchingValues.Contains(item.Value)) - { - yield return item; - } - } - } + ArgumentExceptionHelper.ThrowIfNull(dict); + ArgumentExceptionHelper.ThrowIfNull(indexName); // Create a filter that dynamically checks against the secondary index return new( - dict.Stream, - GetSnapshot(), + dict, kvp => dict.ValueMatchesSecondaryIndex(indexName, kvp.Value, indexKey), TimeSpan.FromMilliseconds(throttleMs), - scheduler); + scheduler, + static (left, right) => EqualityComparer.Default.Equals(left.Key, right.Key)); } /// Creates a reactive view filtered by multiple secondary value index keys. @@ -208,30 +194,9 @@ public ReactiveView> CreateViewBySecondaryIndex> CreateViewBySecondaryIndex(string indexName, TIndexKey[] indexKeys, ISequencer scheduler, int throttleMs) where TIndexKey : notnull { - ThrowHelper.ThrowIfNull(dict); - ThrowHelper.ThrowIfNull(indexName); - ThrowHelper.ThrowIfNull(indexKeys); - - // Get initial snapshot from the secondary index for all keys - var matchingValues = new HashSet(); - foreach (var key in indexKeys) - { - foreach (var value in dict.GetValuesBySecondaryIndex(indexName, key)) - { - _ = matchingValues.Add(value); - } - } - - IEnumerable> GetSnapshot() - { - foreach (var item in dict) - { - if (matchingValues.Contains(item.Value)) - { - yield return item; - } - } - } + ArgumentExceptionHelper.ThrowIfNull(dict); + ArgumentExceptionHelper.ThrowIfNull(indexName); + ArgumentExceptionHelper.ThrowIfNull(indexKeys); // Create a filter that dynamically checks against any of the keys var keySet = new HashSet(indexKeys); @@ -250,11 +215,11 @@ bool MatchesAny(TValue value) } return new( - dict.Stream, - GetSnapshot(), + dict, kvp => MatchesAny(kvp.Value), TimeSpan.FromMilliseconds(throttleMs), - scheduler); + scheduler, + static (left, right) => EqualityComparer.Default.Equals(left.Key, right.Key)); } /// @@ -291,9 +256,9 @@ public DynamicSecondaryIndexDictionaryReactiveView CreateDynamicVi int throttleMs) where TIndexKey : notnull { - ThrowHelper.ThrowIfNull(dict); - ThrowHelper.ThrowIfNull(indexName); - ThrowHelper.ThrowIfNull(keysObservable); + ArgumentExceptionHelper.ThrowIfNull(dict); + ArgumentExceptionHelper.ThrowIfNull(indexName); + ArgumentExceptionHelper.ThrowIfNull(keysObservable); return DynamicSecondaryIndexDictionaryReactiveView.Create(dict, indexName, keysObservable, scheduler, TimeSpan.FromMilliseconds(throttleMs)); } @@ -330,17 +295,13 @@ public ReactiveView CreateViewBySecondaryIndex(string indexName, TKey k public ReactiveView CreateViewBySecondaryIndex(string indexName, TKey key, ISequencer scheduler, int throttleMs) where TKey : notnull { - ThrowHelper.ThrowIfNull(list); - ThrowHelper.ThrowIfNull(indexName); - - // Get initial snapshot from the secondary index - var snapshot = list.GetItemsBySecondaryIndex(indexName, key); + ArgumentExceptionHelper.ThrowIfNull(list); + ArgumentExceptionHelper.ThrowIfNull(indexName); // Create a filter that dynamically checks against the secondary index // This ensures new items are properly filtered based on their key value return new( - list.Stream, - snapshot, + list, item => list.ItemMatchesSecondaryIndex(indexName, item, key), TimeSpan.FromMilliseconds(throttleMs), scheduler); @@ -371,21 +332,9 @@ public ReactiveView CreateViewBySecondaryIndex(string indexName, TKey[] public ReactiveView CreateViewBySecondaryIndex(string indexName, TKey[] keys, ISequencer scheduler, int throttleMs) where TKey : notnull { - ThrowHelper.ThrowIfNull(list); - ThrowHelper.ThrowIfNull(indexName); - ThrowHelper.ThrowIfNull(keys); - - // Get initial snapshot from the secondary index for all keys - IEnumerable GetSnapshot() - { - foreach (var key in keys) - { - foreach (var item in list.GetItemsBySecondaryIndex(indexName, key)) - { - yield return item; - } - } - } + ArgumentExceptionHelper.ThrowIfNull(list); + ArgumentExceptionHelper.ThrowIfNull(indexName); + ArgumentExceptionHelper.ThrowIfNull(keys); // Create a filter that dynamically checks against any of the keys var keySet = new HashSet(keys); @@ -404,8 +353,7 @@ bool MatchesAny(T item) } return new( - list.Stream, - GetSnapshot(), + list, MatchesAny, TimeSpan.FromMilliseconds(throttleMs), scheduler); @@ -439,9 +387,9 @@ public DynamicSecondaryIndexReactiveView CreateDynamicViewBySecondaryIn public DynamicSecondaryIndexReactiveView CreateDynamicViewBySecondaryIndex(string indexName, IObservable keysObservable, ISequencer scheduler, int throttleMs) where TKey : notnull { - ThrowHelper.ThrowIfNull(list); - ThrowHelper.ThrowIfNull(indexName); - ThrowHelper.ThrowIfNull(keysObservable); + ArgumentExceptionHelper.ThrowIfNull(list); + ArgumentExceptionHelper.ThrowIfNull(indexName); + ArgumentExceptionHelper.ThrowIfNull(keysObservable); return new(list, indexName, keysObservable, scheduler, TimeSpan.FromMilliseconds(throttleMs)); } @@ -454,7 +402,7 @@ public DynamicSecondaryIndexReactiveView CreateDynamicViewBySecondaryIn /// The candidate entry. /// The secondary-index filter request. /// when the entry matches at least one requested key; otherwise, . - private static bool MatchesAnyDictionaryKey( + internal static bool MatchesAnyDictionaryKey( KeyValuePair item, SecondaryIndexFilterRequest, TIndexKey> request) where TKey : notnull @@ -482,7 +430,7 @@ private static bool MatchesAnyDictionaryKey( /// The candidate item. /// The secondary-index filter request. /// when the item matches at least one requested key; otherwise, . - private static bool MatchesAnyListKey( + internal static bool MatchesAnyListKey( T item, SecondaryIndexFilterRequest, TIndexKey> request) where T : notnull diff --git a/src/ReactiveList/Queries/GroupedLiveQuery.cs b/src/ReactiveList/Queries/GroupedLiveQuery.cs new file mode 100644 index 00000000..6ee1969d --- /dev/null +++ b/src/ReactiveList/Queries/GroupedLiveQuery.cs @@ -0,0 +1,50 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// A live query whose items are grouped by a key. +/// The grouping key type. +/// The item type the groups hold. +[System.Diagnostics.DebuggerDisplay("GroupedLiveQuery")] +public readonly record struct GroupedLiveQuery + where TKey : notnull + where T : notnull +{ + /// The recorded grouping. + private readonly ILiveGroupPlan _plan; + + /// Initializes a new instance of the struct. + /// The recorded grouping. + internal GroupedLiveQuery(ILiveGroupPlan plan) => _plan = plan; + + /// Creates a view with the default scheduler and throttle. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveGroupView ToView() => ToView(null, LiveQueryPlans.DefaultThrottleMs); + + /// Creates a view with the specified scheduler and the default throttle. + /// The scheduler that applies changes, or for the current-thread scheduler. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveGroupView ToView(ISequencer? scheduler) => ToView(scheduler, LiveQueryPlans.DefaultThrottleMs); + + /// Creates a view with the default scheduler and the specified throttle. + /// The coalescing window in milliseconds. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveGroupView ToView(int throttleMs) => ToView(null, throttleMs); + + /// Creates a view. + /// The scheduler that applies changes, or for the current-thread scheduler. + /// The coalescing window in milliseconds. Zero applies changes as soon as the scheduler runs. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveGroupView ToView(ISequencer? scheduler, int throttleMs) => + LiveQueryPlans.Groups(_plan, scheduler, throttleMs); +} diff --git a/src/ReactiveList/Queries/ILiveFeed.cs b/src/ReactiveList/Queries/ILiveFeed.cs new file mode 100644 index 00000000..ac8fa92d --- /dev/null +++ b/src/ReactiveList/Queries/ILiveFeed.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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// A source together with the filters and projections a query recorded, hiding the source item type. +/// The item type the query exposes. +internal interface ILiveFeed + where T : notnull +{ + /// Records a filter. + /// The filter. + /// The extended feed. + ILiveFeed Where(Func predicate); + + /// Records a projection. + /// The projected item type. + /// The projection. + /// The extended feed. + ILiveFeed Select(Func selector) + where TResult : notnull; + + /// Plans the query onto one view. + /// The ordering and window. + /// The scheduler that applies changes. + /// The coalescing window. + /// The view engine. + ILiveViewCore CreateView(in LiveShape shape, ISequencer scheduler, TimeSpan throttle); + + /// Plans the query onto one view, orders and windows its items and then projects the survivors. + /// The projected item type. + /// The ordering and window, applied to the items before the projection. + /// Projects an item that remains in the window. + /// The scheduler that applies changes. + /// The coalescing window. + /// The view engine. + ILiveViewCore CreateProjectedView(in LiveShape shape, Func project, ISequencer scheduler, TimeSpan throttle) + where TOut : notnull; + + /// Plans the query onto one grouped view. + /// The grouping key type. + /// The member type. + /// Extracts the grouping key. + /// Extracts the member from an item. + /// The ordering of the members, or for source order. + /// The scheduler that applies changes. + /// The coalescing window. + /// The group engine. + ILiveGroupCore CreateGroups( + Func keySelector, + Func elementSelector, + IComparer? order, + ISequencer scheduler, + TimeSpan throttle) + where TKey : notnull + where TElement : notnull; + + /// Plans the number of included items as a state stream. + /// An extra test, or . + /// The state stream. + IObservable Count(Func? predicate); + + /// Plans whether any item is included as a state stream. + /// An extra test, or . + /// The state stream. + IObservable Any(Func? predicate); + + /// Plans whether an item is included as a state stream. + /// The item. + /// The state stream. + IObservable Contains(T item); + + /// Plans the merge of one observable per included item. + /// The merged value type. + /// Creates the observable of an item. + /// The merged observable. + IObservable SelectMany(Func> selector); +} diff --git a/src/ReactiveList/Queries/ILiveGroupCore.cs b/src/ReactiveList/Queries/ILiveGroupCore.cs new file mode 100644 index 00000000..a9ae4100 --- /dev/null +++ b/src/ReactiveList/Queries/ILiveGroupCore.cs @@ -0,0 +1,63 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// The engine behind a . +/// The grouping key type. +/// The item type. +internal interface ILiveGroupCore : IDisposable + where TKey : notnull + where T : notnull +{ + /// Gets the read-only groups. + ReadOnlyObservableCollection> Groups { get; } + + /// Gets the number of groups. + int Count { get; } + + /// Gets or sets the number of changes above which one operation raises a single reset instead of one notification per change. + int ResetLimit { get; set; } + + /// Gets the observable stream of collection-change notifications. + IObservable CollectionChanges { get; } + + /// Gets the observable stream of property-change notifications. + IObservable PropertyChanges { get; } + + /// Determines whether a group exists. + /// The group key. + /// when the group exists. + bool ContainsKey(TKey key); + + /// Gets the members of a group. + /// The group key. + /// The members. + IReadOnlyList GetItems(TKey key); + + /// Tries to get the members of a group. + /// The group key. + /// The members, or an empty list. + /// when the group exists. + bool TryGetValue(TKey key, out IReadOnlyList value); + + /// Copies the group keys. + /// The keys. + TKey[] SnapshotKeys(); + + /// Copies the group member lists. + /// The member lists. + IReadOnlyList[] SnapshotValues(); + + /// Copies the key and members of every group. + /// The pairs. + KeyValuePair>[] SnapshotPairs(); + + /// Rebuilds the groups from the source on the calling thread. + void Refresh(); +} diff --git a/src/ReactiveList/Queries/ILiveGroupPlan.cs b/src/ReactiveList/Queries/ILiveGroupPlan.cs new file mode 100644 index 00000000..b0815105 --- /dev/null +++ b/src/ReactiveList/Queries/ILiveGroupPlan.cs @@ -0,0 +1,23 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// A recorded grouping that hides the item type the groups are formed from. +/// The grouping key type. +/// The member type. +internal interface ILiveGroupPlan + where TKey : notnull + where T : notnull +{ + /// Plans the grouping onto one grouped view. + /// The scheduler that applies changes. + /// The coalescing window. + /// The group engine. + ILiveGroupCore Create(ISequencer scheduler, TimeSpan throttle); +} diff --git a/src/ReactiveList/Queries/ILiveViewCore.cs b/src/ReactiveList/Queries/ILiveViewCore.cs new file mode 100644 index 00000000..9e2870db --- /dev/null +++ b/src/ReactiveList/Queries/ILiveViewCore.cs @@ -0,0 +1,33 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// The engine behind a . +/// The item type. +internal interface ILiveViewCore : IDisposable + where T : notnull +{ + /// Gets the read-only items. + ReadOnlyObservableCollection Items { get; } + + /// Gets the output collection with synchronized storage reads. + BatchObservableCollection Storage { get; } + + /// Gets or sets the number of changes above which one operation raises a single reset instead of one notification per change. + int ResetLimit { get; set; } + + /// Gets the observable stream of collection-change notifications. + IObservable CollectionChanges { get; } + + /// Gets the observable stream of property-change notifications. + IObservable PropertyChanges { get; } + + /// Rebuilds the items from the source on the calling thread. + void Refresh(); +} diff --git a/src/ReactiveList/Queries/LiveBinding.cs b/src/ReactiveList/Queries/LiveBinding.cs new file mode 100644 index 00000000..52323bee --- /dev/null +++ b/src/ReactiveList/Queries/LiveBinding.cs @@ -0,0 +1,62 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Creates, evaluates and compares the entries of one query. +/// The source item type. +/// The item type the query exposes. +internal sealed class LiveBinding + where TRaw : notnull + where T : notnull +{ + /// Initializes a new instance of the class. + /// The recorded filters and projections. + /// Tells whether two source items are equal. + /// Tells whether two source items are the same entry of a keyed source, or . + internal LiveBinding(LiveTryMap map, IEqualityComparer comparer, Func? sameRaw) + { + Map = map; + Comparer = comparer; + SameRaw = sameRaw; + Identity = new(comparer); + } + + /// Gets the recorded filters and projections. + internal LiveTryMap Map { get; } + + /// Gets the comparer that tells whether two source items are equal. + internal IEqualityComparer Comparer { get; } + + /// Gets the comparer that tells whether two source items are the same occurrence: the same instance for reference types. + internal LiveIdentityComparer Identity { get; } + + /// Gets the test for two source items being the same entry of a keyed source, or . + internal Func? SameRaw { get; } + + /// Evaluates an entry and tells whether it belongs in the query. + /// The entry. + /// when the entry belongs in the query. + internal static bool Matches(LiveEntry entry) + { + entry.Resolve(); + return entry.Included; + } + + /// Creates an entry that is evaluated when first needed. + /// The source item. + /// The entry. + internal LiveEntry CreateEntry(TRaw raw) => new(raw, this); + + /// Tells whether two entries are the same entry of a keyed source. + /// The first entry. + /// The second entry. + /// when both name the same key. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal bool SameEntry(LiveEntry left, LiveEntry right) => SameRaw!(left.Raw, right.Raw); +} diff --git a/src/ReactiveList/Queries/LiveChangeSerializer.cs b/src/ReactiveList/Queries/LiveChangeSerializer.cs new file mode 100644 index 00000000..b353bc34 --- /dev/null +++ b/src/ReactiveList/Queries/LiveChangeSerializer.cs @@ -0,0 +1,89 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// +/// Lets one thread at a time mirror the changes of a collection into a derived structure. A change that arrives while another thread is +/// working is not applied on its own: the thread that is working rebuilds the structure from the collection once it is done, so no +/// change is lost and no lock is held while the structure raises its own notifications. +/// +/// Applies one change, and returns when the change cannot be applied exactly. +/// Rebuilds the structure from the whole collection. +/// Tells whether the owner was disposed. +internal sealed class LiveChangeSerializer( + Func apply, + Action rebuild, + Func isStopped) +{ + /// Non-zero while a thread is working on the structure. + private int _busy; + + /// Non-zero when the structure must be rebuilt from the collection. + private int _full; + + /// Applies a change of the collection, or rebuilds when it cannot be applied. + /// The change. + internal void Handle(NotifyCollectionChangedEventArgs e) + { + if (isStopped()) + { + return; + } + + if (Interlocked.CompareExchange(ref _busy, 1, 0) == 0) + { + try + { + if (Volatile.Read(ref _full) != 0) + { + Volatile.Write(ref _full, 0); + rebuild(); + } + else if (!apply(e)) + { + rebuild(); + } + } + finally + { + _ = Interlocked.Exchange(ref _busy, 0); + } + } + else + { + Volatile.Write(ref _full, 1); + } + + DrainRequests(); + } + + /// Rebuilds the structure from the collection, now or once the thread that is working is done. + internal void Rebuild() + { + Volatile.Write(ref _full, 1); + DrainRequests(); + } + + /// Rebuilds while a rebuild is requested and no other thread is working. + private void DrainRequests() + { + while (Volatile.Read(ref _full) != 0 && !isStopped() && Interlocked.CompareExchange(ref _busy, 1, 0) == 0) + { + try + { + Volatile.Write(ref _full, 0); + rebuild(); + } + finally + { + _ = Interlocked.Exchange(ref _busy, 0); + } + } + } +} diff --git a/src/ReactiveList/Queries/LiveComposedSelector.cs b/src/ReactiveList/Queries/LiveComposedSelector.cs new file mode 100644 index 00000000..8e99411c --- /dev/null +++ b/src/ReactiveList/Queries/LiveComposedSelector.cs @@ -0,0 +1,24 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Applies one projection to the result of another. +/// The item type before the first projection. +/// The item type between the projections. +/// The item type after the second projection. +/// The first projection. +/// The second projection. +internal sealed class LiveComposedSelector(Func first, Func second) +{ + /// Projects an item with both projections. + /// The item. + /// The result of the second projection. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal TResult Select(T item) => second(first(item)); +} diff --git a/src/ReactiveList/Queries/LiveCountReader.cs b/src/ReactiveList/Queries/LiveCountReader.cs new file mode 100644 index 00000000..4b7c0c9e --- /dev/null +++ b/src/ReactiveList/Queries/LiveCountReader.cs @@ -0,0 +1,23 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Reads a value derived from a source's own count. +/// The source item type. +/// The derived value type. +/// The source. +/// Derives the value from the count. +internal sealed record LiveCountReader(IReactiveSource Source, Func Project) + where TRaw : notnull +{ + /// Reads the value. + /// The value derived from the source's current count. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal TOut Read() => Project(Source.Count); +} diff --git a/src/ReactiveList/Queries/LiveDrainRequests.cs b/src/ReactiveList/Queries/LiveDrainRequests.cs new file mode 100644 index 00000000..0d3f5967 --- /dev/null +++ b/src/ReactiveList/Queries/LiveDrainRequests.cs @@ -0,0 +1,24 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Asks a view to drain only when a change is waiting for it. +internal static class LiveDrainRequests +{ + /// Runs a drain request when a change is queued. + /// Whether a change is waiting. + /// Asks the owner to drain. + internal static void RequestIf(bool queued, Action requestDrain) + { + if (queued) + { + requestDrain(); + } + } +} diff --git a/src/ReactiveList/Queries/LiveEntry.cs b/src/ReactiveList/Queries/LiveEntry.cs new file mode 100644 index 00000000..95f1af9c --- /dev/null +++ b/src/ReactiveList/Queries/LiveEntry.cs @@ -0,0 +1,74 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// One source item together with what the query made of it. +/// The source item type. +/// The item type the query exposes. +internal sealed class LiveEntry : IEquatable> + where TRaw : notnull + where T : notnull +{ + /// The binding that evaluates and compares entries. + private readonly LiveBinding _binding; + + /// Whether was evaluated. + private bool _resolved; + + /// Initializes a new instance of the class. + /// The source item. + /// The binding that evaluates and compares entries. + internal LiveEntry(TRaw raw, LiveBinding binding) + { + Raw = raw; + _binding = binding; + Value = default!; + } + + /// Gets the source item. + internal TRaw Raw { get; } + + /// Gets the exposed item, which is meaningful once the entry was evaluated and passed. + internal T Value { get; private set; } + + /// Gets or sets a value indicating whether the entry currently sits in the query's sequence. + internal bool Included { get; set; } + + /// Gets or sets the subscription a merge holds for this entry. + internal IDisposable? Subscription { get; set; } + + /// + public bool Equals(LiveEntry? other) => + other is not null && _binding.Comparer.Equals(Raw, other.Raw); + + /// + public override bool Equals(object? obj) => Equals(obj as LiveEntry); + + /// + public override int GetHashCode() => _binding.Comparer.GetHashCode(Raw); + + /// Evaluates the recorded filters and projections without recording the outcome as membership. + /// when the source item belongs in the query. + internal bool Evaluate() + { + _resolved = true; + var passes = _binding.Map(Raw, out var value); + Value = value; + return passes; + } + + /// Evaluates the entry once and records whether it belongs in the query. + internal void Resolve() + { + if (!_resolved) + { + Included = Evaluate(); + } + } +} diff --git a/src/ReactiveList/Queries/LiveEntryComparer.cs b/src/ReactiveList/Queries/LiveEntryComparer.cs new file mode 100644 index 00000000..ea64b264 --- /dev/null +++ b/src/ReactiveList/Queries/LiveEntryComparer.cs @@ -0,0 +1,28 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Orders entries by the item the query exposes. +/// The source item type. +/// The item type the query exposes. +internal sealed class LiveEntryComparer : IComparer> + where TRaw : notnull + where T : notnull +{ + /// Orders the exposed items. + private readonly IComparer _order; + + /// Initializes a new instance of the class. + /// Orders the exposed items. + internal LiveEntryComparer(IComparer order) => _order = order; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Compare(LiveEntry? x, LiveEntry? y) => _order.Compare(x!.Value, y!.Value); +} diff --git a/src/ReactiveList/Queries/LiveEquals.cs b/src/ReactiveList/Queries/LiveEquals.cs new file mode 100644 index 00000000..3b9e1142 --- /dev/null +++ b/src/ReactiveList/Queries/LiveEquals.cs @@ -0,0 +1,21 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Tests items for equality with one item. +/// The item type. +/// The item to compare with. +internal sealed record LiveEquals(T Item) +{ + /// Tests an item. + /// The candidate. + /// when the candidate equals . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal bool Matches(T candidate) => EqualityComparer.Default.Equals(candidate, Item); +} diff --git a/src/ReactiveList/Queries/LiveEventObservables.cs b/src/ReactiveList/Queries/LiveEventObservables.cs new file mode 100644 index 00000000..bd626b65 --- /dev/null +++ b/src/ReactiveList/Queries/LiveEventObservables.cs @@ -0,0 +1,37 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Turns the events of an existing view into observables. +internal static class LiveEventObservables +{ + /// Observes the collection-change event of a view while subscribed. + /// The view. + /// The observable. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static IObservable Collection(INotifyCollectionChanged collection) => + Signal.Create(observer => + { + NotifyCollectionChangedEventHandler handler = (_, args) => observer.OnNext(args); + collection.CollectionChanged += handler; + return Scope.Create((collection, handler), static state => state.collection.CollectionChanged -= state.handler); + }); + + /// Observes the property-change event of a view while subscribed. + /// The view. + /// The observable. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static IObservable Property(INotifyPropertyChanged properties) => + Signal.Create(observer => + { + PropertyChangedEventHandler handler = (_, args) => observer.OnNext(args); + properties.PropertyChanged += handler; + return Scope.Create((properties, handler), static state => state.properties.PropertyChanged -= state.handler); + }); +} diff --git a/src/ReactiveList/Queries/LiveFeed.cs b/src/ReactiveList/Queries/LiveFeed.cs new file mode 100644 index 00000000..176264d1 --- /dev/null +++ b/src/ReactiveList/Queries/LiveFeed.cs @@ -0,0 +1,88 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// The state a query recorded: a source and the filters and projections applied to its items. +/// The source item type. +/// The item type the query exposes. +/// The source. +/// The recorded filters and projections. +/// Whether the query exposes the source items themselves. +/// Whether a filter was recorded. +/// Tells whether two source items are equal. +/// Tells whether two source items are the same entry of a keyed source, or . +/// The keyed source for a plain query over a dictionary, or . +internal sealed record LiveFeed( + IReactiveSource Source, + LiveTryMap Map, + bool Plain, + bool HasFilter, + IEqualityComparer Comparer, + Func? SameRaw, + object? KeyedSource) : ILiveFeed + where TRaw : notnull + where T : notnull +{ + /// Gets the keyed source behind the query when it exposes the source items themselves, or . + public object? Keyed => Plain ? KeyedSource : null; + + /// Gets the test a plain query applies to source items, or when it applies none. + public Func? PlainPredicate => LivePlanner.PlainPredicate(this); + + /// + public ILiveFeed Where(Func predicate) => + this with { Map = LiveMaps.Filter(Map, predicate), HasFilter = true }; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ILiveFeed Select(Func selector) + where TResult : notnull => + new LiveFeed(Source, LiveMaps.Select(Map, selector), false, HasFilter, Comparer, SameRaw, null); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ILiveViewCore CreateView(in LiveShape shape, ISequencer scheduler, TimeSpan throttle) => + LivePlanner.CreateView(this, in shape, scheduler, throttle); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ILiveViewCore CreateProjectedView(in LiveShape shape, Func project, ISequencer scheduler, TimeSpan throttle) + where TOut : notnull => + new LiveProjectedViewCore(LivePlanner.CreateView(this, in shape, scheduler, throttle), project); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ILiveGroupCore CreateGroups( + Func keySelector, + Func elementSelector, + IComparer? order, + ISequencer scheduler, + TimeSpan throttle) + where TKey : notnull + where TElement : notnull => + LivePlanner.CreateGroups(this, keySelector, elementSelector, order, scheduler, throttle); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable Count(Func? predicate) => LivePlanner.Tally(this, predicate, static count => count); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable Any(Func? predicate) => LivePlanner.Tally(this, predicate, static count => count > 0); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable Contains(T item) => + LivePlanner.Tally(this, new LiveEquals(item).Matches, static count => count > 0); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable SelectMany(Func> selector) => + new LiveMergeObservable(Source, new(Map, Comparer, SameRaw), selector); +} diff --git a/src/ReactiveList/Queries/LiveFilterStage.cs b/src/ReactiveList/Queries/LiveFilterStage.cs new file mode 100644 index 00000000..20fff171 --- /dev/null +++ b/src/ReactiveList/Queries/LiveFilterStage.cs @@ -0,0 +1,25 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// A recorded filter applied after the stage it follows. +/// The source item type. +/// The exposed item type. +/// The stage this filter follows. +/// The predicate applied to the exposed item. +internal sealed record LiveFilterStage(LiveTryMap Inner, Func Predicate) + where TRaw : notnull + where T : notnull +{ + /// Applies the stage this filter follows and then the predicate. + /// The source item. + /// Receives the exposed item when the source item passes. + /// when the source item belongs in the query. + internal bool TryMap(TRaw raw, out T value) => Inner(raw, out value) && Predicate(value); +} diff --git a/src/ReactiveList/Queries/LiveFusedGroupCore.cs b/src/ReactiveList/Queries/LiveFusedGroupCore.cs new file mode 100644 index 00000000..4761d96f --- /dev/null +++ b/src/ReactiveList/Queries/LiveFusedGroupCore.cs @@ -0,0 +1,507 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// +/// Groups the output of a fused query. Each change of the output touches only the group it affects, and the group objects of keys that +/// persist stay attached to bindings. Groups appear in the order their keys first occur in the output, as LINQ orders them, and members +/// follow the output's order. For a sharded source the output order is the order its entries were applied, so the groups follow it. +/// The dictionary members can be read from any thread while the source changes. +/// +/// The grouping key type. +/// The item type of the query output. +/// The member type. +internal sealed class LiveFusedGroupCore : ILiveGroupCore + where TKey : notnull + where TIn : notnull + where T : notnull +{ + /// The query output being grouped. + private readonly ILiveViewCore _flat; + + /// Extracts the grouping key. + private readonly Func _keySelector; + + /// Extracts the member from an item of the output. + private readonly Func _elementSelector; + + /// Guards what readers see of the groups. + private readonly Lock _readGate = new(); + + /// The group for each key. + private readonly Dictionary> _slots = []; + + /// The groups in the order they are exposed. + private readonly List> _ordered = []; + + /// The groups in the order they are exposed, as a collection that bindings observe. + private readonly ObservableCollection> _groupCollection = []; + + /// The key of every item of the output, in output order. + private readonly List _keys = []; + + /// The keys already seen while ordering the groups. + private readonly HashSet _seen = []; + + /// The keys in the order of their first occurrence. + private readonly List _desired = []; + + /// Lets one thread at a time change the groups. + private readonly LiveChangeSerializer _serializer; + + /// Non-zero once disposed. + private int _disposed; + + /// Whether a change may have altered the order in which the keys first occur. + private bool _orderDirty; + + /// Initializes a new instance of the class. + /// The query output being grouped. + /// Extracts the grouping key. + /// Extracts the member from an item of the output. + internal LiveFusedGroupCore(ILiveViewCore flat, Func keySelector, Func elementSelector) + { + _flat = flat; + _keySelector = keySelector; + _elementSelector = elementSelector; + Groups = new(_groupCollection); + CollectionChanges = FacadeNotificationHelper.ObserveCollectionChanges(_groupCollection); + _serializer = new(ApplyChange, Regroup, IsStopped); + flat.Storage.CollectionChanged += OnFlatChanged; + _serializer.Rebuild(); + } + + /// + public ReadOnlyObservableCollection> Groups { get; } + + /// + public int Count + { + get + { + lock (_readGate) + { + return _slots.Count; + } + } + } + + /// + public int ResetLimit + { + get => _flat.ResetLimit; + set => _flat.ResetLimit = value; + } + + /// + public IObservable CollectionChanges { get; } + + /// + public IObservable PropertyChanges => _flat.PropertyChanges; + + /// + public bool ContainsKey(TKey key) + { + lock (_readGate) + { + return _slots.ContainsKey(key); + } + } + + /// + public IReadOnlyList GetItems(TKey key) + { + if (TryGetValue(key, out var members)) + { + return members; + } + + throw new KeyNotFoundException("The view has no group with the key."); + } + + /// + public bool TryGetValue(TKey key, out IReadOnlyList value) + { + LiveGroupSlot? slot; + lock (_readGate) + { + _ = _slots.TryGetValue(key, out slot); + } + + if (slot is not null) + { + value = slot.Reader; + return true; + } + + value = []; + return false; + } + + /// + public TKey[] SnapshotKeys() + { + lock (_readGate) + { + var keys = new TKey[_ordered.Count]; + for (var i = 0; i < keys.Length; i++) + { + keys[i] = _ordered[i].Group.Key; + } + + return keys; + } + } + + /// + public IReadOnlyList[] SnapshotValues() + { + lock (_readGate) + { + var values = new IReadOnlyList[_ordered.Count]; + for (var i = 0; i < values.Length; i++) + { + values[i] = _ordered[i].Reader; + } + + return values; + } + } + + /// + public KeyValuePair>[] SnapshotPairs() + { + lock (_readGate) + { + var pairs = new KeyValuePair>[_ordered.Count]; + for (var i = 0; i < pairs.Length; i++) + { + pairs[i] = new(_ordered[i].Group.Key, _ordered[i].Reader); + } + + return pairs; + } + } + + /// + public void Refresh() + { + _flat.Refresh(); + _serializer.Rebuild(); + } + + /// + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + _flat.Storage.CollectionChanged -= OnFlatChanged; + _flat.Dispose(); + } + + /// Rebuilds the groups from the query output, keeping the groups of keys that persist. + internal void Regroup() + { + if (Volatile.Read(ref _disposed) != 0) + { + return; + } + + var items = _flat.Storage.CopySnapshot(); + var buckets = new Dictionary>(); + _keys.Clear(); + for (var i = 0; i < items.Length; i++) + { + var key = _keySelector(items[i]); + _keys.Add(key); + DictionaryCompat.GetOrAdd(buckets, key).Add(_elementSelector(items[i])); + } + + for (var i = _ordered.Count - 1; i >= 0; i--) + { + if (!buckets.ContainsKey(_ordered[i].Group.Key)) + { + RemoveGroup(_ordered[i]); + } + } + + foreach (var pair in buckets) + { + if (_slots.TryGetValue(pair.Key, out var slot)) + { + slot.Members.ReconcileTo(pair.Value); + continue; + } + + BatchObservableCollection members = new(synchronizeReads: true); + for (var i = 0; i < pair.Value.Count; i++) + { + members.Add(pair.Value[i]); + } + + AddGroup(pair.Key, members); + } + + ReorderGroups(); + } + + /// Passes one change of the query output to the serializer. + /// The output collection. + /// The change. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void OnFlatChanged(object? sender, NotifyCollectionChangedEventArgs e) => _serializer.Handle(e); + + /// Tells whether the view was disposed. + /// when it was. + private bool IsStopped() => Volatile.Read(ref _disposed) != 0; + + /// Applies a change to the groups and puts them back in order. + /// The change. + /// when the change cannot be applied exactly, so the groups must be rebuilt. + private bool ApplyChange(NotifyCollectionChangedEventArgs e) + { + if (!TryApply(e)) + { + return false; + } + + if (_orderDirty) + { + ReorderGroups(); + } + + return true; + } + + /// Applies a change of one position or a few positions to the groups it affects. + /// The change. + /// when the change names positions the groups do not hold, so they must be rebuilt. + private bool TryApply(NotifyCollectionChangedEventArgs e) + { + if (!LiveGroupChanges.Fits(e, _keys.Count)) + { + return false; + } + + // Fits has checked that the change carries the items and positions each branch reads. + switch (e.Action) + { + case NotifyCollectionChangedAction.Add: + { + ApplyAdd(e.NewItems!, e.NewStartingIndex); + break; + } + + case NotifyCollectionChangedAction.Remove: + { + ApplyRemove(e.OldItems!.Count, e.OldStartingIndex); + break; + } + + case NotifyCollectionChangedAction.Replace: + { + Replace(e.NewStartingIndex, (TIn)e.NewItems![0]!); + break; + } + + default: + { + var element = RemoveAt(e.OldStartingIndex, out var key); + Insert(e.NewStartingIndex, key, element); + break; + } + } + + return true; + } + + /// Applies items that were added to the output. + /// The new items. + /// The output position of the first one. + private void ApplyAdd(IList added, int start) + { + for (var i = 0; i < added.Count; i++) + { + var item = (TIn)added[i]!; + Insert(start + i, _keySelector(item), _elementSelector(item)); + } + } + + /// Applies items that were removed from the output. + /// The number of items removed. + /// The output position of the first one. + private void ApplyRemove(int count, int start) + { + for (var i = count - 1; i >= 0; i--) + { + _ = RemoveAt(start + i, out _); + } + } + + /// Counts the items before an index that have a key. + /// The key. + /// The index. + /// The number of items before that have the key. + private int CountBefore(TKey key, int index) + { + var count = 0; + for (var i = 0; i < index; i++) + { + if (EqualityComparer.Default.Equals(_keys[i], key)) + { + count++; + } + } + + return count; + } + + /// Adds a member for an item at an output position. + /// The output position. + /// The key of the item. + /// The member. + private void Insert(int index, TKey key, T element) + { + _keys.Insert(index, key); + var atEnd = index == _keys.Count - 1; + if (_slots.TryGetValue(key, out var slot)) + { + var position = atEnd ? slot.Members.Count : CountBefore(key, index); + slot.Members.Insert(position, element); + + // Becoming the first member of a group moves the first occurrence of its key. + _orderDirty |= position == 0; + return; + } + + AddGroup(key, element); + _orderDirty |= !atEnd; + } + + /// Removes the member of the item at an output position. + /// The output position. + /// Receives the key of the item. + /// The member that was removed. + private T RemoveAt(int index, out TKey key) + { + key = _keys[index]; + _keys.RemoveAt(index); + var slot = _slots[key]; + var position = index == _keys.Count ? slot.Members.Count - 1 : CountBefore(key, index); + var element = slot.Members[position]; + if (slot.Members.Count == 1) + { + RemoveGroup(slot); + return element; + } + + slot.Members.RemoveAt(position); + + // Losing the first member of a group moves the first occurrence of its key. + _orderDirty |= position == 0; + return element; + } + + /// Replaces the item at an output position. + /// The output position. + /// The new item. + private void Replace(int index, TIn item) + { + var key = _keySelector(item); + var element = _elementSelector(item); + var oldKey = _keys[index]; + if (EqualityComparer.Default.Equals(oldKey, key)) + { + _slots[oldKey].Members[CountBefore(oldKey, index)] = element; + return; + } + + _ = RemoveAt(index, out _); + Insert(index, key, element); + } + + /// Creates a group with one member and exposes it last. + /// The key. + /// The first member. + private void AddGroup(TKey key, T element) + { + BatchObservableCollection members = new(synchronizeReads: true) { element }; + AddGroup(key, members); + } + + /// Exposes a group last. + /// The key. + /// The members. + private void AddGroup(TKey key, BatchObservableCollection members) + { + LiveGroupSlot slot = new(members, new(key, members), new(members)); + lock (_readGate) + { + _slots.Add(key, slot); + _ordered.Add(slot); + } + + _groupCollection.Add(slot.Group); + } + + /// Stops exposing a group. + /// The group. + private void RemoveGroup(LiveGroupSlot slot) + { + lock (_readGate) + { + _ = _slots.Remove(slot.Group.Key); + _ = _ordered.Remove(slot); + } + + _ = _groupCollection.Remove(slot.Group); + } + + /// Moves the groups into the order in which their keys first occur in the output. + private void ReorderGroups() + { + _orderDirty = false; + _seen.Clear(); + _desired.Clear(); + for (var i = 0; i < _keys.Count; i++) + { + if (_seen.Add(_keys[i])) + { + _desired.Add(_keys[i]); + } + } + + for (var i = 0; i < _desired.Count && i < _ordered.Count; i++) + { + if (EqualityComparer.Default.Equals(_ordered[i].Group.Key, _desired[i])) + { + continue; + } + + var from = i + 1; + while (from < _ordered.Count && !EqualityComparer.Default.Equals(_ordered[from].Group.Key, _desired[i])) + { + from++; + } + + // Every key of the output has a group, and the groups before this one already hold the keys that occur earlier, so the search succeeds. + var slot = _ordered[from]; + lock (_readGate) + { + _ordered.RemoveAt(from); + _ordered.Insert(i, slot); + } + + _groupCollection.Move(from, i); + } + } +} diff --git a/src/ReactiveList/Queries/LiveGroupChanges.cs b/src/ReactiveList/Queries/LiveGroupChanges.cs new file mode 100644 index 00000000..91439a82 --- /dev/null +++ b/src/ReactiveList/Queries/LiveGroupChanges.cs @@ -0,0 +1,27 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Checks that a change of a query output names positions that grouped members can apply exactly. +internal static class LiveGroupChanges +{ + /// Tells whether a change names positions and items that the groups can apply exactly. + /// The change. + /// The number of items of the output the groups hold. + /// when the change is not an add, remove, replace or move of held positions. + internal static bool Fits(NotifyCollectionChangedEventArgs e, int count) => + e.Action switch + { + NotifyCollectionChangedAction.Add => e.NewItems is not null && e.NewStartingIndex >= 0 && e.NewStartingIndex <= count, + NotifyCollectionChangedAction.Remove => e.OldItems is { } removed && e.OldStartingIndex >= 0 && e.OldStartingIndex + removed.Count <= count, + NotifyCollectionChangedAction.Replace => e.NewItems is { Count: 1 } && (uint)e.NewStartingIndex < (uint)count, + NotifyCollectionChangedAction.Move => (uint)e.OldStartingIndex < (uint)count && (uint)e.NewStartingIndex < (uint)count, + _ => false + }; +} diff --git a/src/ReactiveList/Queries/LiveGroupMembers.cs b/src/ReactiveList/Queries/LiveGroupMembers.cs new file mode 100644 index 00000000..043302bf --- /dev/null +++ b/src/ReactiveList/Queries/LiveGroupMembers.cs @@ -0,0 +1,33 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// A read-only list of the members of one group that can be read from any thread while the group changes. +/// The member type. +/// The group's storage, which must have been created to synchronize reads. +internal sealed class LiveGroupMembers(BatchObservableCollection members) : IReadOnlyList +{ + /// + public int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => members.ReadCount(); + } + + /// + public T this[int index] => members.ReadAt(index); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator GetEnumerator() => ((IEnumerable)members.CopySnapshot()).GetEnumerator(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} diff --git a/src/ReactiveList/Queries/LiveGroupPlan.cs b/src/ReactiveList/Queries/LiveGroupPlan.cs new file mode 100644 index 00000000..aee0ef65 --- /dev/null +++ b/src/ReactiveList/Queries/LiveGroupPlan.cs @@ -0,0 +1,32 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// A grouping of the items a query exposes by a key, with a member taken from each item. +/// The grouping key type. +/// The item type the query exposes. +/// The member type. +/// The recorded filters and projections. +/// Takes the grouping key from an item. +/// Takes the member from an item. +/// The ordering of the members, or for source order. +internal sealed record LiveGroupPlan( + ILiveFeed Feed, + Func KeySelector, + Func ElementSelector, + IComparer? Order) : ILiveGroupPlan + where TKey : notnull + where TIn : notnull + where T : notnull +{ + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ILiveGroupCore Create(ISequencer scheduler, TimeSpan throttle) => + Feed.CreateGroups(KeySelector, ElementSelector, Order, scheduler, throttle); +} diff --git a/src/ReactiveList/Queries/LiveGroupSlot.cs b/src/ReactiveList/Queries/LiveGroupSlot.cs new file mode 100644 index 00000000..f9106254 --- /dev/null +++ b/src/ReactiveList/Queries/LiveGroupSlot.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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// One group of a fused grouped view. +/// The grouping key type. +/// The member type. +/// The mutable members. +/// The public group wrapper. +/// The members as a list that can be read from any thread. +internal sealed record LiveGroupSlot(BatchObservableCollection Members, ReactiveGroup Group, LiveGroupMembers Reader) + where TKey : notnull; diff --git a/src/ReactiveList/Queries/LiveGroupView.cs b/src/ReactiveList/Queries/LiveGroupView.cs new file mode 100644 index 00000000..fe24d843 --- /dev/null +++ b/src/ReactiveList/Queries/LiveGroupView.cs @@ -0,0 +1,127 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// A read-only, observable view of the groups a live query forms. +/// The type of the grouping key. +/// The type of elements in the groups. +[System.Diagnostics.DebuggerDisplay("LiveGroupView: {Count}")] +public sealed class LiveGroupView : + IReadOnlyDictionary>, + INotifyCollectionChanged, + INotifyPropertyChanged, + IReactiveView, ReactiveGroup> + where TKey : notnull + where T : notnull +{ + /// Holds the synchronization gate and lazy notification relays for this facade. + private readonly FacadeRelayState _relays = new(); + + /// The engine that owns the groups and the source subscription. + private readonly ILiveGroupCore _core; + + /// Initializes a new instance of the class. + /// The engine that owns the groups and the source subscription. + internal LiveGroupView(ILiveGroupCore core) => _core = core; + + /// + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add => FacadeNotificationHelper.AddCollectionChanged(_relays, this, _core.CollectionChanges, value); + + remove => FacadeNotificationHelper.RemoveCollectionChanged(_relays, value); + } + + /// + public event PropertyChangedEventHandler? PropertyChanged + { + add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _core.PropertyChanges, value); + + remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value); + } + + /// Gets or sets the size above which one applied batch of the group members raises a single reset instead of one notification per item. + /// The value is negative. + /// The default is , so every changed item raises its own notification. + public int BatchResetLimit + { + get => _core.ResetLimit; + + set => _core.ResetLimit = ReactiveViewHelpers.CheckedResetLimit(value); + } + + /// Gets the number of groups. + public int Count => _core.Count; + + /// Gets the collection of groups for UI binding. + public ReadOnlyObservableCollection> Groups => _core.Groups; + + /// Gets the collection of groups for UI binding. This is an alias for . + public ReadOnlyObservableCollection> Items => Groups; + + /// Gets the keys of all groups. + public IEnumerable Keys => _core.SnapshotKeys(); + + /// Gets the member lists of all groups. + public IEnumerable> Values => _core.SnapshotValues(); + + /// Gets the items in the specified group. + /// The group key. + /// The items in the group. + public IReadOnlyList this[TKey key] => _core.GetItems(key); + + /// Determines whether the view contains a group with the specified key. + /// The key to locate. + /// when the view contains a group with the key. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool ContainsKey(TKey key) => _core.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 was found, or an empty list. + /// when the view contains a group with the key. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool TryGetValue(TKey key, out IReadOnlyList value) => _core.TryGetValue(key, out value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator>> GetEnumerator() => + ((IEnumerable>>)_core.SnapshotPairs()).GetEnumerator(); + + /// Forces a rebuild of the groups from the source. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Refresh() => _core.Refresh(); + + /// Assigns the groups collection to a property using the specified setter action. + /// An action that sets a property to the read-only observable collection of groups. + /// The current instance, to enable method chaining. + /// Thrown if is null. + public LiveGroupView ToProperty(Action>> propertySetter) + { + _ = ReactiveViewHelpers.BindToProperty(this, Groups, propertySetter); + return this; + } + + /// Returns the current instance and provides the read-only observable collection of groups. + /// When this method returns, contains the read-only observable collection of groups. + /// The current instance. + public LiveGroupView ToProperty(out ReadOnlyObservableCollection> collection) + { + collection = Groups; + return this; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _core.Dispose(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} diff --git a/src/ReactiveList/Queries/LiveIdentityComparer.cs b/src/ReactiveList/Queries/LiveIdentityComparer.cs new file mode 100644 index 00000000..532eafff --- /dev/null +++ b/src/ReactiveList/Queries/LiveIdentityComparer.cs @@ -0,0 +1,24 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Treats two source items as the same occurrence: by reference for reference types, and by value for value types. +/// The source item type. +/// Compares value types. +internal sealed class LiveIdentityComparer(IEqualityComparer valueComparer) : IEqualityComparer + where T : notnull +{ + /// + public bool Equals(T? x, T? y) => + typeof(T).IsValueType ? valueComparer.Equals(x!, y!) : ReferenceEquals(x, y); + + /// + public int GetHashCode(T obj) => + typeof(T).IsValueType ? valueComparer.GetHashCode(obj) : RuntimeHelpers.GetHashCode(obj); +} diff --git a/src/ReactiveList/Queries/LiveKeyComparer.cs b/src/ReactiveList/Queries/LiveKeyComparer.cs new file mode 100644 index 00000000..50fbd062 --- /dev/null +++ b/src/ReactiveList/Queries/LiveKeyComparer.cs @@ -0,0 +1,44 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Orders items by a key taken from each item. +/// The item type. +/// The sort key type. +internal sealed class LiveKeyComparer : IComparer + where T : notnull +{ + /// Takes the sort key from an item. + private readonly Func _keySelector; + + /// Compares two sort keys. + private readonly IComparer _keyComparer; + + /// Whether larger keys come first. + private readonly bool _descending; + + /// Initializes a new instance of the class. + /// Takes the sort key from an item. + /// Compares two sort keys, or for the default comparer. + /// Whether larger keys come first. + internal LiveKeyComparer(Func keySelector, IComparer? keyComparer, bool descending) + { + _keySelector = keySelector; + _keyComparer = keyComparer ?? Comparer.Default; + _descending = descending; + } + + /// + public int Compare(T? x, T? y) + { + var left = _keySelector(x!); + var right = _keySelector(y!); + return _descending ? _keyComparer.Compare(right, left) : _keyComparer.Compare(left, right); + } +} diff --git a/src/ReactiveList/Queries/LiveKeyReader.cs b/src/ReactiveList/Queries/LiveKeyReader.cs new file mode 100644 index 00000000..f8f0ef33 --- /dev/null +++ b/src/ReactiveList/Queries/LiveKeyReader.cs @@ -0,0 +1,29 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Reads the value stored under one key of a dictionary. +/// The key type. +/// The value type. +/// The dictionary. +/// The key. +/// A filter the entry must pass, or . +internal sealed record LiveKeyReader( + IQuaternaryDictionary Dictionary, + TKey Key, + Func, bool>? Accept) + where TKey : notnull +{ + /// Reads the value with a keyed lookup. + /// The value, or an absent marker when the key is missing or the entry fails the filter. + internal LiveValue Read() => + Dictionary.TryGetValue(Key, out var value) && (Accept is null || Accept(new(Key, value))) + ? new(true, value) + : new(false, default); +} diff --git a/src/ReactiveList/Queries/LiveKeyValueComparer.cs b/src/ReactiveList/Queries/LiveKeyValueComparer.cs new file mode 100644 index 00000000..43730721 --- /dev/null +++ b/src/ReactiveList/Queries/LiveKeyValueComparer.cs @@ -0,0 +1,27 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Compares dictionary entries by key and value without reflection. +/// The key type. +/// The value type. +internal sealed class LiveKeyValueComparer : IEqualityComparer> + where TKey : notnull +{ + /// Gets the shared instance. + internal static LiveKeyValueComparer Instance { get; } = new(); + + /// + public bool Equals(KeyValuePair x, KeyValuePair y) => + EqualityComparer.Default.Equals(x.Key, y.Key) && EqualityComparer.Default.Equals(x.Value, y.Value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int GetHashCode(KeyValuePair obj) => EqualityComparer.Default.GetHashCode(obj.Key); +} diff --git a/src/ReactiveList/Queries/LiveListEngine.cs b/src/ReactiveList/Queries/LiveListEngine.cs new file mode 100644 index 00000000..f14d9f01 --- /dev/null +++ b/src/ReactiveList/Queries/LiveListEngine.cs @@ -0,0 +1,255 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// +/// Maintains the fused view of a query over a versioned, ordered source. One pump subscribes to the source and keeps an ordered mirror; the +/// entries of that mirror feed one sequence that applies the filters, projections, ordering and window. +/// +/// The source item type. +/// The item type the query exposes. +internal sealed class LiveListEngine : IViewMirrorSink, ILiveViewCore + where TRaw : notnull + where T : notnull +{ + /// Drains retained source notifications into this engine. + private readonly ViewMirrorPump _pump; + + /// Creates and compares entries. + private readonly LiveBinding _binding; + + /// One entry per source item, aligned with the pump's mirror. + private readonly List> _entries = []; + + /// The included entries in output order and the collection that exposes them. + private readonly LiveSequence _sequence; + + /// Follows observable windows, or . + private readonly LiveWindowDriver? _driver; + + /// Whether the query orders its items. + private readonly bool _ordered; + + /// Non-zero once disposed. + private int _disposed; + + /// Initializes a new instance of the class. + /// The source to project. + /// Creates and compares entries. + /// The ordering and window. + internal LiveListEngine(IReactiveSource source, LiveBinding binding, in LiveShape shape) + { + _binding = binding; + _ordered = shape.Order is not null; + _pump = new(source); + var skip = shape.Window.Skip; + var take = shape.Window.Take; + if (shape.Window.HasSources) + { + _driver = new(shape.Window, _pump.RequestDrain); + _driver.Start(); + _ = _driver.TryTakePending(out _, out _); + _driver.Current(out skip, out take); + } + + _sequence = new(shape.Order, skip, take, _entries); + CollectionChanges = FacadeNotificationHelper.ObserveCollectionChanges(_sequence.Target); + MirrorReset(); + } + + /// + public ReadOnlyObservableCollection Items => _sequence.Items; + + /// + public BatchObservableCollection Storage => _sequence.Target; + + /// + public int ResetLimit + { + get => _sequence.Target.ResetLimit; + set => _sequence.Target.ResetLimit = value; + } + + /// + public IObservable CollectionChanges { get; } + + /// + public IObservable PropertyChanges => _pump.PropertyChanges; + + /// Gets the retained notifications and ordered source mirror. + private ViewChangeBuffer Buffer => _pump.Buffer; + + /// + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + _driver?.Dispose(); + _pump.Dispose(); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Refresh() => _pump.Refresh(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void BatchStarted(int size) => _sequence.BeginBatch(size); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void BatchEnded() => _sequence.EndBatch(); + + /// + public void ItemsInserted(int index, int count) + { + if (count > BatchObservableCollection.ResetThreshold) + { + MirrorReset(); + return; + } + + var items = Buffer.Items; + for (var i = index; i < index + count; i++) + { + _entries.Insert(i, _binding.CreateEntry(items[i])); + } + + for (var i = index; i < index + count; i++) + { + var entry = _entries[i]; + if (entry.Evaluate()) + { + _sequence.Insert(entry, i); + } + } + } + + /// + public void ItemRemoved(int index, TRaw item) + { + var entry = _entries[index]; + if (entry.Included) + { + _sequence.Remove(entry, index); + } + + _entries.RemoveAt(index); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ItemReplaced(int index, TRaw previous, TRaw current) => + Reevaluate(index, current, ItemComparison.SameItem(previous, current)); + + /// + public void ItemMoved(int oldIndex, int newIndex, TRaw item) + { + var entry = _entries[oldIndex]; + if (!entry.Included) + { + MoveEntry(oldIndex, newIndex, entry); + return; + } + + if (_ordered) + { + _sequence.Remove(entry, oldIndex); + MoveEntry(oldIndex, newIndex, entry); + _sequence.Insert(entry, newIndex); + return; + } + + var oldPosition = _sequence.IncludedBefore(oldIndex); + MoveEntry(oldIndex, newIndex, entry); + var newPosition = _sequence.IncludedBefore(newIndex); + if (newPosition != oldPosition) + { + _sequence.MoveItem(oldPosition, newPosition); + } + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ItemRefreshed(int index, TRaw item) => Reevaluate(index, item, revalidate: true); + + /// + public void MirrorCleared() + { + _sequence.Clear(); + _entries.Clear(); + } + + /// + public void MirrorReset() + { + var items = Buffer.Items; + _entries.Clear(); + for (var i = 0; i < items.Count; i++) + { + _entries.Add(_binding.CreateEntry(items[i])); + } + + _sequence.Rebuild(_entries); + } + + /// Starts observing the source. + /// The coalescing window. + /// The scheduler that applies changes. + internal void Start(TimeSpan throttle, ISequencer scheduler) + { + _pump.Start(this, throttle, scheduler, ApplyQueued, HasQueued, coverSubscriptionGap: true); + + // A window value that arrived before the pump could schedule a drain would wait for the next source change. + LiveDrainRequests.RequestIf(HasQueued(), _pump.RequestDrain); + } + + /// Applies a queued window change. + /// when the window changed. + private bool ApplyQueued() + { + if (_driver is null || !_driver.TryTakePending(out var skip, out var take)) + { + return false; + } + + _sequence.SetWindow(skip, take); + return true; + } + + /// Gets whether a window change is queued. + /// when a change is waiting. + private bool HasQueued() => _driver?.HasPending == true; + + /// Evaluates a source item again and swaps it into the sequence at a mirror position. + /// The mirror index. + /// The source item now at the index. + /// Whether the old entry's sort position cannot be trusted. + private void Reevaluate(int index, TRaw current, bool revalidate) + { + var old = _entries[index]; + var replacement = _binding.CreateEntry(current); + var passes = replacement.Evaluate(); + _sequence.Replace(old, replacement, index, revalidate, passes); + _entries[index] = replacement; + } + + /// Moves an entry within the mirror. + /// The old mirror index. + /// The new mirror index. + /// The entry. + private void MoveEntry(int oldIndex, int newIndex, LiveEntry entry) + { + _entries.RemoveAt(oldIndex); + _entries.Insert(newIndex, entry); + } +} diff --git a/src/ReactiveList/Queries/LiveMaps.cs b/src/ReactiveList/Queries/LiveMaps.cs new file mode 100644 index 00000000..479e0e44 --- /dev/null +++ b/src/ReactiveList/Queries/LiveMaps.cs @@ -0,0 +1,69 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Builds the stage delegates a query records. +internal static class LiveMaps +{ + /// Passes a source item through unchanged. + /// The source and exposed item type. + /// The source item. + /// Receives the item. + /// Always . + internal static bool Identity(T raw, out T value) + where T : notnull + { + value = raw; + return true; + } + + /// Returns an item unchanged, as the member of a group that holds the items themselves. + /// The item type. + /// The item. + /// The same item that was passed in. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static T Same(T item) => item; + + /// Tells whether two dictionary entries have the same key. + /// The key type. + /// The value type. + /// The first entry. + /// The second entry. + /// when the keys are equal. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool SameKey(KeyValuePair left, KeyValuePair right) + where TKey : notnull => + EqualityComparer.Default.Equals(left.Key, right.Key); + + /// Appends a filter to a stage. + /// The source item type. + /// The exposed item type. + /// The stage the filter follows. + /// The predicate. + /// The extended stage. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static LiveTryMap Filter(LiveTryMap inner, Func predicate) + where TRaw : notnull + where T : notnull => + new LiveFilterStage(inner, predicate).TryMap; + + /// Appends a projection to a stage. + /// The source item type. + /// The item type the stage exposes. + /// The projected item type. + /// The stage the projection follows. + /// The projection. + /// The extended stage. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static LiveTryMap Select(LiveTryMap inner, Func selector) + where TRaw : notnull + where TMid : notnull + where T : notnull => + new LiveSelectStage(inner, selector).TryMap; +} diff --git a/src/ReactiveList/Queries/LiveMatcher.cs b/src/ReactiveList/Queries/LiveMatcher.cs new file mode 100644 index 00000000..c4d99aae --- /dev/null +++ b/src/ReactiveList/Queries/LiveMatcher.cs @@ -0,0 +1,37 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Tests source items against a query and an optional extra condition. +/// The source item type. +/// The item type the query exposes. +internal sealed class LiveMatcher + where TRaw : notnull + where T : notnull +{ + /// The recorded filters and projections. + private readonly LiveTryMap _map; + + /// The extra condition on the exposed item, or . + private readonly Func? _extra; + + /// Initializes a new instance of the class. + /// The recorded filters and projections. + /// The extra condition on the exposed item, or . + internal LiveMatcher(LiveTryMap map, Func? extra) + { + _map = map; + _extra = extra; + } + + /// Tests a source item. + /// The source item. + /// when the item belongs in the query and meets the extra condition. + internal bool Matches(TRaw raw) => _map(raw, out var value) && (_extra is null || _extra(value)); +} diff --git a/src/ReactiveList/Queries/LiveMergeObservable.cs b/src/ReactiveList/Queries/LiveMergeObservable.cs new file mode 100644 index 00000000..bfa7f6c4 --- /dev/null +++ b/src/ReactiveList/Queries/LiveMergeObservable.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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// A cold observable that merges one observable per item a query includes. +/// The source item type. +/// The item type the query exposes. +/// The merged value type. +internal sealed class LiveMergeObservable : IObservable + where TRaw : notnull + where T : notnull +{ + /// The source. + private readonly IReactiveSource _source; + + /// Creates and compares entries. + private readonly LiveBinding _binding; + + /// Creates the observable of an item. + private readonly Func> _selector; + + /// Initializes a new instance of the class. + /// The source. + /// Creates and compares entries. + /// Creates the observable of an item. + internal LiveMergeObservable(IReactiveSource source, LiveBinding binding, Func> selector) + { + _source = source; + _binding = binding; + _selector = selector; + } + + /// + public IDisposable Subscribe(IObserver observer) + { + ArgumentExceptionHelper.ThrowIfNull(observer); + + var subscription = new LiveMergeSubscription(observer, _source, _binding, _selector); + subscription.Start(_source); + return subscription; + } +} diff --git a/src/ReactiveList/Queries/LiveMergeSubscription.cs b/src/ReactiveList/Queries/LiveMergeSubscription.cs new file mode 100644 index 00000000..dbef9f07 --- /dev/null +++ b/src/ReactiveList/Queries/LiveMergeSubscription.cs @@ -0,0 +1,351 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// +/// Subscribes to one observable per item a query includes and merges their values into one observer. An item's observable is subscribed +/// when the item enters the query and unsubscribed exactly once when it leaves, is replaced, or the subscription ends. +/// +/// The source item type. +/// The item type the query exposes. +/// The merged value type. +internal sealed class LiveMergeSubscription : IDisposable + where TRaw : notnull + where T : notnull +{ + /// Creates and compares entries. + private readonly LiveBinding _binding; + + /// Creates the observable of an item. + private readonly Func> _selector; + + /// Serializes the values of every item for the observer. + private readonly SerializedObserver _output; + + /// Forwards an item's value. + private readonly Action _onNext; + + /// Ends the merge when an item's observable fails. + private readonly Action _onError; + + /// Observes the source and holds the included entries. + private readonly StreamProjection> _projection; + + /// The included entries in the order the projection holds them. + private readonly List> _mirror = []; + + /// Lets disposal wait for a change running on another thread and stops later changes. + private readonly DisposalGate _gate = new(); + + /// Non-zero while a change or a disposal owns the mirror. + private int _mirrorOwner; + + /// Non-zero once disposed. + private int _disposed; + + /// Initializes a new instance of the class. + /// The observer that receives the merged values. + /// The source. + /// Creates and compares entries. + /// Creates the observable of an item. + internal LiveMergeSubscription( + IObserver observer, + IReactiveSource source, + LiveBinding binding, + Func> selector) + { + _binding = binding; + _selector = selector; + _output = new(observer); + _onNext = _output.OnNext; + _onError = OnInnerError; + var rules = ViewSourceRules.Create( + source, + binding.CreateEntry, + LiveBinding.Matches, + binding.SameRaw is null ? null : binding.SameEntry, + previousIsReliable: binding.SameRaw is null); + _projection = new(source, binding.CreateEntry, rules, "Count"); + } + + /// + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + _projection.Target.CollectionChanged -= OnTargetChanged; + _projection.Dispose(); + _output.Stop(); + _gate.Close(); + SweepMirror(); + } + + /// Starts observing the source. + /// The source. + internal void Start(IReactiveSource source) + { + if (source.IsDisposed) + { + OnSourceCompleted(); + return; + } + + _projection.Target.CollectionChanged += OnTargetChanged; + try + { + _projection.StartFromSource(TimeSpan.Zero, ReactiveListScheduler.Immediate, _onError, OnSourceCompleted); + } + catch (ObjectDisposedException) when (source.IsDisposed) + { + OnSourceCompleted(); + } + } + + /// Mirrors one change of the projection's entries into the subscriptions. + /// The projection's collection. + /// The change. + internal void OnTargetChanged(object? sender, NotifyCollectionChangedEventArgs e) + { + // Disposal closes the gate and waits for a change running on another thread, so no subscription is made or released after it returns. + if (!_gate.TryEnter()) + { + return; + } + + try + { + ApplyOwnedChange(e); + } + finally + { + _gate.Exit(); + } + } + + /// Unsubscribes from the observable of an entry, once. + /// The entry. + private static void Detach(LiveEntry entry) + { + var subscription = entry.Subscription; + entry.Subscription = null; + subscription?.Dispose(); + } + + /// Completes the merged sequence and releases every item subscription because the source ended. + private void OnSourceCompleted() + { + // The serialized output ignores a completion once the merge was disposed, so no disposal check is needed here. + _output.OnCompleted(); + Dispose(); + } + + /// Ends the merge because an item's observable failed. + /// The failure. + private void OnInnerError(Exception error) + { + _output.OnError(error); + Dispose(); + } + + /// Subscribes to the observable of an entry. + /// The entry. + private void Attach(LiveEntry entry) + { + if (Volatile.Read(ref _disposed) != 0) + { + return; + } + + try + { + var subscription = _selector(entry.Value).Subscribe(_onNext, _onError, static () => { }); + if (Volatile.Read(ref _disposed) != 0) + { + subscription.Dispose(); + return; + } + + entry.Subscription = subscription; + } + catch (Exception ex) + { + OnInnerError(ex); + } + } + + /// + /// Unsubscribes from every entry of the mirror unless a change is being applied to it, in which case that change does so when it ends. + /// Whoever holds the mirror is the only one that touches it, so a disposal on another thread cannot race a drain. + /// + private void SweepMirror() + { + if (Interlocked.CompareExchange(ref _mirrorOwner, 1, 0) != 0) + { + return; + } + + try + { + for (var i = 0; i < _mirror.Count; i++) + { + Detach(_mirror[i]); + } + + _mirror.Clear(); + } + finally + { + _ = Interlocked.Exchange(ref _mirrorOwner, 0); + } + } + + /// Applies a change while owning the mirror, and releases the subscriptions if the merge was disposed meanwhile. + /// The change. + private void ApplyOwnedChange(NotifyCollectionChangedEventArgs e) + { + if (Interlocked.CompareExchange(ref _mirrorOwner, 1, 0) != 0) + { + // A disposal is sweeping the mirror. + return; + } + + try + { + ApplyChange(e); + } + finally + { + // The full fence orders the release before the disposal check, which pairs with the disposer's claim after it sets the flag. + _ = Interlocked.Exchange(ref _mirrorOwner, 0); + } + + if (Volatile.Read(ref _disposed) != 0) + { + SweepMirror(); + } + } + + /// Applies one change of the projection's entries to the mirror and the subscriptions. + /// The change. + private void ApplyChange(NotifyCollectionChangedEventArgs e) + { + if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems is not null) + { + AddEntries(e.NewItems, e.NewStartingIndex); + } + else if (e.Action == NotifyCollectionChangedAction.Remove && e.OldItems is not null) + { + RemoveEntries(e.OldItems.Count, e.OldStartingIndex); + } + else if (e.Action == NotifyCollectionChangedAction.Replace && e.NewItems is not null) + { + Replace(e.NewStartingIndex, (LiveEntry)e.NewItems[0]!); + } + else + { + Reset(); + } + } + + /// Subscribes to entries that entered the projection. + /// The new entries. + /// The index of the first one. + private void AddEntries(IList added, int startIndex) + { + for (var i = 0; i < added.Count; i++) + { + var entry = (LiveEntry)added[i]!; + entry.Resolve(); + _mirror.Insert(startIndex + i, entry); + Attach(entry); + } + } + + /// Unsubscribes from entries that left the projection. + /// The number of entries. + /// The index of the first one. + private void RemoveEntries(int count, int startIndex) + { + for (var i = count - 1; i >= 0; i--) + { + var index = startIndex + i; + var removed = _mirror[index]; + _mirror.RemoveAt(index); + Detach(removed); + } + } + + /// Swaps the entry at an index, keeping the subscription when it is the same source item. + /// The index. + /// The new entry. + private void Replace(int index, LiveEntry replacement) + { + replacement.Resolve(); + var old = _mirror[index]; + _mirror[index] = replacement; + if (_binding.Identity.Equals(old.Raw, replacement.Raw) && old.Subscription is not null) + { + replacement.Subscription = old.Subscription; + old.Subscription = null; + return; + } + + Detach(old); + Attach(replacement); + } + + /// Matches the subscriptions to a rebuilt projection, keeping those of items that are still present. + private void Reset() + { + var previous = new Dictionary>>(_binding.Identity); + for (var i = 0; i < _mirror.Count; i++) + { + var old = _mirror[i]; + if (previous.TryGetValue(old.Raw, out var queue)) + { + queue.Enqueue(old); + continue; + } + + queue = new(); + queue.Enqueue(old); + previous.Add(old.Raw, queue); + } + + _mirror.Clear(); + var target = _projection.Target; + for (var i = 0; i < target.Count && Volatile.Read(ref _disposed) == 0; i++) + { + var entry = target[i]; + entry.Resolve(); + _mirror.Add(entry); + if (previous.TryGetValue(entry.Raw, out var queue) && queue.Count > 0) + { + var old = queue.Dequeue(); + entry.Subscription = old.Subscription; + old.Subscription = null; + } + else + { + Attach(entry); + } + } + + foreach (var queue in previous.Values) + { + while (queue.Count > 0) + { + Detach(queue.Dequeue()); + } + } + } +} diff --git a/src/ReactiveList/Queries/LiveOrderedProjectionFeed.cs b/src/ReactiveList/Queries/LiveOrderedProjectionFeed.cs new file mode 100644 index 00000000..cb490fb3 --- /dev/null +++ b/src/ReactiveList/Queries/LiveOrderedProjectionFeed.cs @@ -0,0 +1,90 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// +/// A query that projects the items of an ordered query. The order is decided on the items before the projection, so the view stays on the +/// same fused view and source subscription as the query it extends. Tests and projections added afterwards run on the projected item, +/// which runs the projection again for each test. +/// +/// The item type before the projection. +/// The item type after the projection. +/// The recorded filters and projections before the projection. +/// The ordering of the items before the projection. +/// Projects an item. +internal sealed record LiveOrderedProjectionFeed(ILiveFeed Inner, IComparer Order, Func Project) : ILiveFeed + where T : notnull + where TProjected : notnull +{ + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ILiveFeed Where(Func predicate) => + this with { Inner = Inner.Where(new LiveProjectedPredicate(Project, predicate).Matches) }; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ILiveFeed Select(Func selector) + where TResult : notnull => + new LiveOrderedProjectionFeed(Inner, Order, new LiveComposedSelector(Project, selector).Select); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ILiveViewCore CreateView(in LiveShape shape, ISequencer scheduler, TimeSpan throttle) => + Inner.CreateProjectedView(new(Combine(shape.Order), shape.Window), Project, scheduler, throttle); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ILiveViewCore CreateProjectedView(in LiveShape shape, Func project, ISequencer scheduler, TimeSpan throttle) + where TOut : notnull => + Inner.CreateProjectedView( + new(Combine(shape.Order), shape.Window), + new LiveComposedSelector(Project, project).Select, + scheduler, + throttle); + + /// + public ILiveGroupCore CreateGroups( + Func keySelector, + Func elementSelector, + IComparer? order, + ISequencer scheduler, + TimeSpan throttle) + where TKey : notnull + where TElement : notnull + { + LiveShape shape = new(order, LiveWindow.None); + return new LiveFusedGroupCore(CreateView(in shape, scheduler, throttle), keySelector, elementSelector); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable Count(Func? predicate) => + Inner.Count(predicate is null ? null : new LiveProjectedPredicate(Project, predicate).Matches); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable Any(Func? predicate) => + Inner.Any(predicate is null ? null : new LiveProjectedPredicate(Project, predicate).Matches); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable Contains(TProjected item) => + Inner.Any(new LiveProjectedPredicate(Project, new LiveEquals(item).Matches).Matches); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable SelectMany(Func> selector) => + Inner.SelectMany(new LiveComposedSelector>(Project, selector).Select); + + /// Orders the items by an ordering of their projections, and by the query's own ordering among ties. + /// The ordering of the projections, or for the query's own ordering. + /// The ordering of the items before the projection. + private IComparer Combine(IComparer? primary) => + primary is null ? Order : new LiveProjectedOrder(primary, Project, Order); +} diff --git a/src/ReactiveList/Queries/LivePlanner.cs b/src/ReactiveList/Queries/LivePlanner.cs new file mode 100644 index 00000000..2b29c856 --- /dev/null +++ b/src/ReactiveList/Queries/LivePlanner.cs @@ -0,0 +1,121 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Plans a recorded query onto one fused view or one subscription to its source. +internal static class LivePlanner +{ + /// Gets the test a plain query applies to source items. + /// The source item type. + /// The item type the query exposes. + /// The recorded query. + /// The test, or when the query is not plain or has no filter. + internal static Func? PlainPredicate(LiveFeed feed) + where TRaw : notnull + where T : notnull + { + if (!feed.Plain || !feed.HasFilter) + { + return null; + } + + // A plain query exposes the source items themselves, so both delegate types are the same type. + Func predicate = new LiveMatcher(feed.Map, null).Matches; + return (Func)(object)predicate; + } + + /// Plans a query onto one view. + /// The source item type. + /// The item type the query exposes. + /// The recorded query. + /// The ordering and window. + /// The scheduler that applies changes. + /// The coalescing window. + /// The view engine. + internal static ILiveViewCore CreateView(LiveFeed feed, in LiveShape shape, ISequencer scheduler, TimeSpan throttle) + where TRaw : notnull + where T : notnull + { + var list = feed.Source as IReactiveList; + if (list is null && feed.Plain && !shape.Window.IsSet && shape.Order is null) + { + return (ILiveViewCore)(object)CreatePlainFiltered(feed, scheduler, throttle); + } + + var binding = new LiveBinding(feed.Map, feed.Comparer, feed.SameRaw); + if (list is null) + { + return new LiveSetEngine(feed.Source, binding, shape, throttle, scheduler); + } + + var engine = new LiveListEngine(list, binding, shape); + engine.Start(throttle, scheduler); + return engine; + } + + /// Plans a query onto one grouped view. + /// The source item type. + /// The item type the query exposes. + /// The grouping key type. + /// The member type. + /// The recorded query. + /// Extracts the grouping key. + /// Extracts the member from an item. + /// The ordering of the members, or for source order. + /// The scheduler that applies changes. + /// The coalescing window. + /// The group engine. + internal static ILiveGroupCore CreateGroups( + LiveFeed feed, + Func keySelector, + Func elementSelector, + IComparer? order, + ISequencer scheduler, + TimeSpan throttle) + where TRaw : notnull + where T : notnull + where TKey : notnull + where TElement : notnull + { + LiveShape shape = new(order, LiveWindow.None); + var flat = CreateView(feed, in shape, scheduler, throttle); + return new LiveFusedGroupCore(flat, keySelector, elementSelector); + } + + /// Plans a state stream derived from how many items a query includes. + /// The source item type. + /// The item type the query exposes. + /// The reported value type. + /// The recorded query. + /// An extra test on the exposed item, or . + /// Derives the reported value from the count. + /// The state stream. + internal static IObservable Tally(LiveFeed feed, Func? extra, Func project) + where TRaw : notnull + where T : notnull => + feed.Plain && !feed.HasFilter && extra is null + ? new LiveTallyObservable(feed.Source, null, project, new LiveCountReader(feed.Source, project).Read) + : new LiveTallyObservable(feed.Source, new LiveMatcher(feed.Map, extra).Matches, project, null); + + /// Plans an unordered, unwindowed query over the items of an unordered source onto the existing view for such sources. + /// The source item type. + /// The item type the query exposes. + /// The recorded query. + /// The scheduler that applies changes. + /// The coalescing window. + /// The view engine. + private static LiveWrappedViewCore CreatePlainFiltered(LiveFeed feed, ISequencer scheduler, TimeSpan throttle) + where TRaw : notnull + where T : notnull + { + Func filter = feed.HasFilter ? new LiveMatcher(feed.Map, null).Matches : static _ => true; + var view = new ReactiveView(feed.Source, filter, throttle, scheduler, feed.SameRaw, synchronizeReads: true); + return new(view.Items, view.Storage, view.Items, view, null, view); + } +} diff --git a/src/ReactiveList/Queries/LiveProjectedOrder.cs b/src/ReactiveList/Queries/LiveProjectedOrder.cs new file mode 100644 index 00000000..3249a001 --- /dev/null +++ b/src/ReactiveList/Queries/LiveProjectedOrder.cs @@ -0,0 +1,25 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Orders items by an ordering of their projections, and breaks ties with an earlier ordering of the items. +/// The item type before the projection. +/// The item type after the projection. +/// Orders the projections. +/// Projects an item. +/// Orders the items that tie under . +internal sealed class LiveProjectedOrder(IComparer primary, Func project, IComparer secondary) : IComparer +{ + /// + public int Compare(T? x, T? y) + { + var result = primary.Compare(project(x!), project(y!)); + return result != 0 ? result : secondary.Compare(x!, y!); + } +} diff --git a/src/ReactiveList/Queries/LiveProjectedPredicate.cs b/src/ReactiveList/Queries/LiveProjectedPredicate.cs new file mode 100644 index 00000000..8c4bce77 --- /dev/null +++ b/src/ReactiveList/Queries/LiveProjectedPredicate.cs @@ -0,0 +1,23 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Applies a test to the projection of an item. +/// The item type before the projection. +/// The item type after the projection. +/// Projects an item. +/// The test. +internal sealed class LiveProjectedPredicate(Func project, Func predicate) +{ + /// Tests the projection of an item. + /// The item. + /// The outcome of the test on the projection. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal bool Matches(T item) => predicate(project(item)); +} diff --git a/src/ReactiveList/Queries/LiveProjectedViewCore.cs b/src/ReactiveList/Queries/LiveProjectedViewCore.cs new file mode 100644 index 00000000..25e1e931 --- /dev/null +++ b/src/ReactiveList/Queries/LiveProjectedViewCore.cs @@ -0,0 +1,165 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// +/// Projects the ordered, windowed output of a fused query into the items a view exposes. The order and the window are decided on the items +/// before the projection, so a projection that follows an ordering or a window runs on what the query produced, once per item that enters. +/// +/// The item type the fused query produces. +/// The item type the view exposes. +internal sealed class LiveProjectedViewCore : ILiveViewCore + where T : notnull + where TOut : notnull +{ + /// The fused query that orders and windows the items. + private readonly ILiveViewCore _inner; + + /// Projects an item of the fused query. + private readonly Func _project; + + /// Lets one thread at a time change the projected items. + private readonly LiveChangeSerializer _serializer; + + /// The projected items. + private readonly BatchObservableCollection _target = new(synchronizeReads: true); + + /// Reusable buffer for the projected items of a rebuild. + private readonly List _rebuilt = []; + + /// Non-zero once disposed. + private int _disposed; + + /// Initializes a new instance of the class. + /// The fused query that orders and windows the items. + /// Projects an item of the fused query. + internal LiveProjectedViewCore(ILiveViewCore inner, Func project) + { + _inner = inner; + _project = project; + Items = new(_target); + CollectionChanges = FacadeNotificationHelper.ObserveCollectionChanges(_target); + PropertyChanges = FacadeNotificationHelper.ObserveCollectionPropertyChanges(_target); + _serializer = new(ApplyChange, Rebuild, IsStopped); + inner.Storage.CollectionChanged += OnInnerChanged; + _serializer.Rebuild(); + } + + /// + public ReadOnlyObservableCollection Items { get; } + + /// + public BatchObservableCollection Storage => _target; + + /// + public int ResetLimit + { + get => _target.ResetLimit; + set + { + _target.ResetLimit = value; + _inner.ResetLimit = value; + } + } + + /// + public IObservable CollectionChanges { get; } + + /// + public IObservable PropertyChanges { get; } + + /// + public void Refresh() + { + _inner.Refresh(); + _serializer.Rebuild(); + } + + /// + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + _inner.Storage.CollectionChanged -= OnInnerChanged; + _inner.Dispose(); + } + + /// Passes one change of the fused query's output to the serializer. + /// The output collection. + /// The change. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void OnInnerChanged(object? sender, NotifyCollectionChangedEventArgs e) => _serializer.Handle(e); + + /// Tells whether the view was disposed. + /// when it was. + private bool IsStopped() => Volatile.Read(ref _disposed) != 0; + + /// Applies one change of the fused query's output. + /// The change. + /// when the change names positions the view does not hold, so it must be rebuilt. + private bool ApplyChange(NotifyCollectionChangedEventArgs e) + { + switch (e.Action) + { + case NotifyCollectionChangedAction.Add when e.NewItems is { } added && e.NewStartingIndex >= 0 && e.NewStartingIndex <= _target.Count: + { + for (var i = 0; i < added.Count; i++) + { + _target.Insert(e.NewStartingIndex + i, _project((T)added[i]!)); + } + + return true; + } + + case NotifyCollectionChangedAction.Remove when e.OldItems is { } removed && e.OldStartingIndex >= 0 && e.OldStartingIndex + removed.Count <= _target.Count: + { + for (var i = removed.Count - 1; i >= 0; i--) + { + _target.RemoveAt(e.OldStartingIndex + i); + } + + return true; + } + + case NotifyCollectionChangedAction.Replace when e.NewItems is { Count: 1 } replaced && (uint)e.NewStartingIndex < (uint)_target.Count: + { + _target[e.NewStartingIndex] = _project((T)replaced[0]!); + return true; + } + + case NotifyCollectionChangedAction.Move when (uint)e.OldStartingIndex < (uint)_target.Count && (uint)e.NewStartingIndex < (uint)_target.Count: + { + _target.Move(e.OldStartingIndex, e.NewStartingIndex); + return true; + } + + default: + { + return false; + } + } + } + + /// Rebuilds the projected items from the fused query's output. + private void Rebuild() + { + var items = _inner.Storage.CopySnapshot(); + _rebuilt.Clear(); + for (var i = 0; i < items.Length; i++) + { + _rebuilt.Add(_project(items[i])); + } + + _target.ReconcileTo(_rebuilt); + _rebuilt.Clear(); + } +} diff --git a/src/ReactiveList/Queries/LiveQuery.cs b/src/ReactiveList/Queries/LiveQuery.cs new file mode 100644 index 00000000..c138eb48 --- /dev/null +++ b/src/ReactiveList/Queries/LiveQuery.cs @@ -0,0 +1,229 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// +/// A query over a reactive source that records filters, projections, ordering and a window, and runs as one fused view or one +/// subscription when a terminal such as ToView or Count is called. +/// +/// The item type the query exposes. +[System.Diagnostics.DebuggerDisplay("LiveQuery")] +public readonly record struct LiveQuery + where T : notnull +{ + /// The recorded filters and projections. + private readonly ILiveFeed _feed; + + /// Initializes a new instance of the struct. + /// The recorded filters and projections. + internal LiveQuery(ILiveFeed feed) => _feed = feed; + + /// Gets the recorded filters and projections. + internal ILiveFeed Feed => _feed; + + /// Keeps the items that satisfy a condition. + /// The condition. + /// The extended query. + public LiveQuery Where(Func predicate) + { + ArgumentExceptionHelper.ThrowIfNull(predicate); + return new(_feed.Where(predicate)); + } + + /// Projects each item into a new form. + /// The projected item type. + /// The projection. + /// The extended query. + public LiveQuery Select(Func selector) + where TResult : notnull + { + ArgumentExceptionHelper.ThrowIfNull(selector); + return new(_feed.Select(selector)); + } + + /// Orders the items ascending by a key. + /// The sort key type. + /// Takes the sort key from an item. + /// The ordered query. + public OrderedLiveQuery OrderBy(Func keySelector) => + new(_feed, LiveQueryPlans.Key(keySelector, null, descending: false)); + + /// Orders the items ascending by a key. + /// The sort key type. + /// Takes the sort key from an item. + /// Compares two keys. + /// The ordered query. + public OrderedLiveQuery OrderBy(Func keySelector, IComparer comparer) => + new(_feed, LiveQueryPlans.Key(keySelector, comparer, descending: false)); + + /// Orders the items descending by a key. + /// The sort key type. + /// Takes the sort key from an item. + /// The ordered query. + public OrderedLiveQuery OrderByDescending(Func keySelector) => + new(_feed, LiveQueryPlans.Key(keySelector, null, descending: true)); + + /// Orders the items descending by a key. + /// The sort key type. + /// Takes the sort key from an item. + /// Compares two keys. + /// The ordered query. + public OrderedLiveQuery OrderByDescending(Func keySelector, IComparer comparer) => + new(_feed, LiveQueryPlans.Key(keySelector, comparer, descending: true)); + + /// Groups the items by a key. + /// The grouping key type. + /// Takes the grouping key from an item. + /// The grouped query. + public GroupedLiveQuery GroupBy(Func keySelector) + where TKey : notnull + { + ArgumentExceptionHelper.ThrowIfNull(keySelector); + return new(new LiveGroupPlan(_feed, keySelector, LiveMaps.Same, null)); + } + + /// Groups the items by a key and holds a value taken from each item in the groups. + /// The grouping key type. + /// The type of the values the groups hold. + /// Takes the grouping key from an item. + /// Takes the value a group holds from an item. + /// The grouped query. + public GroupedLiveQuery GroupBy(Func keySelector, Func elementSelector) + where TKey : notnull + where TElement : notnull + { + ArgumentExceptionHelper.ThrowIfNull(keySelector); + ArgumentExceptionHelper.ThrowIfNull(elementSelector); + return new(new LiveGroupPlan(_feed, keySelector, elementSelector, null)); + } + + /// Exposes only the first items. + /// The most items to expose. + /// The windowed query. + public WindowedLiveQuery Take(int count) + { + ArgumentOutOfRangeExceptionHelper.ThrowIfNegative(count); + return new(_feed, null, LiveWindow.None.With(new(true, count, null))); + } + + /// Exposes only the first items, with a count that can change over time. + /// An observable of the most items to expose. The view is empty until it emits, and negative values count as zero. + /// The windowed query. + public WindowedLiveQuery Take(IObservable count) + { + ArgumentExceptionHelper.ThrowIfNull(count); + return new(_feed, null, LiveWindow.None.With(new(true, 0, count))); + } + + /// Leaves out the first items. + /// The number of items to leave out. + /// The windowed query. + public WindowedLiveQuery Skip(int count) + { + ArgumentOutOfRangeExceptionHelper.ThrowIfNegative(count); + return new(_feed, null, LiveWindow.None.With(new(false, count, null))); + } + + /// Leaves out the first items, with a count that can change over time. + /// An observable of the number of items to leave out. Negative values count as zero. + /// The windowed query. + public WindowedLiveQuery Skip(IObservable count) + { + ArgumentExceptionHelper.ThrowIfNull(count); + return new(_feed, null, LiveWindow.None.With(new(false, 0, count))); + } + + /// Merges the observable each item produces into one sequence. + /// The merged value type. + /// + /// Creates the observable of an item. It is subscribed when the item enters the query and unsubscribed once when the item leaves, + /// is replaced by a different instance (an equal copy counts as a replacement for reference types), or the subscription is disposed. + /// Setting an item to the instance it already holds keeps its subscription. + /// + /// The merged sequence. + public IObservable SelectMany(Func> selector) + { + ArgumentExceptionHelper.ThrowIfNull(selector); + return _feed.SelectMany(selector); + } + + /// Merges the observable each item produces into one sequence, combining every value with its item. + /// The value type of an item's observable. + /// The combined value type. + /// Creates the observable of an item. + /// Combines an item with one of its values. + /// The merged sequence. + public IObservable SelectMany( + Func> collectionSelector, + Func resultSelector) + { + ArgumentExceptionHelper.ThrowIfNull(collectionSelector); + ArgumentExceptionHelper.ThrowIfNull(resultSelector); + return _feed.SelectMany(new LiveResultSelector(collectionSelector, resultSelector).Observe); + } + + /// Reports how many items the query includes, now and whenever the number changes. + /// The state stream, which completes when the source is disposed. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable Count() => _feed.Count(null); + + /// Reports how many items satisfy a condition, now and whenever the number changes. + /// The condition. + /// The state stream, which completes when the source is disposed. + public IObservable Count(Func predicate) + { + ArgumentExceptionHelper.ThrowIfNull(predicate); + return _feed.Count(predicate); + } + + /// Reports whether the query includes any item, now and whenever that changes. + /// The state stream, which completes when the source is disposed. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable Any() => _feed.Any(null); + + /// Reports whether any item satisfies a condition, now and whenever that changes. + /// The condition. + /// The state stream, which completes when the source is disposed. + public IObservable Any(Func predicate) + { + ArgumentExceptionHelper.ThrowIfNull(predicate); + return _feed.Any(predicate); + } + + /// Reports whether the query includes an item, now and whenever that changes. + /// The item to look for. + /// The state stream, which completes when the source is disposed. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable Contains(T item) => _feed.Contains(item); + + /// Creates a view with the default scheduler and throttle. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveView ToView() => ToView(null, LiveQueryPlans.DefaultThrottleMs); + + /// Creates a view with the specified scheduler and the default throttle. + /// The scheduler that applies changes, or for the current-thread scheduler. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveView ToView(ISequencer? scheduler) => ToView(scheduler, LiveQueryPlans.DefaultThrottleMs); + + /// Creates a view with the default scheduler and the specified throttle. + /// The coalescing window in milliseconds. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveView ToView(int throttleMs) => ToView(null, throttleMs); + + /// Creates a view. + /// The scheduler that applies changes, or for the current-thread scheduler. + /// The coalescing window in milliseconds. Zero applies changes as soon as the scheduler runs. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveView ToView(ISequencer? scheduler, int throttleMs) => + LiveQueryPlans.View(_feed, new(null, LiveWindow.None), scheduler, throttleMs); +} diff --git a/src/ReactiveList/Queries/LiveQueryExtensions.cs b/src/ReactiveList/Queries/LiveQueryExtensions.cs new file mode 100644 index 00000000..a51d8dbf --- /dev/null +++ b/src/ReactiveList/Queries/LiveQueryExtensions.cs @@ -0,0 +1,80 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Provides the Live entry point of every reactive source. +public static class LiveQueryExtensions +{ + /// Extensions for dictionaries. + /// The key type. + /// The value type. + /// The dictionary. + extension(IQuaternaryDictionary dictionary) + where TKey : notnull + { + /// Gets a live query over the entries of the dictionary. + /// Thrown when the dictionary is . + public LiveQuery> Live + { + get + { + ArgumentExceptionHelper.ThrowIfNull(dictionary); + return new(new LiveFeed, KeyValuePair>( + dictionary, + LiveMaps.Identity, + true, + false, + LiveKeyValueComparer.Instance, + LiveMaps.SameKey, + dictionary)); + } + } + } + + /// Extensions for reactive sources. + /// The item type of the source. + /// The source. + extension(IReactiveSource source) + where T : notnull + { + /// Gets a live query over the source, whose members carry the LINQ operator names and run as one fused view or subscription. + /// Thrown when the source is . + public LiveQuery Live + { + get + { + ArgumentExceptionHelper.ThrowIfNull(source); + return new(new LiveFeed(source, LiveMaps.Identity, true, false, EqualityComparer.Default, null, null)); + } + } + } + + /// Extensions for live queries over dictionary entries. + /// The key type. + /// The value type. + /// The query. + extension(LiveQuery> query) + where TKey : notnull + { + /// Reports the value stored under a key, now and whenever it changes, using the dictionary's keyed lookup. + /// The key. + /// The state stream, which completes when the dictionary is disposed. + /// Thrown when the query was not made directly from a dictionary with filters only. + public IObservable> ObserveValue(TKey key) + { + if (query.Feed is not LiveFeed, KeyValuePair> { Keyed: IQuaternaryDictionary dictionary } feed) + { + throw new InvalidOperationException("ObserveValue needs a query made directly from a dictionary, with at most Where clauses."); + } + + var reader = new LiveKeyReader(dictionary, key, feed.PlainPredicate); + return new LiveTallyObservable, LiveValue>(dictionary, null, static _ => default, reader.Read); + } + } +} diff --git a/src/ReactiveList/Queries/LiveQueryPlans.cs b/src/ReactiveList/Queries/LiveQueryPlans.cs new file mode 100644 index 00000000..006040cd --- /dev/null +++ b/src/ReactiveList/Queries/LiveQueryPlans.cs @@ -0,0 +1,59 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Turns the state a public query recorded into views, shared by every query shape. +internal static class LiveQueryPlans +{ + /// The default view throttle interval in milliseconds. + internal const int DefaultThrottleMs = 50; + + /// Creates a flat view. + /// The item type. + /// The recorded filters and projections. + /// The ordering and window. + /// The scheduler that applies changes, or for the current-thread scheduler. + /// The coalescing window in milliseconds. + /// The view. + internal static LiveView View(ILiveFeed feed, in LiveShape shape, ISequencer? scheduler, int throttleMs) + where T : notnull + { + ArgumentExceptionHelper.ThrowIfNull(feed); + return new(feed.CreateView(in shape, scheduler ?? ReactiveListScheduler.CurrentThread, TimeSpan.FromMilliseconds(throttleMs))); + } + + /// Creates a grouped view. + /// The grouping key type. + /// The member type. + /// The recorded grouping. + /// The scheduler that applies changes, or for the current-thread scheduler. + /// The coalescing window in milliseconds. + /// The view. + internal static LiveGroupView Groups(ILiveGroupPlan plan, ISequencer? scheduler, int throttleMs) + where TKey : notnull + where T : notnull + { + ArgumentExceptionHelper.ThrowIfNull(plan); + return new(plan.Create(scheduler ?? ReactiveListScheduler.CurrentThread, TimeSpan.FromMilliseconds(throttleMs))); + } + + /// Records a sort key. + /// The item type. + /// The sort key type. + /// Takes the sort key from an item. + /// Compares two keys, or for the default comparer. + /// Whether larger keys come first. + /// The comparer. + internal static IComparer Key(Func keySelector, IComparer? keyComparer, bool descending) + where T : notnull + { + ArgumentExceptionHelper.ThrowIfNull(keySelector); + return new LiveKeyComparer(keySelector, keyComparer, descending); + } +} diff --git a/src/ReactiveList/Queries/LiveResultMap.cs b/src/ReactiveList/Queries/LiveResultMap.cs new file mode 100644 index 00000000..b7ce0756 --- /dev/null +++ b/src/ReactiveList/Queries/LiveResultMap.cs @@ -0,0 +1,24 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Combines the values of one item's observable with that item. +/// The item type. +/// The value type the item's observable produces. +/// The combined value type. +/// The item. +/// Combines an item with one of its values. +internal sealed record LiveResultMap(T Item, Func Result) +{ + /// Combines a value with the item. + /// The value. + /// The combined value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal TResult Apply(TCollection value) => Result(Item, value); +} diff --git a/src/ReactiveList/Queries/LiveResultSelector.cs b/src/ReactiveList/Queries/LiveResultSelector.cs new file mode 100644 index 00000000..5a231848 --- /dev/null +++ b/src/ReactiveList/Queries/LiveResultSelector.cs @@ -0,0 +1,27 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Combines each value an item's observable produces with the item itself. +/// The item type. +/// The value type the item's observable produces. +/// The combined value type. +/// Creates the observable of an item. +/// Combines an item with one of its values. +internal sealed record LiveResultSelector( + Func> Collection, + Func Result) + where T : notnull +{ + /// Creates the combined observable of an item. + /// The item. + /// The observable of combined values. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal IObservable Observe(T item) => Collection(item).Map(new LiveResultMap(item, Result).Apply); +} diff --git a/src/ReactiveList/Queries/LiveSelectStage.cs b/src/ReactiveList/Queries/LiveSelectStage.cs new file mode 100644 index 00000000..57e5990f --- /dev/null +++ b/src/ReactiveList/Queries/LiveSelectStage.cs @@ -0,0 +1,37 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// A recorded projection applied after the stage it follows. +/// The source item type. +/// The item type the previous stage exposes. +/// The exposed item type. +/// The stage this projection follows. +/// The projection. +internal sealed record LiveSelectStage(LiveTryMap Inner, Func Selector) + where TRaw : notnull + where TMid : notnull + where T : notnull +{ + /// Applies the stage this projection follows and then the projection. + /// The source item. + /// Receives the exposed item when the source item passes. + /// when the source item belongs in the query. + internal bool TryMap(TRaw raw, out T value) + { + if (Inner(raw, out var middle)) + { + value = Selector(middle); + return true; + } + + value = default!; + return false; + } +} diff --git a/src/ReactiveList/Queries/LiveSequence.cs b/src/ReactiveList/Queries/LiveSequence.cs new file mode 100644 index 00000000..7a33baa0 --- /dev/null +++ b/src/ReactiveList/Queries/LiveSequence.cs @@ -0,0 +1,489 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// +/// Keeps the entries a query includes in output order and mirrors the window of them into the collection a view exposes. +/// Ties keep source order when a source mirror is supplied and arrival order otherwise. +/// +/// The source item type. +/// The item type the query exposes. +internal sealed class LiveSequence + where TRaw : notnull + where T : notnull +{ + /// The included entries in output order. + private readonly List> _items = []; + + /// Every entry of the source in source order, or when the source has no order. + private readonly List>? _mirror; + + /// The ordering, or for source order. + private readonly IComparer? _order; + + /// The entry ordering used for stable sorts. + private readonly LiveEntryComparer? _entryComparer; + + /// Reusable buffer for the exposed slice. + private readonly List _slice = []; + + /// The number of leading items left out. + private int _skip; + + /// The most items exposed, or -1 for all. + private int _take; + + /// Whether a window is being changed by a batch. + private bool _windowBatch; + + /// Whether the window must be reconciled when the batch ends. + private bool _windowSyncPending; + + /// Initializes a new instance of the class. + /// The ordering, or for source order. + /// The number of leading items left out. + /// The most items exposed, or -1 for all. + /// Every entry of the source in source order, or when the source has no order. + internal LiveSequence(IComparer? order, int skip, int take, List>? mirror) + { + _order = order; + _entryComparer = order is null ? null : new LiveEntryComparer(order); + _skip = skip; + _take = take; + _mirror = mirror; + Target = new(synchronizeReads: true); + Items = new(Target); + } + + /// Gets the collection a view exposes. + internal BatchObservableCollection Target { get; } + + /// Gets the read-only wrapper of . + internal ReadOnlyObservableCollection Items { get; } + + /// Gets a value indicating whether the window leaves anything out. + private bool IsWindowed => _skip > 0 || _take >= 0; + + /// Starts applying a source batch. + /// The number of mutations in the batch. + internal void BeginBatch(int size) + { + Target.BeginBatch(size); + _windowBatch = size > 1 && IsWindowed; + } + + /// Publishes the final window and closes the batch. + internal void EndBatch() + { + _windowBatch = false; + try + { + if (_windowSyncPending) + { + _windowSyncPending = false; + Sync(); + } + } + finally + { + Target.EndBatch(); + } + } + + /// Counts the included mirror entries before a mirror index. + /// The mirror index. + /// The sequence position of the first included entry at or after the index. + internal int IncludedBefore(int index) + { + var mirror = _mirror!; + var count = mirror.Count; + index = Math.Min(index, count); + if (index <= count >> 1) + { + var result = 0; + for (var i = 0; i < index; i++) + { + if (mirror[i].Included) + { + result++; + } + } + + return result; + } + + var after = 0; + for (var i = index; i < count; i++) + { + if (mirror[i].Included) + { + after++; + } + } + + return _items.Count - after; + } + + /// Changes the window and updates the exposed collection. + /// The number of leading items left out. + /// The most items exposed, or -1 for all. + internal void SetWindow(int skip, int take) + { + var oldSkip = _skip; + var oldTake = _take; + _skip = skip; + _take = take; + if (_windowBatch || _windowSyncPending || !TrySlide(oldSkip, oldTake)) + { + Sync(); + } + } + + /// Adds an entry that passed the query. + /// The entry, which must not be marked included yet. + /// The mirror index of the entry, or the position among included entries for sources without order. + internal void Insert(LiveEntry entry, int index) + { + var position = InsertionPosition(entry, index); + entry.Included = true; + _items.Insert(position, entry); + if (IsWindowed) + { + Sync(); + } + else + { + Target.Insert(position, entry.Value); + } + } + + /// Removes an included entry. + /// The entry. + /// The mirror index of the entry, or its position for sources without order. + internal void Remove(LiveEntry entry, int index) + { + var position = Locate(entry, index); + entry.Included = false; + if (position < 0) + { + return; + } + + _items.RemoveAt(position); + if (IsWindowed) + { + Sync(); + } + else + { + Target.RemoveAt(position); + } + } + + /// Replaces the entry at a source position. + /// The entry that is leaving. + /// The entry that takes its place, which must not be marked included yet. + /// The mirror index of the entry, or its position for sources without order. + /// Whether the old entry's sort position cannot be trusted because its item may have changed in place. + /// Whether the replacement belongs in the query. + internal void Replace(LiveEntry old, LiveEntry replacement, int index, bool revalidate, bool replacementPasses) + { + if (old.Included && replacementPasses) + { + ReplaceIncluded(old, replacement, index, revalidate); + return; + } + + if (old.Included) + { + Remove(old, index); + } + else if (replacementPasses) + { + Insert(replacement, index); + } + } + + /// Moves an included entry between sequence positions. + /// The old position. + /// The new position. + internal void MoveItem(int from, int to) + { + var entry = _items[from]; + _items.RemoveAt(from); + _items.Insert(to, entry); + if (IsWindowed) + { + Sync(); + } + else + { + Target.Move(from, to); + } + } + + /// Empties the sequence. + internal void Clear() + { + for (var i = 0; i < _items.Count; i++) + { + _items[i].Included = false; + } + + _items.Clear(); + Target.Clear(); + } + + /// Rebuilds the sequence from entries in source order. + /// The entries. + internal void Rebuild(IReadOnlyList> entries) + { + _items.Clear(); + for (var i = 0; i < entries.Count; i++) + { + var entry = entries[i]; + entry.Resolve(); + if (entry.Included) + { + _items.Add(entry); + } + } + + if (_entryComparer is not null) + { + var array = _items.ToArray(); + StableMergeSort.Sort(array, _entryComparer); + _items.Clear(); + _items.AddRange(array); + } + + Sync(); + } + + /// Replaces one included entry with another. + /// The entry that is leaving. + /// The entry that takes its place. + /// The mirror index or position. + /// Whether the sort position of the old entry cannot be trusted. + private void ReplaceIncluded(LiveEntry old, LiveEntry replacement, int index, bool revalidate) + { + var position = Locate(old, index); + if (position < 0) + { + old.Included = false; + Insert(replacement, index); + return; + } + + if (_order is null || (!revalidate && _order.Compare(old.Value, replacement.Value) == 0)) + { + old.Included = false; + replacement.Included = true; + _items[position] = replacement; + if (IsWindowed) + { + Sync(); + } + else + { + Target[position] = replacement.Value; + } + + return; + } + + Remove(old, index); + Insert(replacement, index); + } + + /// Finds where a new entry belongs. + /// The entry. + /// The mirror index, or the position for sources without order. + /// The sequence position. + private int InsertionPosition(LiveEntry entry, int index) + { + if (_order is null) + { + return _mirror is null ? Math.Min(index, _items.Count) : IncludedBefore(index); + } + + var value = entry.Value; + var upper = Bound(value, orEqual: true); + if (_mirror is null) + { + return upper; + } + + var lower = Bound(value, orEqual: false); + return lower == upper ? upper : lower + TiesBefore(entry, index); + } + + /// Counts the included source entries before an index that tie with an entry. + /// The entry. + /// The mirror index. + /// The number of ties that precede the entry in source order. + private int TiesBefore(LiveEntry entry, int index) + { + var mirror = _mirror!; + var order = _order!; + var count = 0; + var limit = Math.Min(index, mirror.Count); + for (var i = 0; i < limit; i++) + { + var other = mirror[i]; + if (other.Included && !ReferenceEquals(other, entry) && order.Compare(other.Value, entry.Value) == 0) + { + count++; + } + } + + return count; + } + + /// Binary-searches the ordered entries. + /// The value to place. + /// Whether equal entries count as smaller, giving the position after the ties. + /// The first position whose entry is not smaller than the value, or larger than it when is set. + private int Bound(T value, bool orEqual) + { + var order = _order!; + var low = 0; + var high = _items.Count; + while (low < high) + { + var middle = low + ((high - low) >> 1); + var comparison = order.Compare(_items[middle].Value, value); + if (comparison < 0 || (orEqual && comparison == 0)) + { + low = middle + 1; + } + else + { + high = middle; + } + } + + return low; + } + + /// Finds an included entry by identity. + /// The entry. + /// The mirror index, or the position for sources without order. + /// The sequence position, or -1. + private int Locate(LiveEntry entry, int index) + { + var guessed = LocateByOrder(entry, index); + if (guessed >= 0) + { + return guessed; + } + + for (var i = 0; i < _items.Count; i++) + { + if (ReferenceEquals(_items[i], entry)) + { + return i; + } + } + + return -1; + } + + /// Finds an included entry cheaply from its source position or its sort position. + /// The entry. + /// The mirror index, or the position for sources without order. + /// The sequence position, or -1 when the cheap lookup does not find it. + private int LocateByOrder(LiveEntry entry, int index) + { + if (_order is null) + { + var guess = _mirror is null ? index : IncludedBefore(index); + return (uint)guess < (uint)_items.Count && ReferenceEquals(_items[guess], entry) ? guess : -1; + } + + var value = entry.Value; + for (var i = Bound(value, orEqual: false); i < _items.Count && _order.Compare(_items[i].Value, value) == 0; i++) + { + if (ReferenceEquals(_items[i], entry)) + { + return i; + } + } + + return -1; + } + + /// Moves the exposed collection to a new window by removing the items that left it and adding the items that entered it. + /// The skip the exposed collection reflects. + /// The take the exposed collection reflects. + /// when the windows share no item or differ too much, so the exposed collection must be reconciled instead. + private bool TrySlide(int oldSkip, int oldTake) + { + var count = _items.Count; + LiveWindow.Range(oldSkip, oldTake, count, out var oldStart, out var oldEnd); + LiveWindow.Range(_skip, _take, count, out var newStart, out var newEnd); + var sharedStart = Math.Max(oldStart, newStart); + var sharedEnd = Math.Min(oldEnd, newEnd); + if (sharedEnd <= sharedStart || Target.Count != oldEnd - oldStart) + { + return false; + } + + var removedFront = sharedStart - oldStart; + var removedBack = oldEnd - sharedEnd; + var addedFront = sharedStart - newStart; + var addedBack = newEnd - sharedEnd; + if (removedFront + removedBack + addedFront + addedBack > Math.Min(BatchObservableCollection.ResetThreshold, Target.ResetLimit)) + { + return false; + } + + for (var i = 0; i < removedBack; i++) + { + Target.RemoveAt(Target.Count - 1); + } + + for (var i = 0; i < removedFront; i++) + { + Target.RemoveAt(0); + } + + for (var i = addedFront - 1; i >= 0; i--) + { + Target.Insert(0, _items[newStart + i].Value); + } + + for (var i = 0; i < addedBack; i++) + { + Target.Add(_items[sharedEnd + i].Value); + } + + return true; + } + + /// Makes the exposed collection hold the window of the sequence. + private void Sync() + { + if (_windowBatch) + { + // Intermediate slices are not changes to the window of the committed source batch. + _windowSyncPending = true; + return; + } + + _slice.Clear(); + var end = _take < 0 ? _items.Count : (int)Math.Min((long)_items.Count, (long)_skip + _take); + for (var i = _skip; i < end; i++) + { + _slice.Add(_items[i].Value); + } + + Target.ReconcileTo(_slice); + } +} diff --git a/src/ReactiveList/Queries/LiveSetEngine.cs b/src/ReactiveList/Queries/LiveSetEngine.cs new file mode 100644 index 00000000..496c5ba6 --- /dev/null +++ b/src/ReactiveList/Queries/LiveSetEngine.cs @@ -0,0 +1,162 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// +/// Maintains the fused view of a query over an unordered source such as a sharded collection. One stream projection subscribes to the source, +/// closes the snapshot gap and confirms its copy; the included entries it holds feed one sequence that applies ordering and the window. +/// +/// The source item type. +/// The item type the query exposes. +internal sealed class LiveSetEngine : ILiveViewCore + where TRaw : notnull + where T : notnull +{ + /// Observes the source and holds the included entries. + private readonly StreamProjection> _projection; + + /// The included entries in output order and the collection that exposes them. + private readonly LiveSequence _sequence; + + /// Follows observable windows, or . + private readonly LiveWindowDriver? _driver; + + /// Non-zero once disposed. + private int _disposed; + + /// Initializes a new instance of the class and starts observing the source. + /// The source to project. + /// Creates and compares entries. + /// The ordering and window. + /// The coalescing window. + /// The scheduler that applies changes. + internal LiveSetEngine( + IReactiveSource source, + LiveBinding binding, + in LiveShape shape, + TimeSpan throttle, + ISequencer scheduler) + { + var rules = ViewSourceRules.Create( + source, + binding.CreateEntry, + LiveBinding.Matches, + binding.SameRaw is null ? null : binding.SameEntry, + previousIsReliable: binding.SameRaw is null); + _projection = new(source, binding.CreateEntry, rules, "Count"); + var skip = shape.Window.Skip; + var take = shape.Window.Take; + if (shape.Window.HasSources) + { + _driver = new(shape.Window, RequestApply); + _driver.Start(); + _ = _driver.TryTakePending(out _, out _); + _driver.Current(out skip, out take); + } + + _sequence = new(shape.Order, skip, take, null); + _projection.Target.CollectionChanged += OnTargetChanged; + _projection.StartFromSource(throttle, scheduler, applyQueued: ApplyPendingWindow, hasQueued: HasPendingWindow); + } + + /// + public ReadOnlyObservableCollection Items => _sequence.Items; + + /// + public BatchObservableCollection Storage => _sequence.Target; + + /// + public int ResetLimit + { + get => _sequence.Target.ResetLimit; + set => _sequence.Target.ResetLimit = value; + } + + /// + public IObservable CollectionChanges => + FacadeNotificationHelper.ObserveCollectionChanges(_sequence.Target); + + /// + public IObservable PropertyChanges => _projection.PropertyChanges; + + /// + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + _driver?.Dispose(); + _projection.Target.CollectionChanged -= OnTargetChanged; + _projection.Dispose(); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Refresh() => _projection.Refresh(); + + /// Asks for a drain, which applies a window change without rebuilding the entries from the source. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void RequestApply() => _projection.RequestDrain(); + + /// Gets whether a window change is waiting. + /// when a drain has a window change to apply. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool HasPendingWindow() => _driver?.HasPending == true; + + /// Applies a window change that is waiting. + /// when the window changed. + private bool ApplyPendingWindow() + { + if (_driver is null || !_driver.TryTakePending(out var skip, out var take)) + { + return false; + } + + _sequence.SetWindow(skip, take); + return true; + } + + /// Mirrors one change of the projection's entries into the sequence. + /// The projection's collection. + /// The change. + private void OnTargetChanged(object? sender, NotifyCollectionChangedEventArgs e) + { + _ = ApplyPendingWindow(); + if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems is not null) + { + for (var i = 0; i < e.NewItems.Count; i++) + { + var entry = (LiveEntry)e.NewItems[i]!; + entry.Resolve(); + entry.Included = false; + _sequence.Insert(entry, e.NewStartingIndex + i); + } + } + else if (e.Action == NotifyCollectionChangedAction.Remove && e.OldItems is not null) + { + for (var i = e.OldItems.Count - 1; i >= 0; i--) + { + _sequence.Remove((LiveEntry)e.OldItems[i]!, e.OldStartingIndex + i); + } + } + else if (e.Action == NotifyCollectionChangedAction.Replace && e.OldItems is not null && e.NewItems is not null) + { + var replacement = (LiveEntry)e.NewItems[0]!; + replacement.Resolve(); + replacement.Included = false; + _sequence.Replace((LiveEntry)e.OldItems[0]!, replacement, e.NewStartingIndex, revalidate: false, replacementPasses: true); + } + else + { + _sequence.Rebuild(_projection.Target); + } + } +} diff --git a/src/ReactiveList/Queries/LiveShape.cs b/src/ReactiveList/Queries/LiveShape.cs new file mode 100644 index 00000000..d4a4b354 --- /dev/null +++ b/src/ReactiveList/Queries/LiveShape.cs @@ -0,0 +1,16 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// The ordering and window recorded after a query's filters and projections. +/// The item type the query exposes. +/// The comparer that orders the items, or for source order. +/// The slice of the ordered items to expose. +internal readonly record struct LiveShape(IComparer? Order, LiveWindow Window) + where T : notnull; diff --git a/src/ReactiveList/Queries/LiveTallyObservable.cs b/src/ReactiveList/Queries/LiveTallyObservable.cs new file mode 100644 index 00000000..657078f0 --- /dev/null +++ b/src/ReactiveList/Queries/LiveTallyObservable.cs @@ -0,0 +1,51 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// A cold observable that reports a value derived from how many source items pass a test. +/// The source item type. +/// The reported value type. +internal sealed class LiveTallyObservable : IObservable + where TRaw : notnull +{ + /// The source. + private readonly IReactiveSource _source; + + /// The test an item must pass to be counted, or to count every item. + private readonly Func? _match; + + /// Derives the reported value from the count. + private readonly Func _project; + + /// Reads the reported value straight from the source, or when items are counted. + private readonly Func? _read; + + /// Initializes a new instance of the class. + /// The source. + /// The test an item must pass to be counted. + /// Derives the reported value from the count. + /// Reads the reported value straight from the source, or to count items that pass . + internal LiveTallyObservable(IReactiveSource source, Func? match, Func project, Func? read) + { + _source = source; + _match = match; + _project = project; + _read = read; + } + + /// + public IDisposable Subscribe(IObserver observer) + { + ArgumentExceptionHelper.ThrowIfNull(observer); + + var subscription = new LiveTallySubscription(observer, _source, _match, _project, _read); + subscription.Start(); + return subscription; + } +} diff --git a/src/ReactiveList/Queries/LiveTallySubscription.cs b/src/ReactiveList/Queries/LiveTallySubscription.cs new file mode 100644 index 00000000..592a0165 --- /dev/null +++ b/src/ReactiveList/Queries/LiveTallySubscription.cs @@ -0,0 +1,531 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// +/// Follows how many source items pass a test and reports a value derived from that count each time it changes. Without a test it +/// reads the source's own count. With one it keeps a running count from the notifications and copies the source only to start, +/// to confirm the start, and to repair a count that cannot be kept exactly. No item is retained. +/// +/// The source item type. +/// The reported value type. +internal sealed class LiveTallySubscription : IDisposable + where TRaw : notnull +{ + /// Guards the queue of retained notifications. + private readonly Lock _gate = new(); + + /// The retained notifications. + private readonly Queue> _pending = []; + + /// The subscription to the source stream. + private readonly MultipleDisposable _disposables = []; + + /// The observer that receives the values. + private readonly IObserver _observer; + + /// The source. + private readonly IReactiveSource _source; + + /// The test an item must pass to be counted, or to count every item. + private readonly Func? _match; + + /// Derives the reported value from the count. + private readonly Func _project; + + /// Reads the reported value straight from the source, or when items are counted. + private readonly Func? _read; + + /// Lets disposal wait for a pump on another thread and stops later pumps. + private readonly DisposalGate _disposalGate = new(); + + /// The number of signals not yet handled. + private int _signals; + + /// Non-zero once disposed. + private int _disposed; + + /// Non-zero once the source completed or failed. + private int _completed; + + /// Non-zero once the observer was told the sequence ended. + private int _terminated; + + /// The failure of the source, or . + private Exception? _error; + + /// Non-zero when a recount was requested. + private int _resync; + + /// The current count of items that pass the test. + private int _count; + + /// The number of source items implied by the notifications applied since the last copy. + private int _sourceCount; + + /// The source revision when the stream was subscribed. + private long _sequenceBase; + + /// The number of notifications received. + private long _received; + + /// Notifications numbered up to this revision are already reflected in the last copy. + private long _covered; + + /// Whether the last copy still has to be confirmed. + private bool _settlePending; + + /// Whether a notification was applied since the last copy. + private bool _appliedSinceCopy; + + /// Whether a value was reported. + private bool _hasReported; + + /// The last reported value. + private TOut? _last; + + /// Initializes a new instance of the class. + /// The observer that receives the values. + /// The source. + /// The test an item must pass to be counted, or to count every item. + /// Derives the reported value from the count. + /// Reads the reported value straight from the source, or to count items that pass . + internal LiveTallySubscription( + IObserver observer, + IReactiveSource source, + Func? match, + Func project, + Func? read) + { + _observer = observer; + _source = source; + _match = match; + _project = project; + _read = read; + } + + /// + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + _disposables.Dispose(); + _disposalGate.Close(); + lock (_gate) + { + while (_pending.Count > 0) + { + _pending.Dequeue().Notification.Batch?.Dispose(); + } + } + } + + /// Subscribes to the source and reports the first value. + internal void Start() + { + // The first count must come from a copy of the source. A notification that arrives while the subscription is being made would + // otherwise be applied to a count that has not been taken yet. + Volatile.Write(ref _resync, 1); + _sequenceBase = _source.Version; + try + { + _disposables.Add(_source is IVersionedSnapshotSource versioned + ? versioned.VersionedStream.Subscribe(OnVersionedNotification, OnError, OnCompleted) + : _source.Stream.Subscribe(OnNotification, OnError, OnCompleted)); + } + catch (ObjectDisposedException) when (_source.IsDisposed) + { + Volatile.Write(ref _completed, 1); + } + + Signal(); + } + + /// Retains a notification and asks for a recount. + /// The notification. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void OnNotification(CacheNotify notification) => Enqueue(notification, null); + + /// Retains a notification with its source version and asks for a recount. + /// The notification and its source version. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void OnVersionedNotification(VersionedNotification versioned) => Enqueue(versioned.Notification, versioned.Version); + + /// Retains a notification when the tally depends on its contents. + /// The notification. + /// The source version when supplied by the stream. + private void Enqueue(CacheNotify notification, long? knownVersion) + { + var accepted = false; + if (_match is not null) + { + lock (_gate) + { + accepted = Volatile.Read(ref _disposed) == 0; + if (accepted) + { + _received++; + var version = knownVersion ?? (_source is IReactiveList ? _source.Version : _sequenceBase + _received); + _pending.Enqueue(new(notification, version)); + } + } + } + + if (!accepted) + { + notification.Batch?.Dispose(); + } + + Signal(); + } + + /// Records that the source failed. + /// The failure. + private void OnError(Exception error) + { + _error = error; + Volatile.Write(ref _completed, 1); + Signal(); + } + + /// Records that the source completed. + private void OnCompleted() + { + Volatile.Write(ref _completed, 1); + Signal(); + } + + /// Handles signals one thread at a time, so values are reported in the order they were computed and outside any lock. + private void Signal() + { + if (Interlocked.Increment(ref _signals) != 1) + { + return; + } + + var observed = 1; + while (true) + { + try + { + Pump(); + } + catch (Exception ex) + { + Fail(ex); + return; + } + + var remaining = Interlocked.Add(ref _signals, -observed); + if (remaining == 0) + { + return; + } + + observed = remaining; + } + } + + /// Brings the count up to date, reports a changed value and ends the sequence when the source ended. + private void Pump() + { + // Disposal closes the gate and waits for a pump on another thread, so nothing is reported after it returns. + if (Volatile.Read(ref _disposed) != 0 || !_disposalGate.TryEnter()) + { + return; + } + + try + { + if (!_source.IsDisposed && TryReadValue(out var value)) + { + Report(value); + } + + if (Volatile.Read(ref _completed) != 0) + { + Terminate(); + } + } + finally + { + _disposalGate.Exit(); + } + } + + /// Reads the current result unless the source shuts down during the read. + /// The result of a successful read. + /// Whether a value was read. + private bool TryReadValue([MaybeNullWhen(false)] out TOut value) + { + try + { + if (_read is not null) + { + value = _read(); + } + else + { + Tally(); + value = _project(_count); + } + + return true; + } + catch (ObjectDisposedException) when (_source.IsDisposed) + { + // Disposal can win after the initial check. The source stream still delivers its terminal signal. + value = default; + return false; + } + } + + /// Applies the retained notifications and recounts when the running count cannot be trusted. + private void Tally() + { + do + { + var mustRecount = ApplyPending() || Volatile.Read(ref _resync) != 0; + var settle = _settlePending && _appliedSinceCopy; + var drift = _source is not IVersionedSnapshotSource && _sourceCount != _source.Count; + if (mustRecount || drift || settle) + { + _ = Interlocked.Exchange(ref _resync, 0); + Recount(settle && !mustRecount); + } + } + while (Volatile.Read(ref _disposed) == 0 && HasPending()); + } + + /// Gets whether retained notifications remain. + /// when more are waiting. + private bool HasPending() + { + lock (_gate) + { + return _pending.Count > 0; + } + } + + /// Counts the items that pass the test in a consistent copy of the source. + /// Whether this copy only confirms an earlier one. + private void Recount(bool confirming) + { + var (items, version) = ViewSourceRules.ReadVersioned(_source); + var count = 0; + for (var i = 0; i < items.Length; i++) + { + if (_match!(items[i])) + { + count++; + } + } + + _count = count; + _sourceCount = items.Length; + _covered = version; + _appliedSinceCopy = false; + _settlePending = !confirming && _source is not IVersionedSnapshotSource; + } + + /// Applies every retained notification that the last copy does not already contain. + /// when a notification could not be applied exactly. + private bool ApplyPending() + { + var anomaly = false; + while (Volatile.Read(ref _disposed) == 0 && TryTake(out var notification)) + { + try + { + anomaly |= Apply(notification); + } + finally + { + notification.Batch?.Dispose(); + } + + _appliedSinceCopy = true; + } + + return anomaly; + } + + /// Takes the next retained notification that the last copy does not contain. + /// The notification. + /// when one was available. + private bool TryTake(out CacheNotify notification) + { + while (true) + { + PendingNotification next; + lock (_gate) + { + if (_pending.Count == 0) + { + notification = null!; + return false; + } + + next = _pending.Dequeue(); + } + + if (next.Version > _covered) + { + notification = next.Notification; + return true; + } + + next.Notification.Batch?.Dispose(); + } + } + + /// Applies one notification to the running count. + /// The notification. + /// when the count must be rebuilt. + private bool Apply(CacheNotify notification) + { + switch (notification.Action) + { + case CacheAction.Added: + return Adjust(notification.Item, 1); + case CacheAction.Removed: + return Adjust(notification.Item, -1); + case CacheAction.Updated: + { + // An item that replaces itself changed in place, so the test result it had before is not known and the count is rebuilt. + if (notification.Item is not { } current || notification.Previous is not { } previous || ItemComparison.SameItem(previous, current)) + { + return true; + } + + AdjustUpdate(previous, current); + return false; + } + + case CacheAction.Cleared: + { + _count = 0; + _sourceCount = 0; + return false; + } + + case CacheAction.BatchAdded: + return AdjustBatch(notification.Batch, 1); + case CacheAction.BatchRemoved: + return AdjustBatch(notification.Batch, -1); + case CacheAction.Moved: + return false; + default: + return true; + } + } + + /// Applies an item that joined or left the source. + /// The item. + /// 1 when the item joined, -1 when it left. + /// when the count must be rebuilt. + private bool Adjust(TRaw? item, int direction) + { + if (item is null) + { + return false; + } + + _sourceCount += direction; + if (_match!(item)) + { + _count += direction; + } + + return false; + } + + /// Applies a replaced item. + /// The replaced item. + /// The replacement. + private void AdjustUpdate(TRaw previous, TRaw current) + { + if (_match!(previous)) + { + _count--; + } + + if (_match(current)) + { + _count++; + } + } + + /// Applies a batch of items that joined or left the source. + /// The batch, or when it carried none. + /// 1 when the items joined, -1 when they left. + /// when the count must be rebuilt. + private bool AdjustBatch(PooledBatch? batch, int direction) + { + if (batch is null) + { + return true; + } + + for (var i = 0; i < batch.Count; i++) + { + _ = Adjust(batch.Items[i], direction); + } + + return false; + } + + /// Reports the derived value when it differs from the last one reported. + /// The value to report. + private void Report(TOut value) + { + if (_hasReported && EqualityComparer.Default.Equals(_last!, value)) + { + return; + } + + _hasReported = true; + _last = value; + if (Volatile.Read(ref _disposed) == 0) + { + _observer.OnNext(value); + } + } + + /// Tells the observer the sequence ended and releases the subscription. + private void Terminate() + { + if (Interlocked.Exchange(ref _terminated, 1) != 0) + { + return; + } + + var error = _error; + Dispose(); + if (error is not null) + { + _observer.OnError(error); + } + else + { + _observer.OnCompleted(); + } + } + + /// Ends the sequence with an error raised by the test or the source. + /// The failure. + private void Fail(Exception error) + { + _error = error; + Terminate(); + } +} diff --git a/src/ReactiveList/Queries/LiveThenComparer.cs b/src/ReactiveList/Queries/LiveThenComparer.cs new file mode 100644 index 00000000..008267ed --- /dev/null +++ b/src/ReactiveList/Queries/LiveThenComparer.cs @@ -0,0 +1,36 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Orders items by one comparer and breaks ties with another. +/// The item type. +internal sealed class LiveThenComparer : IComparer +{ + /// The primary comparer. + private readonly IComparer _first; + + /// The comparer that breaks ties. + private readonly IComparer _second; + + /// Initializes a new instance of the class. + /// The primary comparer. + /// The comparer that breaks ties. + internal LiveThenComparer(IComparer first, IComparer second) + { + _first = first; + _second = second; + } + + /// + public int Compare(T? x, T? y) + { + var result = _first.Compare(x!, y!); + return result != 0 ? result : _second.Compare(x!, y!); + } +} diff --git a/src/ReactiveList/Queries/LiveTryMap.cs b/src/ReactiveList/Queries/LiveTryMap.cs new file mode 100644 index 00000000..567594d8 --- /dev/null +++ b/src/ReactiveList/Queries/LiveTryMap.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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Applies the filters and projections a query recorded to one source item. +/// The source item type. +/// The item type the query exposes. +/// The source item. +/// Receives the exposed item when the source item passes. +/// when the source item belongs in the query. +internal delegate bool LiveTryMap(TRaw raw, out T value) + where TRaw : notnull + where T : notnull; diff --git a/src/ReactiveList/Queries/LiveValue.cs b/src/ReactiveList/Queries/LiveValue.cs new file mode 100644 index 00000000..2dcae2ef --- /dev/null +++ b/src/ReactiveList/Queries/LiveValue.cs @@ -0,0 +1,16 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// The value stored under a key at one moment, or the fact that the key is absent. +/// The value type. +/// Whether the key was present. +/// The value, which is the default when the key was absent. +[System.Diagnostics.DebuggerDisplay("LiveValue: Found = {Found}, Value = {Value}")] +public readonly record struct LiveValue(bool Found, TValue? Value); diff --git a/src/ReactiveList/Queries/LiveView.cs b/src/ReactiveList/Queries/LiveView.cs new file mode 100644 index 00000000..88c4af39 --- /dev/null +++ b/src/ReactiveList/Queries/LiveView.cs @@ -0,0 +1,104 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// A read-only, observable view of the items a live query includes. +/// The type of elements in the view. +[System.Diagnostics.DebuggerDisplay("LiveView: {Count}")] +public sealed class LiveView : IReadOnlyList, INotifyCollectionChanged, INotifyPropertyChanged, IReactiveView, T> + where T : notnull +{ + /// Holds the synchronization gate and lazy notification relays for this facade. + private readonly FacadeRelayState _relays = new(); + + /// The engine that owns the items and the source subscription. + private readonly ILiveViewCore _core; + + /// Initializes a new instance of the class. + /// The engine that owns the items and the source subscription. + internal LiveView(ILiveViewCore core) => _core = core; + + /// + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add => FacadeNotificationHelper.AddCollectionChanged(_relays, this, _core.CollectionChanges, value); + + remove => FacadeNotificationHelper.RemoveCollectionChanged(_relays, value); + } + + /// + public event PropertyChangedEventHandler? PropertyChanged + { + add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _core.PropertyChanges, value); + + remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value); + } + + /// Gets or sets the size above which one applied batch raises a single reset instead of one notification per item. + /// The value is negative. + /// + /// The default is , so every changed item raises its own notification. + /// A larger batch, or a window change that moves more items than the limit, updates the collection first and then raises one reset. + /// + public int BatchResetLimit + { + get => _core.ResetLimit; + + set => _core.ResetLimit = ReactiveViewHelpers.CheckedResetLimit(value); + } + + /// Gets the number of items in the view. + public int Count => _core.Storage.ReadCount(); + + /// Gets the read-only observable collection for UI binding. + /// Access the binding collection on the view's scheduler. Enumerate the view itself for a snapshot from any thread. + public ReadOnlyObservableCollection Items => _core.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] => _core.Storage.ReadAt(index); + + /// Enumerates a snapshot of the view's items. + /// An enumerator over the captured contents. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator GetEnumerator() => ((IEnumerable)_core.Storage.CopySnapshot()).GetEnumerator(); + + /// Forces a rebuild of the view from the source. + /// Views over sharded collections rebuild from a fresh copy of the source, which runs the query's delegates over every item again. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Refresh() => _core.Refresh(); + + /// Assigns the items collection to a property using the specified setter action. + /// An action that sets a property to the read-only observable collection of items. + /// The current instance, to enable method chaining. + /// Thrown if is null. + public LiveView ToProperty(Action> propertySetter) + { + _ = ReactiveViewHelpers.BindToProperty(this, Items, propertySetter); + return this; + } + + /// Returns the current instance and provides the read-only observable collection of items. + /// When this method returns, contains the read-only observable collection of items. + /// The current instance. + public LiveView ToProperty(out ReadOnlyObservableCollection collection) + { + collection = Items; + return this; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _core.Dispose(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} diff --git a/src/ReactiveList/Queries/LiveWindow.cs b/src/ReactiveList/Queries/LiveWindow.cs new file mode 100644 index 00000000..6f86eaf2 --- /dev/null +++ b/src/ReactiveList/Queries/LiveWindow.cs @@ -0,0 +1,130 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// The slice of an ordered query a view exposes: the skips and takes applied in the order they were recorded, as LINQ applies them. +/// The recorded skips and takes, or for none. +internal readonly record struct LiveWindow(LiveWindowOp[]? Operations) +{ + /// Gets a window that exposes every item. + internal static LiveWindow None => default; + + /// Gets the recorded skips and takes. + internal ReadOnlySpan Ops => Operations; + + /// Gets a value indicating whether a skip or a take is supplied over time. + internal bool HasSources + { + get + { + var ops = Ops; + for (var i = 0; i < ops.Length; i++) + { + if (ops[i].Source is not null) + { + return true; + } + } + + return false; + } + } + + /// Gets a value indicating whether the window leaves anything out or can change. + internal bool IsSet => HasSources || Skip > 0 || Take >= 0; + + /// Gets the number of leading items left out before any value arrives over time. + internal int Skip + { + get + { + Initial(out var skip, out _); + return skip; + } + } + + /// Gets the most items exposed before any value arrives over time, or -1 for all of them. + internal int Take + { + get + { + Initial(out _, out var take); + return take; + } + } + + /// Combines the skips and takes into the number of leading items left out and the most items exposed. + /// The recorded skips and takes. + /// The current value of each one. + /// Receives the number of leading items left out. + /// Receives the most items exposed, or -1 for all of them. + internal static void Fold(ReadOnlySpan ops, ReadOnlySpan values, out int skip, out int take) + { + long skipped = 0; + long taken = -1; + for (var i = 0; i < ops.Length; i++) + { + long value = Math.Max(0, values[i]); + if (ops[i].IsTake) + { + taken = taken < 0 ? value : Math.Min(taken, value); + continue; + } + + skipped += value; + if (taken >= 0) + { + taken = Math.Max(0, taken - value); + } + } + + skip = (int)Math.Min(skipped, int.MaxValue); + take = (int)taken; + } + + /// Finds the positions of a sequence a window exposes. + /// The number of leading items left out. + /// The most items exposed, or -1 for all. + /// The number of items in the sequence. + /// Receives the position of the first exposed item. + /// Receives the position after the last exposed item. + internal static void Range(int skip, int take, int count, out int start, out int end) + { + start = skip; + end = take < 0 ? count : (int)Math.Min(count, (long)skip + take); + end = Math.Max(start, end); + } + + /// Records one more skip or take after the ones already recorded. + /// The skip or take. + /// The extended window. + internal LiveWindow With(LiveWindowOp operation) + { + var existing = Operations ?? []; + var extended = new LiveWindowOp[existing.Length + 1]; + Array.Copy(existing, extended, existing.Length); + extended[existing.Length] = operation; + return new(extended); + } + + /// Combines the values the window starts with, where a value supplied over time is zero until it arrives. + /// Receives the number of leading items left out. + /// Receives the most items exposed, or -1 for all of them. + private void Initial(out int skip, out int take) + { + var ops = Ops; + var values = new int[ops.Length]; + for (var i = 0; i < ops.Length; i++) + { + values[i] = ops[i].Source is null ? ops[i].Value : 0; + } + + Fold(ops, values, out skip, out take); + } +} diff --git a/src/ReactiveList/Queries/LiveWindowDriver.cs b/src/ReactiveList/Queries/LiveWindowDriver.cs new file mode 100644 index 00000000..8a3032f5 --- /dev/null +++ b/src/ReactiveList/Queries/LiveWindowDriver.cs @@ -0,0 +1,129 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Follows the observables that supply a window's skips and takes and hands changes to the view's drain. +internal sealed class LiveWindowDriver : IDisposable +{ + /// Guards the current values. + private readonly Lock _gate = new(); + + /// The window the query recorded. + private readonly LiveWindow _window; + + /// Asks the owner to apply a pending change. + private readonly Action _requestApply; + + /// The subscriptions to the observables. + private readonly MultipleDisposable _subscriptions = []; + + /// The current value of every recorded skip and take. + private readonly int[] _values; + + /// The change waiting to be applied, or . + private object? _pending; + + /// Initializes a new instance of the class. + /// The window the query recorded. + /// Asks the owner to apply a pending change. + internal LiveWindowDriver(LiveWindow window, Action requestApply) + { + _window = window; + _requestApply = requestApply; + var ops = window.Ops; + _values = new int[ops.Length]; + for (var i = 0; i < ops.Length; i++) + { + // A value that is supplied over time exposes nothing, or skips nothing, until its first value arrives. + _values[i] = ops[i].Source is null ? ops[i].Value : 0; + } + } + + /// Gets a value indicating whether a change waits to be applied. + internal bool HasPending => Volatile.Read(ref _pending) is not null; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _subscriptions.Dispose(); + + /// Subscribes to the observables that supply skips and takes. + internal void Start() + { + var ops = _window.Ops; + for (var i = 0; i < ops.Length; i++) + { + if (ops[i].Source is { } source) + { + _subscriptions.Add(source.Subscribe(new Subscriber(this, i))); + } + } + } + + /// Reads the current skip and take. + /// Receives the skip. + /// Receives the take, or -1 for all. + internal void Current(out int skip, out int take) + { + lock (_gate) + { + LiveWindow.Fold(_window.Ops, _values, out skip, out take); + } + } + + /// Takes the change waiting to be applied. + /// Receives the skip. + /// Receives the take, or -1 for all. + /// when a change was waiting. + internal bool TryTakePending(out int skip, out int take) + { + if (Interlocked.Exchange(ref _pending, null) is null) + { + skip = 0; + take = -1; + return false; + } + + Current(out skip, out take); + return true; + } + + /// Records a new value for a skip or take. + /// The position of the skip or take. + /// The value. + private void OnValue(int index, int value) + { + lock (_gate) + { + _values[index] = Math.Max(0, value); + } + + Volatile.Write(ref _pending, this); + _requestApply(); + } + + /// Receives the values of one skip or take. + /// The driver. + /// The position of the skip or take. + private sealed class Subscriber(LiveWindowDriver owner, int index) : IObserver + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnNext(int value) => owner.OnValue(index, value); + + /// + public void OnError(Exception error) + { + } + + /// + public void OnCompleted() + { + } + } +} diff --git a/src/ReactiveList/Queries/LiveWindowOp.cs b/src/ReactiveList/Queries/LiveWindowOp.cs new file mode 100644 index 00000000..05227c1a --- /dev/null +++ b/src/ReactiveList/Queries/LiveWindowOp.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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// One skip or take recorded on a query. +/// for a take, for a skip. +/// The number of items, which is zero until a value arrives when supplies it. +/// An observable that supplies the number of items over time, or . +internal readonly record struct LiveWindowOp(bool IsTake, int Value, IObservable? Source); diff --git a/src/ReactiveList/Queries/LiveWrappedViewCore.cs b/src/ReactiveList/Queries/LiveWrappedViewCore.cs new file mode 100644 index 00000000..fdd2f8a0 --- /dev/null +++ b/src/ReactiveList/Queries/LiveWrappedViewCore.cs @@ -0,0 +1,71 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// Presents an existing view class as the engine behind a . +/// The item type. +internal sealed class LiveWrappedViewCore : ILiveViewCore + where T : notnull +{ + /// Rebuilds the view, or when the view always stays exact. + private readonly Action? _refresh; + + /// The wrapped view. + private readonly IDisposable _view; + + /// Initializes a new instance of the class. + /// The wrapped view's items. + /// The wrapped view's synchronized storage. + /// The wrapped view as a collection-change source. + /// The wrapped view as a property-change source. + /// Rebuilds the view, or when the view always stays exact. + /// The wrapped view. + internal LiveWrappedViewCore( + ReadOnlyObservableCollection items, + BatchObservableCollection storage, + INotifyCollectionChanged collection, + INotifyPropertyChanged properties, + Action? refresh, + IDisposable view) + { + Items = items; + Storage = storage; + _refresh = refresh; + _view = view; + CollectionChanges = LiveEventObservables.Collection(collection); + PropertyChanges = LiveEventObservables.Property(properties); + } + + /// + public ReadOnlyObservableCollection Items { get; } + + /// + public BatchObservableCollection Storage { get; } + + /// + public int ResetLimit + { + get => Storage.ResetLimit; + set => Storage.ResetLimit = value; + } + + /// + public IObservable CollectionChanges { get; } + + /// + public IObservable PropertyChanges { get; } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _view.Dispose(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Refresh() => _refresh?.Invoke(); +} diff --git a/src/ReactiveList/Queries/OrderedLiveQuery.cs b/src/ReactiveList/Queries/OrderedLiveQuery.cs new file mode 100644 index 00000000..4315b3b1 --- /dev/null +++ b/src/ReactiveList/Queries/OrderedLiveQuery.cs @@ -0,0 +1,216 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// +/// A live query whose items are ordered. Over an ordered source such as a list, items that compare equal keep source order. Over a sharded +/// source, which has no order, they keep the order in which the view received them, so add a final key that is unique when ties matter. +/// +/// The item type the query exposes. +[System.Diagnostics.DebuggerDisplay("OrderedLiveQuery")] +public readonly record struct OrderedLiveQuery + where T : notnull +{ + /// The recorded filters and projections. + private readonly ILiveFeed _feed; + + /// The recorded ordering. + private readonly IComparer _order; + + /// Initializes a new instance of the struct. + /// The recorded filters and projections. + /// The recorded ordering. + internal OrderedLiveQuery(ILiveFeed feed, IComparer order) + { + _feed = feed; + _order = order; + } + + /// Keeps the items that satisfy a condition. The items that remain keep their order. + /// The condition. + /// The extended query. + public OrderedLiveQuery Where(Func predicate) + { + ArgumentExceptionHelper.ThrowIfNull(predicate); + return new(_feed.Where(predicate), _order); + } + + /// Projects each ordered item into a new form. The projections keep the order of the items they come from. + /// The projected item type. + /// The projection. + /// The extended query. A condition added to it tests the projection, and runs the projection again for each test. + public LiveQuery Select(Func selector) + where TResult : notnull + { + ArgumentExceptionHelper.ThrowIfNull(selector); + return new(new LiveOrderedProjectionFeed(_feed, _order, selector)); + } + + /// Breaks ties ascending by another key. + /// The sort key type. + /// Takes the sort key from an item. + /// The extended query. + public OrderedLiveQuery ThenBy(Func keySelector) => + new(_feed, new LiveThenComparer(_order, LiveQueryPlans.Key(keySelector, null, descending: false))); + + /// Breaks ties ascending by another key. + /// The sort key type. + /// Takes the sort key from an item. + /// Compares two keys. + /// The extended query. + public OrderedLiveQuery ThenBy(Func keySelector, IComparer comparer) => + new(_feed, new LiveThenComparer(_order, LiveQueryPlans.Key(keySelector, comparer, descending: false))); + + /// Breaks ties descending by another key. + /// The sort key type. + /// Takes the sort key from an item. + /// The extended query. + public OrderedLiveQuery ThenByDescending(Func keySelector) => + new(_feed, new LiveThenComparer(_order, LiveQueryPlans.Key(keySelector, null, descending: true))); + + /// Breaks ties descending by another key. + /// The sort key type. + /// Takes the sort key from an item. + /// Compares two keys. + /// The extended query. + public OrderedLiveQuery ThenByDescending(Func keySelector, IComparer comparer) => + new(_feed, new LiveThenComparer(_order, LiveQueryPlans.Key(keySelector, comparer, descending: true))); + + /// Groups the ordered items by a key. Members of each group keep the query's order. + /// The grouping key type. + /// Takes the grouping key from an item. + /// The grouped query. + public GroupedLiveQuery GroupBy(Func keySelector) + where TKey : notnull + { + ArgumentExceptionHelper.ThrowIfNull(keySelector); + return new(new LiveGroupPlan(_feed, keySelector, LiveMaps.Same, _order)); + } + + /// Groups the ordered items by a key and holds a value taken from each item in the groups. Members of each group keep the query's order. + /// The grouping key type. + /// The type of the values the groups hold. + /// Takes the grouping key from an item. + /// Takes the value a group holds from an item. + /// The grouped query. + public GroupedLiveQuery GroupBy(Func keySelector, Func elementSelector) + where TKey : notnull + where TElement : notnull + { + ArgumentExceptionHelper.ThrowIfNull(keySelector); + ArgumentExceptionHelper.ThrowIfNull(elementSelector); + return new(new LiveGroupPlan(_feed, keySelector, elementSelector, _order)); + } + + /// Exposes only the first items. + /// The most items to expose. + /// The windowed query. + public WindowedLiveQuery Take(int count) + { + ArgumentOutOfRangeExceptionHelper.ThrowIfNegative(count); + return new(_feed, _order, LiveWindow.None.With(new(true, count, null))); + } + + /// Exposes only the first items, with a count that can change over time. + /// An observable of the most items to expose. The view is empty until it emits, and negative values count as zero. + /// The windowed query. + public WindowedLiveQuery Take(IObservable count) + { + ArgumentExceptionHelper.ThrowIfNull(count); + return new(_feed, _order, LiveWindow.None.With(new(true, 0, count))); + } + + /// Leaves out the first items. + /// The number of items to leave out. + /// The windowed query. + public WindowedLiveQuery Skip(int count) + { + ArgumentOutOfRangeExceptionHelper.ThrowIfNegative(count); + return new(_feed, _order, LiveWindow.None.With(new(false, count, null))); + } + + /// Leaves out the first items, with a count that can change over time. + /// An observable of the number of items to leave out. Negative values count as zero. + /// The windowed query. + public WindowedLiveQuery Skip(IObservable count) + { + ArgumentExceptionHelper.ThrowIfNull(count); + return new(_feed, _order, LiveWindow.None.With(new(false, 0, count))); + } + + /// Merges the observable each item produces into one sequence. The order does not affect the result. + /// The merged value type. + /// + /// Creates the observable of an item. It is subscribed when the item enters the query and unsubscribed once when the item leaves, + /// is replaced by a different instance (an equal copy counts as a replacement for reference types), or the subscription is disposed. + /// Setting an item to the instance it already holds keeps its subscription. + /// + /// The merged sequence. + public IObservable SelectMany(Func> selector) + { + ArgumentExceptionHelper.ThrowIfNull(selector); + return _feed.SelectMany(selector); + } + + /// Merges the observable each item produces into one sequence, combining every value with its item. The order does not affect the result. + /// The value type of an item's observable. + /// The combined value type. + /// Creates the observable of an item. + /// Combines an item with one of its values. + /// The merged sequence. + public IObservable SelectMany( + Func> collectionSelector, + Func resultSelector) + { + ArgumentExceptionHelper.ThrowIfNull(collectionSelector); + ArgumentExceptionHelper.ThrowIfNull(resultSelector); + return _feed.SelectMany(new LiveResultSelector(collectionSelector, resultSelector).Observe); + } + + /// Reports how many items the query includes, now and whenever the number changes. + /// The state stream, which completes when the source is disposed. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable Count() => _feed.Count(null); + + /// Reports whether the query includes any item, now and whenever that changes. + /// The state stream, which completes when the source is disposed. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable Any() => _feed.Any(null); + + /// Reports whether the query includes an item, now and whenever that changes. + /// The item to look for. + /// The state stream, which completes when the source is disposed. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IObservable Contains(T item) => _feed.Contains(item); + + /// Creates a view with the default scheduler and throttle. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveView ToView() => ToView(null, LiveQueryPlans.DefaultThrottleMs); + + /// Creates a view with the specified scheduler and the default throttle. + /// The scheduler that applies changes, or for the current-thread scheduler. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveView ToView(ISequencer? scheduler) => ToView(scheduler, LiveQueryPlans.DefaultThrottleMs); + + /// Creates a view with the default scheduler and the specified throttle. + /// The coalescing window in milliseconds. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveView ToView(int throttleMs) => ToView(null, throttleMs); + + /// Creates a view. + /// The scheduler that applies changes, or for the current-thread scheduler. + /// The coalescing window in milliseconds. Zero applies changes as soon as the scheduler runs. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveView ToView(ISequencer? scheduler, int throttleMs) => + LiveQueryPlans.View(_feed, new(_order, LiveWindow.None), scheduler, throttleMs); +} diff --git a/src/ReactiveList/Queries/WindowedLiveQuery.cs b/src/ReactiveList/Queries/WindowedLiveQuery.cs new file mode 100644 index 00000000..a7ef8a05 --- /dev/null +++ b/src/ReactiveList/Queries/WindowedLiveQuery.cs @@ -0,0 +1,110 @@ +// 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.Queries; +#else +namespace ReactiveList.Queries; +#endif + +/// A live query that exposes a window of its ordered items, so a view can page. +/// The item type the query exposes. +[System.Diagnostics.DebuggerDisplay("WindowedLiveQuery")] +public readonly record struct WindowedLiveQuery + where T : notnull +{ + /// The recorded filters and projections. + private readonly ILiveFeed _feed; + + /// The recorded ordering, or for source order. + private readonly IComparer? _order; + + /// The recorded window. + private readonly LiveWindow _window; + + /// Initializes a new instance of the struct. + /// The recorded filters and projections. + /// The recorded ordering, or for source order. + /// The recorded window. + internal WindowedLiveQuery(ILiveFeed feed, IComparer? order, LiveWindow window) + { + _feed = feed; + _order = order; + _window = window; + } + + /// Exposes only the first items of the window so far, as LINQ does: Take(10).Skip(2) exposes the items from the third to the tenth. + /// The most items to expose. + /// The windowed query. + public WindowedLiveQuery Take(int count) + { + ArgumentOutOfRangeExceptionHelper.ThrowIfNegative(count); + return new(_feed, _order, _window.With(new(true, count, null))); + } + + /// Exposes only the first items of the window so far, with a count that can change over time. + /// An observable of the most items to expose. The view is empty until it emits, and negative values count as zero. + /// The windowed query. + public WindowedLiveQuery Take(IObservable count) + { + ArgumentExceptionHelper.ThrowIfNull(count); + return new(_feed, _order, _window.With(new(true, 0, count))); + } + + /// Leaves out the first items of the window so far, as LINQ does. + /// The number of items to leave out. + /// The windowed query. + public WindowedLiveQuery Skip(int count) + { + ArgumentOutOfRangeExceptionHelper.ThrowIfNegative(count); + return new(_feed, _order, _window.With(new(false, count, null))); + } + + /// Leaves out the first items of the window so far, with a count that can change over time. + /// An observable of the number of items to leave out. Negative values count as zero. + /// The windowed query. + public WindowedLiveQuery Skip(IObservable count) + { + ArgumentExceptionHelper.ThrowIfNull(count); + return new(_feed, _order, _window.With(new(false, 0, count))); + } + + /// Projects each item of the window into a new form. Skips and takes added afterwards apply to the same sequence. + /// The projected item type. + /// The projection. + /// The windowed query of projections. + public WindowedLiveQuery Select(Func selector) + where TResult : notnull + { + ArgumentExceptionHelper.ThrowIfNull(selector); + return _order is null + ? new(_feed.Select(selector), null, _window) + : new(new LiveOrderedProjectionFeed(_feed, _order, selector), null, _window); + } + + /// Creates a view with the default scheduler and throttle. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveView ToView() => ToView(null, LiveQueryPlans.DefaultThrottleMs); + + /// Creates a view with the specified scheduler and the default throttle. + /// The scheduler that applies changes, or for the current-thread scheduler. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveView ToView(ISequencer? scheduler) => ToView(scheduler, LiveQueryPlans.DefaultThrottleMs); + + /// Creates a view with the default scheduler and the specified throttle. + /// The coalescing window in milliseconds. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveView ToView(int throttleMs) => ToView(null, throttleMs); + + /// Creates a view. + /// The scheduler that applies changes, or for the current-thread scheduler. + /// The coalescing window in milliseconds. Zero applies changes as soon as the scheduler runs. + /// The view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public LiveView ToView(ISequencer? scheduler, int throttleMs) => + LiveQueryPlans.View(_feed, new(_order, _window), scheduler, throttleMs); +} diff --git a/src/ReactiveList/ReactiveList.csproj b/src/ReactiveList/ReactiveList.csproj index 7613d854..0470b44e 100644 --- a/src/ReactiveList/ReactiveList.csproj +++ b/src/ReactiveList/ReactiveList.csproj @@ -29,6 +29,8 @@ + + @@ -47,6 +49,7 @@ + diff --git a/src/ReactiveList/ReactiveListExtensions.cs b/src/ReactiveList/ReactiveListExtensions.cs index 2e9607be..cf064bf2 100644 --- a/src/ReactiveList/ReactiveListExtensions.cs +++ b/src/ReactiveList/ReactiveListExtensions.cs @@ -31,32 +31,15 @@ public static class ReactiveListExtensions /// an observable. When a new filter is emitted, subsequent cache notifications are filtered using that predicate. public IObservable>> FilterDynamic(IObservable, bool>> filterObservable) { -#if NET8_0_OR_GREATER - ThrowHelper.ThrowIfNull(stream); - ThrowHelper.ThrowIfNull(filterObservable); -#else - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } + ArgumentExceptionHelper.ThrowIfNull(stream); + ArgumentExceptionHelper.ThrowIfNull(filterObservable); - if (filterObservable is null) + return Signal.Create>>(observer => { - throw new ArgumentNullException(nameof(filterObservable)); - } -#endif - - return filterObservable - .Lead(static _ => true) // Default to include all items - .Map(filter => stream.Map(notification => notification.Action switch - { - CacheAction.Added or CacheAction.Removed or CacheAction.Cleared - when notification.Action != CacheAction.Added || filter(notification.Item) => notification, - CacheAction.BatchAdded or CacheAction.BatchRemoved or CacheAction.BatchOperation when notification.Batch is not null => - FilterBatchByPredicate(notification, filter), - _ => null - }).Where(static n => n is not null).Map(static n => n!)) - .SwitchTo(); + var subscription = new DynamicFilterSubscription>(observer); + subscription.Connect(stream, filterObservable); + return subscription; + }); } } @@ -77,34 +60,15 @@ CacheAction.Added or CacheAction.Removed or CacheAction.Cleared /// an observable. When a new filter is emitted, subsequent cache notifications are filtered using that predicate. public IObservable> FilterDynamic(IObservable> filterObservable) { -#if NET8_0_OR_GREATER - ThrowHelper.ThrowIfNull(stream); - ThrowHelper.ThrowIfNull(filterObservable); -#else - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } + ArgumentExceptionHelper.ThrowIfNull(stream); + ArgumentExceptionHelper.ThrowIfNull(filterObservable); - if (filterObservable is null) + return Signal.Create>(observer => { - throw new ArgumentNullException(nameof(filterObservable)); - } -#endif - - return filterObservable - .Lead(static _ => true) // Default to include all items - .Map(filter => stream.Map(notification => notification.Action switch - { - CacheAction.Added or CacheAction.Removed or CacheAction.Cleared - when notification.Action == CacheAction.Cleared - || (notification.Item is not null - && (notification.Action == CacheAction.Removed || filter(notification.Item))) => notification, - CacheAction.BatchAdded or CacheAction.BatchRemoved or CacheAction.BatchOperation when notification.Batch is not null => - FilterBatchByPredicate(notification, filter), - _ => null - }).Where(static n => n is not null).Map(static n => n!)) - .SwitchTo(); + var subscription = new DynamicFilterSubscription(observer); + subscription.Connect(stream, filterObservable); + return subscription; + }); } /// Filters the items in each cache notification emitted by the stream observable according to the specified predicate. @@ -125,7 +89,7 @@ or CacheAction.Moved return isSingleItemAction && notification.Item is not null ? predicate(notification.Item) - : notification.Action is CacheAction.Cleared or + : notification.Action is CacheAction.Cleared or CacheAction.Reset or CacheAction.BatchOperation or CacheAction.BatchAdded or CacheAction.BatchRemoved; @@ -144,20 +108,8 @@ CacheAction.BatchAdded or [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable> WhereChanges(Func, bool> predicate) { -#if NET8_0_OR_GREATER - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(predicate); -#else - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - - if (predicate is null) - { - throw new ArgumentNullException(nameof(predicate)); - } -#endif + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(predicate); return source.Map(changeSet => { @@ -222,20 +174,8 @@ public IObservable> WhereChanges(Func, bool> predicate) [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable> SelectChanges(Func selector) { -#if NET8_0_OR_GREATER - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); -#else - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - - if (selector is null) - { - throw new ArgumentNullException(nameof(selector)); - } -#endif + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(selector); return source.Map(changes => { @@ -268,20 +208,8 @@ public IObservable> SelectChanges(Func s [MethodImpl(MethodImplOptions.AggressiveInlining)] public IObservable SelectChanges(Func, TResult> selector) { -#if NET8_0_OR_GREATER - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(selector); -#else - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - - if (selector is null) - { - throw new ArgumentNullException(nameof(selector)); - } -#endif + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(selector); return source.FlatMap(changeSet => { @@ -337,8 +265,8 @@ public IObservable OnRemove() => /// change set. public IObservable> GroupByChanges(Func keySelector) { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(keySelector); return Signal.Create>(observer => { var groups = new List>(); @@ -404,8 +332,8 @@ public IObservable> GroupByChanges(Func>> GroupingByChanges(Func keySelector) where TKey : notnull { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(keySelector); + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(keySelector); return source.FlatMap(changeSet => { @@ -414,23 +342,7 @@ public IObservable>> GroupingByChanges(Func>[groups.Count]; @@ -486,39 +398,23 @@ public IObservable> SortBy(Func keySelector) => sour extension(IObservable> source) where T : INotifyPropertyChanged { - /// Automatically refreshes items when the specified property changes (via INotifyPropertyChanged). + /// Emits the source change sets plus a refresh whenever a watched item raises . /// The name of the property to watch for changes. If null or empty, watches all properties. /// An observable that includes refresh notifications when property changes occur. + /// + /// An item is watched from the time it is added or swapped in until it is removed, replaced or cleared, the source ends, or the subscription is + /// disposed; a handler is detached at that moment. An item that appears several times is watched once and stays watched until its last + /// occurrence leaves. Items already in the source before the subscription are not watched. Notifications reach the observer one at a time. + /// public IObservable> AutoRefresh(string? propertyName) { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); - var watchAllProperties = string.IsNullOrEmpty(propertyName); - - return source.FlatMap(changeSet => + return Signal.Create>(observer => { - var results = new List>> { Signal.Emit(changeSet) }; - - for (var i = 0; i < changeSet.Count; i++) - { - var change = changeSet[i]; - if (change.Reason is not (ChangeReason.Add or ChangeReason.Update)) - { - continue; - } - - var item = change.Current; - var index = change.CurrentIndex; - var refreshObservable = Observable.FromEventPattern( - h => item.PropertyChanged += h, - h => item.PropertyChanged -= h) - .Keep(e => watchAllProperties || e.EventArgs.PropertyName == propertyName || string.IsNullOrEmpty(e.EventArgs.PropertyName)) - .Map(_ => new ChangeSet([Change.CreateRefresh(item, index)])); - - results.Add(refreshObservable); - } - - return results.Blend(); + var subscription = new AutoRefreshSubscription(observer, propertyName); + subscription.Connect(source); + return subscription; }); } @@ -851,26 +747,9 @@ public DynamicReactiveView CreateView( /// Thrown when source is null. public DynamicReactiveView CreateView(IObservable queryObservable, Func filter, ISequencer scheduler, int throttleMs) { -#if NET8_0_OR_GREATER - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(queryObservable); - ThrowHelper.ThrowIfNull(filter); -#else - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - - if (queryObservable is null) - { - throw new ArgumentNullException(nameof(queryObservable)); - } - - if (filter is null) - { - throw new ArgumentNullException(nameof(filter)); - } -#endif + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(queryObservable); + ArgumentExceptionHelper.ThrowIfNull(filter); // Convert query observable to a filter observable var filterObservable = queryObservable.Map>(query => item => filter(query, item)); @@ -898,20 +777,8 @@ public DynamicReactiveView CreateView(IObservable> filterObserv /// Thrown when source is null. public DynamicReactiveView CreateView(IObservable> filterObservable, ISequencer scheduler, int throttleMs) { -#if NET8_0_OR_GREATER - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(filterObservable); -#else - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - - if (filterObservable is null) - { - throw new ArgumentNullException(nameof(filterObservable)); - } -#endif + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(filterObservable); return new(source, filterObservable, TimeSpan.FromMilliseconds(throttleMs), scheduler); } @@ -925,7 +792,7 @@ public DynamicReactiveView CreateView(IObservable> filterObserv /// specified throttling. /// The returned view provides a thread-safe, observable snapshot of the source. Change /// notifications are throttled to avoid excessive updates when the source changes rapidly. Use this method to - /// efficiently bind UI or other observers to dynamic data sources. + /// efficiently bind UI or other observers to changing sources. [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReactiveView CreateView(ISequencer scheduler) => source.CreateView(scheduler, DefaultThrottleMs); @@ -937,18 +804,9 @@ public ReactiveView CreateView(ISequencer scheduler) => /// Thrown when source is null. public ReactiveView CreateView(ISequencer scheduler, int throttleMs) { -#if NET8_0_OR_GREATER - ThrowHelper.ThrowIfNull(source); -#else - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } -#endif + ArgumentExceptionHelper.ThrowIfNull(source); - // Thread-safe snapshot - var snapshot = source.ToArray(); - return new(source.Stream, snapshot, static _ => true, TimeSpan.FromMilliseconds(throttleMs), scheduler); + return new(source, static _ => true, TimeSpan.FromMilliseconds(throttleMs), scheduler); } /// @@ -976,21 +834,12 @@ public ReactiveView CreateView(Func filter, ISequencer scheduler) => /// Thrown when source is null. public ReactiveView CreateView(Func filter, ISequencer scheduler, int throttleMs) { -#if NET8_0_OR_GREATER - ThrowHelper.ThrowIfNull(source); -#else - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } -#endif + ArgumentExceptionHelper.ThrowIfNull(source); - // Thread-safe snapshot - var snapshot = source.ToArray(); - return new(source.Stream, snapshot, filter, TimeSpan.FromMilliseconds(throttleMs), scheduler); + return new(source, filter, TimeSpan.FromMilliseconds(throttleMs), scheduler); } - /// Connects to the change stream and converts to ChangeSet format for compatibility with DynamicData-style processing. + /// Connects to the change stream and converts it to ChangeSet format. /// An observable stream of change sets representing all modifications to the source. /// /// This is a convenience method that bridges the Stream-based notification model @@ -998,7 +847,7 @@ public ReactiveView CreateView(Func filter, ISequencer scheduler, in /// public IObservable> Connect() { - ThrowHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(source); return Observable.Defer(() => { @@ -1019,35 +868,18 @@ public IObservable> Connect() }); } - /// - /// Creates an observable sequence that emits a refresh change set whenever the specified property of any item in - /// the source changes. - /// - /// An expression specifying the property of each item to observe for changes. Must refer to a property of type - /// . - /// An observable sequence that produces a refresh notification each time the specified property changes on any item - /// in the source. + /// Validates a property expression and returns the source's change stream. + /// An expression specifying a property of . + /// The source's . /// Thrown if does not refer to a property. /// Thrown when source is null. - /// The returned observable emits a refresh change set for the entire source whenever the observed - /// property changes on any item. This is useful for scenarios where downstream consumers need to be notified of - /// property changes that may affect filtering, sorting, or other derived views. + /// This overload only validates that names a property and then returns the source's own + /// unchanged. It does not watch items for property changes. To receive refreshes, connect the source + /// with and use the change-set AutoRefresh overload. public IObservable> AutoRefresh(Expression> property) { -#if NET8_0_OR_GREATER - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(property); -#else - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - - if (property is null) - { - throw new ArgumentNullException(nameof(property)); - } -#endif + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(property); _ = (property.Body as MemberExpression)?.Member ?? throw new ArgumentException("Expression must be a property", nameof(property)); @@ -1058,6 +890,88 @@ public IObservable> AutoRefresh(Expression> prope } } + /// Applies a dynamic filter to one notification. + /// The item type. + /// The notification. + /// The current filter. + /// The notification to forward, or when the filter drops it. + /// + /// Additions, moves and refreshes pass when the item matches. Removals and clears always pass so downstream collections can drop items that + /// matched an earlier filter. An update becomes an update, an addition, a removal or nothing depending on whether the old and new items match. + /// + internal static CacheNotify? FilterNotification(CacheNotify notification, Func filter) + where T : notnull => + notification.Action switch + { + CacheAction.Cleared or CacheAction.Removed => notification, + CacheAction.Added or CacheAction.Moved or CacheAction.Refreshed => + notification.Item is not null && filter(notification.Item) ? notification : null, + CacheAction.Updated => FilterUpdate(notification, filter), + CacheAction.BatchAdded or CacheAction.BatchRemoved or CacheAction.BatchOperation or CacheAction.Reset when notification.Batch is not null => + NarrowBatch(notification, filter), + _ => null + }; + + /// Keeps the matching items of a batch notification and its action. + /// The item type. + /// The batch notification. + /// The predicate. + /// The original notification when every item matches, a narrowed copy when some do, or when none do. + /// The narrowed batch is a new array that the pipeline never returns to a pool. + internal static CacheNotify? NarrowBatch(CacheNotify notification, Func filter) + where T : notnull + { + // The predicate runs once per item, so an unstable or side-effecting predicate cannot disagree with itself. + var batch = notification.Batch!; + var kept = new T[batch.Count]; + var written = 0; + for (var i = 0; i < batch.Count; i++) + { + var item = batch.Items[i]; + if (!filter(item)) + { + continue; + } + + kept[written] = item; + written++; + } + + if (written == 0 && notification.Action != CacheAction.Reset) + { + return null; + } + + return written == batch.Count + ? notification + : new(notification.Action, default, new PooledBatch(kept, written, ReturnToPool: false)); + } + + /// Applies a dynamic filter to an update notification. + /// The item type. + /// The update notification. + /// The current filter. + /// The notification to forward, or when neither the old nor the new item matches. + internal static CacheNotify? FilterUpdate(CacheNotify notification, Func filter) + where T : notnull + { + var current = notification.Item; + var previous = notification.Previous; + var currentMatches = current is not null && filter(current); + var previousMatches = previous is not null && filter(previous); + if (currentMatches && previousMatches) + { + return notification; + } + + if (currentMatches) + { + return new(CacheAction.Added, current, null, notification.CurrentIndex); + } + + return previousMatches ? new(CacheAction.Removed, previous, null, notification.CurrentIndex) : null; + } + /// Filters the items in a batch notification based on a specified predicate. /// The type of items contained in the batch notification. Must be non-nullable. /// The batch notification containing the items to filter. diff --git a/src/ReactiveList/Views/DynamicFilteredReactiveView.cs b/src/ReactiveList/Views/DynamicFilteredReactiveView.cs index 7fbe3c36..fd476c88 100644 --- a/src/ReactiveList/Views/DynamicFilteredReactiveView.cs +++ b/src/ReactiveList/Views/DynamicFilteredReactiveView.cs @@ -7,23 +7,27 @@ 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}")] public sealed class DynamicFilteredReactiveView : IReadOnlyList, INotifyCollectionChanged, INotifyPropertyChanged, IReactiveView, T> where T : notnull { - /// Holds the synchronization gate and lazy notification relays for this facade. - private readonly FacadeRelayState _relays = new(); + /// The engine that owns filtering and the source subscription. + private readonly FilteredViewEngine _engine; + + /// The subscription to the filter observable. + private readonly IDisposable _filterSubscription; - /// Contains the mutable state and subscriptions owned by this view. - private readonly State _state; + /// Holds the synchronization gate and lazy notification relays for this facade, created when a handler is first added. + private FacadeRelayState? _relays; /// 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(filterObservable); - _state.Start(filterObservable, scheduler, throttle); + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(filterObservable); + ArgumentExceptionHelper.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(ref _relays, this, _engine.CollectionChanges, value); remove => FacadeNotificationHelper.RemoveCollectionChanged(_relays, value); } @@ -47,33 +55,43 @@ public event NotifyCollectionChangedEventHandler? CollectionChanged /// public event PropertyChangedEventHandler? PropertyChanged { - add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _state.PropertyChanges, value); + add => FacadeNotificationHelper.AddPropertyChanged(ref _relays, this, _engine.PropertyChanges, value); remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value); } + /// Gets or sets the size above which one applied batch raises a single reset instead of one notification per item. + /// The value is negative. + /// The default is , so every changed item raises its own notification. A larger batch updates the collection first and then raises one reset. + public int BatchResetLimit + { + get => _engine.Filtered.ResetLimit; + + set => _engine.Filtered.ResetLimit = ReactiveViewHelpers.CheckedResetLimit(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 +114,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/DynamicReactiveView.cs b/src/ReactiveList/Views/DynamicReactiveView.cs index 6bf36fea..0896c306 100644 --- a/src/ReactiveList/Views/DynamicReactiveView.cs +++ b/src/ReactiveList/Views/DynamicReactiveView.cs @@ -7,6 +7,7 @@ namespace ReactiveList.Reactive.Views; #else namespace ReactiveList.Views; #endif + /// /// Represents a dynamic, filtered, and observable view over a collection that updates in response to changes from an /// observable data stream and supports dynamically changing filter predicates. @@ -20,29 +21,20 @@ namespace ReactiveList.Views; /// when its contents are updated. Thread safety is provided for UI-bound scenarios by observing updates on the /// specified scheduler. [System.Diagnostics.DebuggerDisplay("DynamicReactiveView: {Items}")] -public class DynamicReactiveView : INotifyPropertyChanged, IReactiveView, T> +public sealed class DynamicReactiveView : INotifyPropertyChanged, IReactiveView, T> where T : notnull { - /// The mutable collection backing the public read-only view. - private readonly ObservableCollection _target = []; - - /// The source whose notifications update this view. - private readonly IReactiveSource _source; - - /// The subscriptions owned by this view. - private readonly MultipleDisposable _disposables = []; - - /// The sequencer used to marshal view updates. - private readonly ISequencer _scheduler; + /// The name of the property raised after the view changes. + private const string ItemsPropertyName = "Items"; - /// The interval over which source notifications are batched. - private readonly TimeSpan _throttle; + /// The projection that owns the collection and source subscription. + private readonly StreamProjection _projection; - /// The predicate currently applied to source items. - private Func _currentFilter = static _ => true; + /// The subscription to the filters. + private readonly IDisposable _filterSubscription; - /// The active subscription to the source notification stream. - private IDisposable? _streamSubscription; + /// Holds the synchronization gate and lazy notification relays for this facade, created when a handler is first added. + private FacadeRelayState? _relays; /// Indicates whether this view has been disposed. private int _disposedValue; @@ -67,41 +59,41 @@ public DynamicReactiveView(IReactiveSource source, IObservable> public DynamicReactiveView(IReactiveSource source, IObservable> filterObservable, TimeSpan throttle, ISequencer scheduler) #endif { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(filterObservable); - ThrowHelper.ThrowIfNull(scheduler); - - _source = source; - _throttle = throttle; - _scheduler = scheduler; - Items = new(_target); - - var initial = ReactiveViewHelpers.ProbeInitialValue(filterObservable); - if (initial.HasValue) - { - _currentFilter = initial.Value ?? (static _ => true); - } - - RebuildView(); - SubscribeToStream(); - - // Subscribe to subsequent filter changes with scheduler observation - var filterChanges = initial.HasValue ? filterObservable.Skip(1) : filterObservable; - _ = filterChanges - .ObserveOn(scheduler) - .Subscribe(newFilter => - { - _currentFilter = newFilter ?? (static _ => true); - RebuildView(); - SubscribeToStream(); - }).DisposeWith(_disposables); + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(filterObservable); + ArgumentExceptionHelper.ThrowIfNull(scheduler); + + // The first value only starts the view. The same observer then receives the live values, so no closure or wrapper is allocated. + DynamicFilterRelay relay = new(source); + filterObservable.Subscribe(relay).Dispose(); + _projection = new(source, static item => item, RulesFor(source, relay.Initial), ItemsPropertyName); + Items = _projection.Items; + _projection.StartFromSource(throttle, scheduler, quietFirstFill: true); + + relay.Attach(_projection); + _filterSubscription = filterObservable.ObserveOn(scheduler).Subscribe(relay); } /// Occurs when a property value changes. /// This event is typically raised by classes that implement the interface to notify clients, such as data-binding frameworks, that a property /// value has changed. - public event PropertyChangedEventHandler? PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged + { + add => FacadeNotificationHelper.AddPropertyChanged(ref _relays, this, _projection.PropertyChanges, value); + + remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value); + } + + /// Gets or sets the size above which one applied batch raises a single reset instead of one notification per item. + /// The value is negative. + /// The default is , so every changed item raises its own notification. A larger batch updates the collection first and then raises one reset. + public int BatchResetLimit + { + get => _projection.Target.ResetLimit; + + set => _projection.Target.ResetLimit = ReactiveViewHelpers.CheckedResetLimit(value); + } /// Gets a read-only, observable collection of items of type T. /// The collection reflects changes to the underlying data source and notifies observers of any @@ -134,136 +126,21 @@ public DynamicReactiveView ToProperty(out ReadOnlyObservableCollection col /// Call this method when you are finished using the object to release unmanaged resources and /// perform other cleanup operations. After calling Dispose, the object should not be used further. public void Dispose() - { - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - /// Releases the unmanaged resources used by the object and optionally releases the managed resources. - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - /// This method is called by public Dispose methods and the finalizer. When disposing is true, - /// this method releases all resources held by managed objects. When disposing is false, only unmanaged resources - /// are released. Override this method to release resources specific to the derived class. - protected virtual void Dispose(bool disposing) { if (Interlocked.Exchange(ref _disposedValue, 1) != 0) { return; } - if (!disposing) - { - return; - } - - _streamSubscription?.Dispose(); - _disposables.Dispose(); - } - - /// - /// Applies the specified cache change notification to the target collection, updating its contents based on the - /// action described. - /// - /// A cache notification describing the action to apply and the affected item or batch. Cannot be null. - private void ApplyChange(CacheNotify n) - { - if (n.Action is CacheAction.Added) - { - ReactiveViewHelpers.AddMatchingItem(_target, n.Item, _currentFilter); - } - else if (n.Action is CacheAction.Removed) - { - if (n.Item is not null) - { - _ = _target.Remove(n.Item); - } - } - else if (n.Action is CacheAction.Updated or CacheAction.Moved or CacheAction.Refreshed) - { - RebuildView(); - } - else if (n.Action is CacheAction.Cleared) - { - _target.Clear(); - } - else if (n.Action is CacheAction.BatchAdded) - { - ReactiveViewHelpers.AddMatchingBatch(_target, n.Batch, _currentFilter); - } - else if (n.Action is CacheAction.BatchRemoved) - { - ReactiveViewHelpers.RemoveBatch(_target, n.Batch); - } - } - - /// - /// Refreshes the view by reapplying the current filter to the source collection and updating the target collection - /// accordingly. - /// - /// Call this method to ensure that the target collection reflects the latest state of the source - /// collection and filter. This method also raises the PropertyChanged event for the Items property to notify - /// listeners of the update. - private void RebuildView() - { - _target.Clear(); - foreach (var item in _source) - { - if (_currentFilter(item)) - { - _target.Add(item); - } - } - - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Items))); + _filterSubscription?.Dispose(); + _projection.Dispose(); } - /// Subscribes to the data stream and updates the collection when new items are received. - /// Disposes any existing stream subscription before creating a new one. Updates to the - /// collection are batched and processed on the specified scheduler. Raises the PropertyChanged event for the Items - /// property after each batch is applied. - private void SubscribeToStream() - { - // Dispose previous subscription - _streamSubscription?.Dispose(); - - // Subscribe to stream with current filter - _streamSubscription = _source.Stream - .Buffer(_throttle) - .Keep(static b => b.Count > 0) - .ObserveOn(_scheduler) - .Subscribe(batch => - { - var requiresRebuild = false; - for (var i = 0; i < batch.Count; i++) - { - var action = batch[i].Action; - if (action is not (CacheAction.Updated or CacheAction.Moved or CacheAction.Refreshed or CacheAction.BatchOperation)) - { - continue; - } - - requiresRebuild = true; - break; - } - - if (requiresRebuild) - { - RebuildView(); - } - else - { - for (var i = 0; i < batch.Count; i++) - { - ApplyChange(batch[i]); - } - - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Items))); - } - - for (var i = 0; i < batch.Count; i++) - { - batch[i].Batch?.Dispose(); - } - }); - } + /// Builds the projection rules for a filter. + /// The source to filter. + /// The filter, or to include everything. + /// The rules. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static ProjectionRules RulesFor(IReactiveSource source, Func? filter) => + ViewSourceRules.Create(source, filter ?? (static _ => true)); } diff --git a/src/ReactiveList/Views/DynamicSecondaryIndexDictionaryReactiveView.cs b/src/ReactiveList/Views/DynamicSecondaryIndexDictionaryReactiveView.cs index 341f075e..b04b965d 100644 --- a/src/ReactiveList/Views/DynamicSecondaryIndexDictionaryReactiveView.cs +++ b/src/ReactiveList/Views/DynamicSecondaryIndexDictionaryReactiveView.cs @@ -7,6 +7,7 @@ namespace ReactiveList.Reactive.Views; #else namespace ReactiveList.Views; #endif + /// /// Provides a reactive view over a filtered by secondary index keys /// that can change dynamically. The view rebuilds when the key observable emits new keys. @@ -22,65 +23,76 @@ public sealed class DynamicSecondaryIndexDictionaryReactiveView : IReactiveView, KeyValuePair> where TKey : notnull { + /// The name of the property raised after the view changes. + private const string CountPropertyName = "Count"; + + /// Holds the synchronization gate and lazy notification relays for this facade. + private readonly FacadeRelayState _relays = new(); + /// The indexed dictionary whose changes feed this view. private readonly QuaternaryDictionary _source; /// The name of the secondary index queried by this view. private readonly string _indexName; - /// Retrieves values for a boxed secondary-index key. - private readonly Func, string, object, IEnumerable> _getValuesByIndex; - - /// Validates current membership when an indexed value is mutable. + /// Validates current membership for a boxed secondary-index key. private readonly Func, string, TValue, object, bool> _valueMatchesIndex; - /// The mutable collection backing the public read-only view. - private readonly ObservableCollection> _filteredItems; + /// The projection that owns the collection and source subscription. + private readonly StreamProjection, KeyValuePair> _projection; /// The subscriptions owned by this view. private readonly MultipleDisposable _disposables = []; - /// Serializes key changes and collection updates. - private readonly Lock _lock = new(); - - /// The secondary-index keys currently included in the view. - private HashSet _currentKeys = []; - - /// Indicates that reconciliation is delivering collection notifications. - private bool _rebuilding; - - /// Defers reentrant requests until the current reconciliation completes. - private bool _rebuildRequested; - /// Initializes a new instance of the class. /// The source dictionary to filter. /// The name of the secondary index. - /// The delegate used to retrieve values for a boxed secondary index key. /// The delegate used to validate current secondary-index membership. /// Thrown when source is . private DynamicSecondaryIndexDictionaryReactiveView( QuaternaryDictionary source, string indexName, - Func, string, object, IEnumerable> getValuesByIndex, Func, string, TValue, object, bool> valueMatchesIndex) { - _source = source ?? throw new ArgumentNullException(nameof(source)); - _indexName = indexName ?? throw new ArgumentNullException(nameof(indexName)); - _getValuesByIndex = getValuesByIndex ?? throw new ArgumentNullException(nameof(getValuesByIndex)); - _valueMatchesIndex = valueMatchesIndex ?? throw new ArgumentNullException(nameof(valueMatchesIndex)); - - _filteredItems = []; - Items = new(_filteredItems); + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(indexName); + ArgumentExceptionHelper.ThrowIfNull(valueMatchesIndex); + + _source = source; + _indexName = indexName; + _valueMatchesIndex = valueMatchesIndex; + _projection = new(source, static entry => entry, RulesFor([]), CountPropertyName, itemComparer: KeyValueItemComparer.Instance); + Items = _projection.Items; } /// - public event NotifyCollectionChangedEventHandler? CollectionChanged; + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add => FacadeNotificationHelper.AddCollectionChanged(_relays, this, _projection.CollectionChanges, value); + + remove => FacadeNotificationHelper.RemoveCollectionChanged(_relays, value); + } /// - public event PropertyChangedEventHandler? PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged + { + add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _projection.PropertyChanges, value); + + remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value); + } + + /// Gets or sets the size above which one applied batch raises a single reset instead of one notification per item. + /// The value is negative. + /// The default is , so every changed item raises its own notification. A larger batch updates the collection first and then raises one reset. + public int BatchResetLimit + { + get => _projection.Target.ResetLimit; + + set => _projection.Target.ResetLimit = ReactiveViewHelpers.CheckedResetLimit(value); + } /// Gets the number of items in the filtered view. - public int Count => _filteredItems.Count; + public int Count => _projection.Target.Count; /// Gets the underlying read-only observable collection for UI binding. public ReadOnlyObservableCollection> Items { get; } @@ -88,7 +100,7 @@ private DynamicSecondaryIndexDictionaryReactiveView( /// Gets the item at the specified index. /// The zero-based index of the item to get. /// The item at the specified index. - public KeyValuePair this[int index] => _filteredItems[index]; + public KeyValuePair this[int index] => _projection.Target[index]; /// Creates a typed instance of for dynamic secondary index keys. /// The type of the secondary index key. @@ -106,6 +118,9 @@ public static DynamicSecondaryIndexDictionaryReactiveView Create { var boxedKeys = new object[keys.Length]; @@ -119,7 +134,6 @@ public static DynamicSecondaryIndexDictionaryReactiveView Create( source, indexName, - static (dict, name, key) => dict.GetValuesBySecondaryIndex(name, (TIndexKey)key), static (dict, name, value, key) => dict.ValueMatchesSecondaryIndex(name, value, (TIndexKey)key)); view.Start(typedKeys, scheduler, throttle); return view; @@ -127,7 +141,7 @@ public static DynamicSecondaryIndexDictionaryReactiveView Create [MethodImpl(MethodImplOptions.AggressiveInlining)] - public IEnumerator> GetEnumerator() => _filteredItems.GetEnumerator(); + public IEnumerator> GetEnumerator() => _projection.Target.GetEnumerator(); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -136,10 +150,8 @@ public static DynamicSecondaryIndexDictionaryReactiveView CreateForces a rebuild of the filtered view from the source. public void Refresh() { - lock (_lock) - { - RebuildView(); - } + _projection.RequestResync(); + _projection.Drain(); } /// Assigns the current collection of items to a property using the specified setter action. @@ -165,154 +177,61 @@ public DynamicSecondaryIndexDictionaryReactiveView ToProperty(out /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Dispose() => _disposables.Dispose(); - - /// Initializes the view contents and activates its subscriptions. - /// An observable of key arrays to filter by. - /// The scheduler for dispatching updates. - /// The throttle duration for updates. - private void Start(IObservable keysObservable, ISequencer scheduler, TimeSpan throttle) + public void Dispose() { - ThrowHelper.ThrowIfNull(keysObservable); - - var initial = ReactiveViewHelpers.ProbeInitialValue(keysObservable); - _currentKeys = initial.Value?.ToHashSet() ?? []; - RebuildView(); - - // Subscribe to key changes (skip the first since we already processed it) - var keyChanges = initial.HasValue ? keysObservable.Skip(1) : keysObservable; - _ = keyChanges - .Subscribe(keys => - { - lock (_lock) - { - _currentKeys = keys is null ? [] : new HashSet(keys); - RebuildView(); - } - - OnPropertyChanged(nameof(Count)); - }) - .DisposeWith(_disposables); - - // Subscribe to source changes - var updates = _source.Stream.Map(static notification => notification.Action); - if (throttle > TimeSpan.Zero) - { - updates = updates.Throttle(throttle); - } - - _ = updates - .ObserveOn(scheduler) - .Subscribe(_ => OnSourceChanged()) - .DisposeWith(_disposables); - - // Forward collection changed events - _filteredItems.CollectionChanged += (_, e) => CollectionChanged?.Invoke(this, e); + _disposables.Dispose(); + _projection.Dispose(); } - /// Handles source change notifications. + /// Builds the projection rules for a set of boxed keys. + /// The keys to include. + /// The rules. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void OnSourceChanged() + private ProjectionRules> RulesFor(object[] keys) => + ViewSourceRules.Create( + _source, + entry => entry.Value is not null && MatchesAny(entry.Value, keys), + static (left, right) => EqualityComparer.Default.Equals(left.Key, right.Key)); + + /// Determines whether a value matches any of the keys. + /// The value to test. + /// The boxed keys. + /// when the value matches one of the keys. + private bool MatchesAny(TValue value, object[] keys) { - lock (_lock) + for (var i = 0; i < keys.Length; i++) { - RebuildView(); - } - - OnPropertyChanged(nameof(Count)); - } - - /// Rebuilds the view from the current source state. - private void RebuildView() - { - if (_rebuilding) - { - _rebuildRequested = true; - return; - } - - _rebuilding = true; - try - { - do - { - _rebuildRequested = false; - ReconcileSnapshot(); - } - while (_rebuildRequested); - } - finally - { - _rebuilding = false; - } - } - - /// Reconciles current indexed entries, preserving primary-key uniqueness and value identity. - private void ReconcileSnapshot() - { - var snapshot = CreateSnapshot(); - for (var index = 0; index < snapshot.Count; index++) - { - var item = snapshot[index]; - if (index == _filteredItems.Count) - { - _filteredItems.Add(item); - } - else if (!EqualityComparer.Default.Equals(_filteredItems[index].Key, item.Key) - || (typeof(TValue).IsValueType - ? !EqualityComparer.Default.Equals(_filteredItems[index].Value, item.Value) - : !ReferenceEquals(_filteredItems[index].Value, item.Value))) + if (_valueMatchesIndex(_source, _indexName, value, keys[i])) { - _filteredItems[index] = item; + return true; } } - while (_filteredItems.Count > snapshot.Count) - { - _filteredItems.RemoveAt(_filteredItems.Count - 1); - } + return false; } - /// Snapshots all matching indexed entries once per primary key. - /// The current matching dictionary entries. - private List> CreateSnapshot() + /// Applies the first key set, starts observing the source and follows later key changes. + /// An observable of key arrays to filter by. + /// The scheduler for dispatching updates. + /// The throttle duration for updates. + private void Start(IObservable keysObservable, ISequencer scheduler, TimeSpan throttle) { - List> snapshot = []; - HashSet addedKeys = []; - foreach (var indexKey in _currentKeys) + var initial = ReactiveViewHelpers.ProbeInitialValue(keysObservable); + if (initial.HasValue) { - foreach (var value in _getValuesByIndex(_source, _indexName, indexKey)) - { - if (value is null || !_valueMatchesIndex(_source, _indexName, value, indexKey)) - { - continue; - } - - AppendMatchingEntries(value, addedKeys, snapshot); - } + _projection.SetRules(RulesFor(initial.Value ?? [])); } - return snapshot; - } + _projection.StartFromSource(throttle, scheduler, quietFirstFill: true); - /// Adds dictionary entries associated with one indexed value. - /// The indexed value. - /// The primary keys already included. - /// The matching entries. - private void AppendMatchingEntries(TValue value, HashSet addedKeys, List> snapshot) - { - foreach (var item in _source) - { - if (EqualityComparer.Default.Equals(item.Value, value) && addedKeys.Add(item.Key)) - { - snapshot.Add(item); - } - } + var keyChanges = initial.HasValue ? keysObservable.Skip(1) : keysObservable; + _ = keyChanges + .Subscribe(OnKeysChanged) + .DisposeWith(_disposables); } - /// Handles property change notifications. - /// The propertyName value. + /// Applies a new set of keys and rebuilds the view. + /// The keys now included in the view. [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void OnPropertyChanged(string propertyName) => - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + private void OnKeysChanged(object[]? keys) => _projection.SetRules(RulesFor(keys ?? [])); } diff --git a/src/ReactiveList/Views/DynamicSecondaryIndexReactiveView.cs b/src/ReactiveList/Views/DynamicSecondaryIndexReactiveView.cs index 27505aff..7cc80774 100644 --- a/src/ReactiveList/Views/DynamicSecondaryIndexReactiveView.cs +++ b/src/ReactiveList/Views/DynamicSecondaryIndexReactiveView.cs @@ -7,6 +7,7 @@ namespace ReactiveList.Reactive.Views; #else namespace ReactiveList.Views; #endif + /// Provides a reactive view over a filtered by dynamically changing secondary-index keys. /// The type of items in the list. /// The type of the secondary index key. @@ -19,11 +20,23 @@ public sealed class DynamicSecondaryIndexReactiveView : where T : notnull where TKey : notnull { - /// Holds the synchronization gate and lazy notification relays for this facade. - private readonly FacadeRelayState _relays = new(); + /// The name of the property raised after the view changes. + private const string CountPropertyName = "Count"; + + /// The indexed list whose changes feed this view. + private readonly QuaternaryList _source; + + /// The name of the secondary index queried by this view. + private readonly string _indexName; - /// Contains the mutable state and subscriptions owned by this view. - private readonly State _state; + /// The projection that owns the collection and source subscription. + private readonly StreamProjection _projection; + + /// The subscription to the keys. + private readonly IDisposable _keySubscription; + + /// Holds the synchronization gate and lazy notification relays for this facade, created when a handler is first added. + private FacadeRelayState? _relays; /// Initializes a new instance of the class. /// The source list to filter. @@ -38,15 +51,27 @@ public DynamicSecondaryIndexReactiveView( ISequencer scheduler, TimeSpan throttle) { - _state = new(source, indexName); - ThrowHelper.ThrowIfNull(keysObservable); - _state.Start(keysObservable, scheduler, throttle); + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(indexName); + ArgumentExceptionHelper.ThrowIfNull(keysObservable); + ArgumentExceptionHelper.ThrowIfNull(scheduler); + + _source = source; + _indexName = indexName; + FirstValueRelay relay = new(); + keysObservable.Subscribe(relay).Dispose(); + _projection = new(source, static item => item, RulesFor(relay.Initial), CountPropertyName); + Items = _projection.Items; + _projection.StartFromSource(throttle, scheduler, quietFirstFill: true); + + relay.Attach(OnKeysChanged); + _keySubscription = keysObservable.Subscribe(relay); } /// public event NotifyCollectionChangedEventHandler? CollectionChanged { - add => FacadeNotificationHelper.AddCollectionChanged(_relays, this, _state.CollectionChanges, value); + add => FacadeNotificationHelper.AddCollectionChanged(ref _relays, this, _projection.CollectionChanges, value); remove => FacadeNotificationHelper.RemoveCollectionChanged(_relays, value); } @@ -54,25 +79,35 @@ public event NotifyCollectionChangedEventHandler? CollectionChanged /// public event PropertyChangedEventHandler? PropertyChanged { - add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _state.PropertyChanges, value); + add => FacadeNotificationHelper.AddPropertyChanged(ref _relays, this, _projection.PropertyChanges, value); remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value); } + /// Gets or sets the size above which one applied batch raises a single reset instead of one notification per item. + /// The value is negative. + /// The default is , so every changed item raises its own notification. A larger batch updates the collection first and then raises one reset. + public int BatchResetLimit + { + get => _projection.Target.ResetLimit; + + set => _projection.Target.ResetLimit = ReactiveViewHelpers.CheckedResetLimit(value); + } + /// Gets the number of items in the filtered view. - public int Count => _state.Count; + public int Count => _projection.Target.Count; /// Gets the underlying read-only observable collection for UI binding. - public ReadOnlyObservableCollection Items => _state.Items; + 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. - public T this[int index] => _state.GetItem(index); + public T this[int index] => _projection.Target[index]; /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public IEnumerator GetEnumerator() => _state.GetEnumerator(); + public IEnumerator GetEnumerator() => _projection.Target.GetEnumerator(); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -80,7 +115,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() => _projection.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. @@ -103,242 +138,40 @@ public DynamicSecondaryIndexReactiveView ToProperty(out ReadOnlyObserva /// [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 indexed list whose changes feed this view. - private readonly QuaternaryList _source; - - /// The name of the secondary index queried by this view. - private readonly string _indexName; - - /// The mutable collection backing the public read-only view. - private readonly ObservableCollection _filteredItems; - - /// The subscriptions owned by this view. - private readonly MultipleDisposable _disposables = []; - - /// Serializes key changes and collection updates. - private readonly Lock _lock = new(); - - /// Publishes property-change notifications when subscribed. - private readonly Signal _propertyChanges = new(); - - /// The secondary-index keys currently included in the view. - private HashSet _currentKeys = []; - - /// Initializes a new instance of the class. - /// The source list to filter. - /// The name of the secondary index. - /// Thrown when source or indexName is . - public State(QuaternaryList source, string indexName) - { - ThrowHelper.ThrowIfNull(source); - ThrowHelper.ThrowIfNull(indexName); - - _source = source; - _indexName = indexName; - _filteredItems = []; - 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 => _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) => _filteredItems[index]; - - /// Starts key and source subscriptions after this state is fully constructed. - /// An observable of key arrays to filter by. - /// The scheduler for dispatching source updates. - /// The throttle duration for source updates. - public void Start( - IObservable keysObservable, - ISequencer scheduler, - TimeSpan throttle) - { - var initial = ReactiveViewHelpers.ProbeInitialValue(keysObservable); - _currentKeys = initial.Value?.ToHashSet() ?? []; - RebuildView(); - - var keyChanges = initial.HasValue ? keysObservable.Skip(1) : keysObservable; - _ = keyChanges - .Subscribe(OnKeysChanged) - .DisposeWith(_disposables); - - _ = _source.Stream - .ThrottleNotifications(throttle) - .ObserveOn(scheduler) - .Subscribe(OnSourceChanged) - .DisposeWith(_disposables); - } - - /// Gets an enumerator over the filtered items. - /// An enumerator over the filtered items. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public IEnumerator GetEnumerator() => _filteredItems.GetEnumerator(); - - /// Rebuilds the view from the current source state. - public void Refresh() - { - lock (_lock) - { - RebuildView(); - } - } - - /// Stops the key and source subscriptions. - public void Dispose() - { - _disposables.Dispose(); - _propertyChanges.Dispose(); - } - - /// Handles a dynamic key change. - /// The keys now included in the view. - private void OnKeysChanged(TKey[] keys) - { - lock (_lock) - { - _currentKeys = keys?.ToHashSet() ?? []; - RebuildView(); - } - - EmitCountChanged(); - } - - /// Handles source change notifications. - /// The notification value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void OnSourceChanged(CacheNotify notification) - { - lock (_lock) - { - if (notification.Action is CacheAction.Added) - { - if (notification.Item is not null && ItemMatchesCurrentKeys(notification.Item)) - { - _filteredItems.Add(notification.Item); - } - } - else if (notification.Action is CacheAction.Removed) - { - if (notification.Item is not null) - { - _ = _filteredItems.Remove(notification.Item); - } - } - else if (notification.Action is CacheAction.Updated) - { - UpdateItem(notification); - } - else if (notification.Action is CacheAction.Cleared) - { - _filteredItems.Clear(); - } - else if (CacheActionHelper.RequiresIndexRebuild(notification.Action)) - { - RebuildView(); - } - } - - 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))); - } - } - - /// Updates an item and its membership in the current secondary-index view. - /// The update notification to apply. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void UpdateItem(CacheNotify notification) - { - var current = notification.Item; - if (current is null) - { - return; - } - - var previous = notification.Previous; - var existingIndex = previous is null - ? _filteredItems.IndexOf(current) - : _filteredItems.IndexOf(previous); - var shouldBeInView = ItemMatchesCurrentKeys(current); - - if (existingIndex < 0) - { - if (!shouldBeInView) - { - return; - } - - _filteredItems.Add(current); - return; - } - - if (!shouldBeInView) - { - _filteredItems.RemoveAt(existingIndex); - return; - } + _keySubscription.Dispose(); + _projection.Dispose(); + } - _filteredItems[existingIndex] = current; - } + /// Builds the projection rules for a set of keys. + /// The keys to include, or for none. + /// The rules. + private ProjectionRules RulesFor(TKey[]? keys) + { + var current = keys is null ? [] : new List(keys); + return ViewSourceRules.Create(_source, item => MatchesAny(current, item)); + } - /// Rebuilds the view from the current source state. - private void RebuildView() + /// Determines whether an item matches any of the keys. + /// The keys. + /// The item to test. + /// when the item matches one of the keys. + private bool MatchesAny(List keys, T item) + { + for (var i = 0; i < keys.Count; i++) { - _filteredItems.Clear(); - - foreach (var key in _currentKeys) + if (_source.ItemMatchesSecondaryIndex(_indexName, item, keys[i])) { - foreach (var item in _source.GetItemsBySecondaryIndex(_indexName, key)) - { - // Avoid duplicates if the same item matches multiple keys. - if (!_filteredItems.Contains(item)) - { - _filteredItems.Add(item); - } - } + return true; } } - /// Determines whether an item matches any current secondary-index key. - /// The item to test. - /// when the item matches a current key; otherwise, . - private bool ItemMatchesCurrentKeys(T item) - { - foreach (var key in _currentKeys) - { - if (_source.ItemMatchesSecondaryIndex(_indexName, item, key)) - { - return true; - } - } - - return false; - } + return false; } + + /// Applies a new set of keys and rebuilds the view. + /// The keys now included in the view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void OnKeysChanged(TKey[] keys) => _projection.SetRules(RulesFor(keys)); } diff --git a/src/ReactiveList/Views/FilteredReactiveView.cs b/src/ReactiveList/Views/FilteredReactiveView.cs index fef16b3e..62e5eed8 100644 --- a/src/ReactiveList/Views/FilteredReactiveView.cs +++ b/src/ReactiveList/Views/FilteredReactiveView.cs @@ -7,37 +7,39 @@ 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}")] public sealed class FilteredReactiveView : IReadOnlyList, INotifyCollectionChanged, INotifyPropertyChanged, IReactiveView, T> where T : notnull { - /// Holds the synchronization gate and lazy notification relays for this facade. - private readonly FacadeRelayState _relays = new(); + /// The engine that owns filtering and the source subscription. + private readonly FilteredViewEngine _engine; - /// The completed state object that owns filtering and source subscriptions. - private readonly State _state; + /// Holds the synchronization gate and lazy notification relays for this facade, created when a handler is first added. + private FacadeRelayState? _relays; /// 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(); + ArgumentExceptionHelper.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(ref _relays, this, _engine.CollectionChanges, value); remove => FacadeNotificationHelper.RemoveCollectionChanged(_relays, value); } @@ -45,25 +47,35 @@ public event NotifyCollectionChangedEventHandler? CollectionChanged /// public event PropertyChangedEventHandler? PropertyChanged { - add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _state.PropertyChanges, value); + add => FacadeNotificationHelper.AddPropertyChanged(ref _relays, this, _engine.PropertyChanges, value); remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value); } + /// Gets or sets the size above which one applied batch raises a single reset instead of one notification per item. + /// The value is negative. + /// The default is , so every changed item raises its own notification. A larger batch updates the collection first and then raises one reset. + public int BatchResetLimit + { + get => _engine.Filtered.ResetLimit; + + set => _engine.Filtered.ResetLimit = ReactiveViewHelpers.CheckedResetLimit(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 +83,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 +106,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..cab41d7a 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. @@ -19,31 +20,32 @@ public sealed class GroupedReactiveView : where T : notnull where TKey : notnull { - /// Holds the synchronization gate and lazy notification relays for this facade. - private readonly FacadeRelayState _relays = new(); + /// The engine that owns grouping and the source subscription. + private readonly GroupedViewEngine _engine; - /// The completed state object that owns grouping and source subscriptions. - private readonly State _state; + /// Holds the synchronization gate and lazy notification relays for this facade, created when a handler is first added. + private FacadeRelayState? _relays; /// 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(); + ArgumentExceptionHelper.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(ref _relays, this, _engine.CollectionChanges, value); remove => FacadeNotificationHelper.RemoveCollectionChanged(_relays, value); } @@ -51,48 +53,60 @@ public event NotifyCollectionChangedEventHandler? CollectionChanged /// public event PropertyChangedEventHandler? PropertyChanged { - add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _state.PropertyChanges, value); + add => FacadeNotificationHelper.AddPropertyChanged(ref _relays, this, _engine.PropertyChanges, value); remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value); } + /// Gets or sets the size above which one applied batch raises a single reset instead of one notification per item. + /// The value is negative. + /// The default is , so every changed item raises its own notification. + /// A larger batch updates the groups first and then raises one reset on the group collection and on each group that changed. + public int BatchResetLimit + { + get => _engine.ResetLimit; + + set => _engine.ResetLimit = ReactiveViewHelpers.CheckedResetLimit(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 +114,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 +139,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/ReactiveView.cs b/src/ReactiveList/Views/ReactiveView.cs index 0a1f8af2..9d41f8ea 100644 --- a/src/ReactiveList/Views/ReactiveView.cs +++ b/src/ReactiveList/Views/ReactiveView.cs @@ -7,76 +7,105 @@ namespace ReactiveList.Reactive.Views; #else namespace ReactiveList.Views; #endif + /// -/// Represents a dynamic, filtered, and observable view over a collection that updates in response to changes from an +/// Represents a filtered, observable view over a collection that updates in response to changes from an /// observable data stream. /// /// The type of items contained in the view. Must be non-nullable. -/// ReactiveView of T maintains a live, read-only collection that reflects both an initial snapshot and -/// ongoing changes from an observable source. The view automatically applies a filter to all items and batches updates -/// to optimize UI responsiveness. This class is designed for scenarios where a UI or other consumer needs to observe a -/// collection that changes over time, such as in MVVM applications. The view raises property change notifications when -/// its contents are updated. Thread safety is provided for UI-bound scenarios by observing updates on the current -/// synchronization context. +/// The view holds an initial snapshot plus ongoing changes from the source stream, applies a filter to every +/// item and batches updates. It raises property change notifications when its contents are updated. Item order follows +/// arrival order rather than source order. [System.Diagnostics.DebuggerDisplay("ReactiveView: {Items}")] -public class ReactiveView : INotifyPropertyChanged, IReactiveView, T> +public sealed class ReactiveView : INotifyPropertyChanged, IReactiveView, T> where T : notnull { - /// Holds the synchronization gate and lazy notification relays for this facade. - private readonly FacadeRelayState _relays = new(); + /// The name of the property raised after the view changes. + private const string ItemsPropertyName = "Items"; + + /// The projection that owns the collection and source subscription. + private readonly StreamProjection _projection; - /// The composed state that owns the collection and source subscription. - private readonly State _state; + /// Holds the synchronization gate and lazy notification relays for this facade, created when a handler is first added. + private FacadeRelayState? _relays; /// Indicates whether this view has been disposed. private int _disposedValue; - /// - /// Initializes a new instance of the class, providing a filtered, observable, and throttled view over. - /// a stream of cache notifications and an optional initial snapshot. - /// + /// Initializes a new instance of the class from a notification stream and an initial snapshot. /// An observable sequence of cache notifications to monitor for changes. Cannot be null. /// An optional initial collection of items to populate the view before processing the stream. Only items matching /// the filter are included. /// A predicate used to determine which items from the snapshot and stream are included in the view. Cannot be null. /// The time interval used to batch incoming notifications from the stream before processing. - /// The scheduler on which to observe and process batched notifications, typically used to marshal updates to the + /// The scheduler on which to observe and process batched notifications, typically used to marshal updates to the /// appropriate thread (such as the UI thread). /// Thrown if stream or filter is null. - /// The view is populated with items from the initial snapshot that satisfy the filter, and then - /// kept up to date by subscribing to the provided stream. Notifications from the stream are buffered according to - /// the specified throttle interval and processed on the given scheduler. This design helps reduce UI update - /// frequency and ensures thread-safe updates when used with UI frameworks. + /// Changes that land between taking the snapshot and subscribing are not seen, because a bare stream cannot + /// be rebuilt. Use a constructor that takes the source when that matters. #if NET8_0_OR_GREATER - public ReactiveView(IObservable> stream, IEnumerable snapshot, Func filter, in TimeSpan throttle, ISequencer sheduler) + public ReactiveView(IObservable> stream, IEnumerable snapshot, Func filter, in TimeSpan throttle, ISequencer scheduler) #else - public ReactiveView(IObservable> stream, IEnumerable snapshot, Func filter, TimeSpan throttle, ISequencer sheduler) + public ReactiveView(IObservable> stream, IEnumerable snapshot, Func filter, TimeSpan throttle, ISequencer scheduler) #endif { - ThrowHelper.ThrowIfNull(stream); - ThrowHelper.ThrowIfNull(filter); + ArgumentExceptionHelper.ThrowIfNull(stream); + ArgumentExceptionHelper.ThrowIfNull(filter); + + _projection = new(null, static item => item, new(filter, null, null), ItemsPropertyName); + Items = _projection.Items; + _projection.StartFromSnapshot(stream, snapshot, throttle, scheduler); + } + + /// + /// Initializes a new instance of the class that observes and + /// rebuilds itself from it whenever a notification cannot be applied exactly. + /// + /// The source to project. + /// A predicate used to determine which source items are included in the view. + /// The coalescing window for incoming notifications. + /// The scheduler on which notifications are applied. + /// Tells whether two items are the same source entry, for keyed sources whose updates do not name the replaced item. + /// Whether the facade reads the collection independently of the dispatcher. + internal ReactiveView(IReactiveSource source, Func filter, TimeSpan throttle, ISequencer scheduler, Func? sameEntry = null, bool synchronizeReads = false) + { + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(filter); - _state = new(snapshot, filter); - Items = _state.Items; - _state.Activate(stream, throttle, sheduler); + _projection = new(source, static item => item, ViewSourceRules.Create(source, filter, sameEntry), ItemsPropertyName, synchronizeReads); + Items = _projection.Items; + _projection.StartFromSource(throttle, scheduler, quietFirstFill: true); } /// Occurs when a property value changes. - /// This event is typically raised by classes that implement the interface to notify clients, such as data-binding frameworks, that a property - /// value has changed. public event PropertyChangedEventHandler? PropertyChanged { - add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _state.PropertyChanges, value); + add => FacadeNotificationHelper.AddPropertyChanged(ref _relays, this, _projection.PropertyChanges, value); remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value); } + /// Gets or sets the size above which one applied batch raises a single reset instead of one notification per item. + /// The value is negative. + /// The default is , so every changed item raises its own notification. A larger batch updates the collection first and then raises one reset. + public int BatchResetLimit + { + get => _projection.Target.ResetLimit; + + set => _projection.Target.ResetLimit = ReactiveViewHelpers.CheckedResetLimit(value); + } + /// Gets a read-only, observable collection of items of type T. /// The collection reflects changes to the underlying data source and notifies observers of any /// modifications. Items cannot be added to or removed from this collection directly. public ReadOnlyObservableCollection Items { get; } + /// Gets the underlying storage for the live-query facade. + internal BatchObservableCollection Storage => _projection.Target; + + /// Gets how many times the view rebuilt itself from its source instead of applying a notification. + internal int ResyncCount => _projection.ResyncCount; + /// 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. /// The current instance of to enable method chaining. @@ -90,9 +119,6 @@ public ReactiveView ToProperty(Action> proper /// Returns the current instance and assigns the underlying items collection to the specified output parameter. /// When the method returns, contains a read-only observable collection of items managed by this view. /// The current instance of . - /// This method provides direct access to the underlying items collection without modifying the - /// state of the view. The returned collection reflects the current contents and updates automatically as the view - /// changes. public ReactiveView ToProperty(out ReadOnlyObservableCollection collection) { collection = Items; @@ -100,222 +126,13 @@ public ReactiveView ToProperty(out ReadOnlyObservableCollection collection } /// Releases all resources used by the current instance of the class. - /// Call this method when you are finished using the object to release unmanaged resources and - /// perform other cleanup operations. After calling Dispose, the object should not be used further. public void Dispose() - { - // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - /// Releases the unmanaged resources used by the object and optionally releases the managed resources. - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - /// This method is called by public Dispose methods and the finalizer. When disposing is true, - /// this method releases all resources held by managed objects. When disposing is false, only unmanaged resources - /// are released. Override this method to release resources specific to the derived class. - protected virtual void Dispose(bool disposing) { if (Interlocked.Exchange(ref _disposedValue, 1) != 0) { return; } - if (disposing) - { - _state.Dispose(); - } - } - - /// Owns the mutable data and active subscription used by the facade. - private sealed class State : IDisposable - { - /// The predicate applied to snapshot items and source notifications. - private readonly Func _filter; - - /// The mutable collection backing the public read-only view. - private readonly ObservableCollection _target = []; - - /// Publishes property-change notifications when subscribed. - private readonly Signal _propertyChanges = new(); - - /// The subscription that feeds source notifications into this state. - private IDisposable? _subscription; - - /// Initializes a new instance of the class from a snapshot. - /// The initial items to filter into the view. - /// The predicate that controls view membership. - internal State(IEnumerable snapshot, Func filter) - { - _filter = filter; - Items = new(_target); - - if (snapshot is null) - { - return; - } - - foreach (var item in snapshot) - { - if (filter(item)) - { - _target.Add(item); - } - } - } - - /// Gets the observable stream of property-change notifications. - internal IObservable PropertyChanges => _propertyChanges; - - /// Gets the read-only collection exposed by the facade. - internal ReadOnlyObservableCollection Items { get; } - - /// Disposes the active source subscription and property signal. - public void Dispose() - { - _subscription?.Dispose(); - _propertyChanges.Dispose(); - } - - /// Subscribes this fully initialized state to the source stream. - /// The source notification stream. - /// The interval over which notifications are buffered. - /// The scheduler on which buffered notifications are observed. -#if NET8_0_OR_GREATER - internal void Activate(IObservable> stream, in TimeSpan throttle, ISequencer scheduler) => -#else - internal void Activate(IObservable> stream, TimeSpan throttle, ISequencer scheduler) => -#endif - _subscription = stream - .Buffer(throttle) - .Keep(static batch => batch.Count > 0) - .ObserveOn(scheduler) - .Subscribe(HandleBatch); - - /// Processes a buffered source batch and returns any pooled payloads. - /// The buffered notifications to process. - private void HandleBatch(IList> batch) - { - foreach (var notification in batch) - { - ApplyChange(notification); - notification.Batch?.Dispose(); - } - - if (_propertyChanges.HasObservers) - { - _propertyChanges.OnNext(new(nameof(Items))); - } - } - - /// Applies one cache notification to the target collection. - /// The notification describing the change to apply. - private void ApplyChange(CacheNotify notification) - { - if (notification.Action is CacheAction.Added) - { - ReactiveViewHelpers.AddMatchingItem(_target, notification.Item, _filter); - } - else if (notification.Action is CacheAction.Removed) - { - if (notification.Item is not null) - { - _ = _target.Remove(notification.Item); - } - } - else if (notification.Action is CacheAction.Updated) - { - UpdateItem(notification); - } - else if (notification.Action is CacheAction.Refreshed) - { - RefreshItem(notification.Item); - } - else if (notification.Action is CacheAction.Cleared) - { - _target.Clear(); - } - else if (notification.Action is CacheAction.BatchOperation or CacheAction.BatchAdded) - { - ReactiveViewHelpers.AddMatchingBatch(_target, notification.Batch, _filter); - } - else if (notification.Action is CacheAction.BatchRemoved) - { - ReactiveViewHelpers.RemoveBatch(_target, notification.Batch); - } - } - - /// Updates an item and its membership in the filtered view. - /// The update notification. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void UpdateItem(CacheNotify notification) - { - var previous = notification.Previous; - var current = notification.Item; - var existingIndex = -1; - if (previous is not null) - { - existingIndex = _target.IndexOf(previous); - } - else if (current is not null) - { - existingIndex = _target.IndexOf(current); - } - - if (current is null || !_filter(current)) - { - if (existingIndex >= 0) - { - _target.RemoveAt(existingIndex); - } - - return; - } - - if (existingIndex < 0) - { - // Without a previous value there is no reliable way to identify and remove the item being replaced. - // Preserve the current view rather than appending a potentially duplicate or stale replacement. - if (previous is not null) - { - _target.Add(current); - } - - return; - } - - _target[existingIndex] = current; - } - - /// Re-evaluates one item against the view filter. - /// The refreshed item. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void RefreshItem(T? item) - { - if (item is null) - { - return; - } - - var existingIndex = _target.IndexOf(item); - var shouldInclude = _filter(item); - if (existingIndex < 0) - { - if (!shouldInclude) - { - return; - } - - _target.Add(item); - return; - } - - if (shouldInclude) - { - return; - } - - _target.RemoveAt(existingIndex); - } + _projection.Dispose(); } } diff --git a/src/ReactiveList/Views/SecondaryIndexReactiveView.cs b/src/ReactiveList/Views/SecondaryIndexReactiveView.cs index deca3604..b71c7bd0 100644 --- a/src/ReactiveList/Views/SecondaryIndexReactiveView.cs +++ b/src/ReactiveList/Views/SecondaryIndexReactiveView.cs @@ -7,6 +7,7 @@ namespace ReactiveList.Reactive.Views; #else namespace ReactiveList.Views; #endif + /// /// Provides a reactive view over a filtered by a secondary index key. /// The view automatically updates when the source dictionary changes. @@ -18,62 +19,59 @@ public sealed class SecondaryIndexReactiveView : IReadOnlyList, TValue> where TKey : notnull { - /// The dictionary that supplies items to this view. - private readonly QuaternaryDictionary _source; - - /// The name of the secondary index used to filter items. - private readonly string _indexName; - - /// The secondary index key used to filter items. - private readonly object _indexKey; - - /// Retrieves the values matching a secondary index key. - private readonly Func, string, object, IEnumerable> _getValuesByIndex; - - /// Determines whether a value matches a secondary index key. - private readonly Func, string, TValue, object, bool> _valueMatchesIndex; - - /// The mutable collection that backs the read-only filtered items collection. - private readonly ObservableCollection _filteredItems; + /// The name of the property raised after the view changes. + private const string CountPropertyName = "Count"; - /// The subscriptions owned by this view. - private readonly MultipleDisposable _disposables = []; + /// The projection that owns the collection and source subscription. + private readonly StreamProjection, TValue> _projection; - /// Synchronizes access to the filtered items collection. - private readonly Lock _lock = new(); + /// Holds the synchronization gate and lazy notification relays for this facade, created when a handler is first added. + private FacadeRelayState? _relays; /// Initializes a new instance of the class. /// The source dictionary to filter. - /// The name of the secondary index. - /// The secondary index key (boxed) to filter on. - /// The delegate used to retrieve values for a boxed secondary index key. - /// The delegate used to test whether a value matches a boxed secondary index key. + /// Determines whether a value belongs in the view. /// Thrown when source is . - private SecondaryIndexReactiveView( - QuaternaryDictionary source, - string indexName, - object indexKey, - Func, string, object, IEnumerable> getValuesByIndex, - Func, string, TValue, object, bool> valueMatchesIndex) + private SecondaryIndexReactiveView(QuaternaryDictionary source, Func matches) { - _source = source ?? throw new ArgumentNullException(nameof(source)); - _indexName = indexName ?? throw new ArgumentNullException(nameof(indexName)); - _indexKey = indexKey; - _getValuesByIndex = getValuesByIndex ?? throw new ArgumentNullException(nameof(getValuesByIndex)); - _valueMatchesIndex = valueMatchesIndex ?? throw new ArgumentNullException(nameof(valueMatchesIndex)); - - _filteredItems = []; - Items = new(_filteredItems); + ArgumentExceptionHelper.ThrowIfNull(source); + + _projection = new( + source, + static entry => entry.Value, + ViewSourceRules.Create(source, static entry => entry.Value, matches), + CountPropertyName); + Items = _projection.Items; } /// - public event NotifyCollectionChangedEventHandler? CollectionChanged; + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add => FacadeNotificationHelper.AddCollectionChanged(ref _relays, this, _projection.CollectionChanges, value); + + remove => FacadeNotificationHelper.RemoveCollectionChanged(_relays, value); + } /// - public event PropertyChangedEventHandler? PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged + { + add => FacadeNotificationHelper.AddPropertyChanged(ref _relays, this, _projection.PropertyChanges, value); + + remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value); + } + + /// Gets or sets the size above which one applied batch raises a single reset instead of one notification per item. + /// The value is negative. + /// The default is , so every changed item raises its own notification. A larger batch updates the collection first and then raises one reset. + public int BatchResetLimit + { + get => _projection.Target.ResetLimit; + + set => _projection.Target.ResetLimit = ReactiveViewHelpers.CheckedResetLimit(value); + } /// Gets the number of items in the filtered view. - public int Count => _filteredItems.Count; + public int Count => _projection.Target.Count; /// Gets the underlying read-only observable collection for UI binding. public ReadOnlyObservableCollection Items { get; } @@ -81,7 +79,7 @@ private SecondaryIndexReactiveView( /// Gets the item at the specified index. /// The zero-based index of the item to get. /// The item at the specified index. - public TValue this[int index] => _filteredItems[index]; + public TValue this[int index] => _projection.Target[index]; /// Creates a typed instance of for a secondary index key. /// The type of the secondary index key. @@ -99,19 +97,19 @@ public static SecondaryIndexReactiveView Create( TimeSpan throttle) where TIndexKey : notnull { + ArgumentExceptionHelper.ThrowIfNull(source); + ArgumentExceptionHelper.ThrowIfNull(indexName); + var view = new SecondaryIndexReactiveView( source, - indexName, - indexKey, - static (dict, name, key) => dict.GetValuesBySecondaryIndex(name, (TIndexKey)key), - static (dict, name, value, key) => dict.ValueMatchesSecondaryIndex(name, value, (TIndexKey)key)); - view.Start(scheduler, throttle); + value => value is not null && source.ValueMatchesSecondaryIndex(indexName, value, indexKey)); + view._projection.StartFromSource(throttle, scheduler, quietFirstFill: true); return view; } /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public IEnumerator GetEnumerator() => _filteredItems.GetEnumerator(); + public IEnumerator GetEnumerator() => _projection.Target.GetEnumerator(); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -120,10 +118,8 @@ public static SecondaryIndexReactiveView Create( /// Forces a rebuild of the filtered view from the source. public void Refresh() { - lock (_lock) - { - RebuildView(); - } + _projection.RequestResync(); + _projection.Drain(); } /// Assigns the current collection of items to a property using the specified setter action. @@ -134,7 +130,7 @@ public void Refresh() /// as a view model property, in a reactive UI pattern. public SecondaryIndexReactiveView ToProperty(Action> propertySetter) { - ThrowHelper.ThrowIfNull(propertySetter); + ArgumentExceptionHelper.ThrowIfNull(propertySetter); propertySetter(Items); return this; } @@ -150,91 +146,5 @@ public SecondaryIndexReactiveView ToProperty(out ReadOnlyObservabl /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Dispose() => _disposables.Dispose(); - - /// Initializes the view contents and activates its subscriptions. - /// The scheduler for dispatching updates. - /// The throttle duration for updates. - private void Start(ISequencer scheduler, TimeSpan throttle) - { - // Initialize with current matching items - RebuildView(); - - // Subscribe to changes - var subscription = _source.Stream - .ThrottleNotifications(throttle) - .ObserveOn(scheduler) - .Subscribe(OnSourceChanged); - - _disposables.Add(subscription); - - // Forward collection changed events - _filteredItems.CollectionChanged += (_, e) => CollectionChanged?.Invoke(this, e); - } - - /// Handles source change notifications. - /// The notification value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void OnSourceChanged(CacheNotify> notification) - { - lock (_lock) - { - if (notification.Action is CacheAction.Added) - { - AddItem(notification.Item.Value); - } - else if (notification.Action is CacheAction.Removed) - { - if (notification.Item.Value is not null) - { - _ = _filteredItems.Remove(notification.Item.Value); - } - } - else if (notification.Action is CacheAction.Updated) - { - if (notification.Item.Value is not null) - { - RebuildView(); - } - } - else if (notification.Action is CacheAction.Cleared) - { - _filteredItems.Clear(); - } - else if (CacheActionHelper.RequiresIndexRebuild(notification.Action)) - { - RebuildView(); - } - } - - OnPropertyChanged(nameof(Count)); - } - - /// Adds an item when its value matches the selected secondary-index key. - /// The value to consider. - private void AddItem(TValue? value) - { - if (value is null || !_valueMatchesIndex(_source, _indexName, value, _indexKey)) - { - return; - } - - _filteredItems.Add(value); - } - - /// Rebuilds the view from the current source state. - private void RebuildView() - { - _filteredItems.Clear(); - foreach (var value in _getValuesByIndex(_source, _indexName, _indexKey)) - { - _filteredItems.Add(value); - } - } - - /// Handles property change notifications. - /// The propertyName value. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void OnPropertyChanged(string propertyName) => - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + public void Dispose() => _projection.Dispose(); } diff --git a/src/ReactiveList/Views/SortedReactiveView.cs b/src/ReactiveList/Views/SortedReactiveView.cs index 70e94723..64f49589 100644 --- a/src/ReactiveList/Views/SortedReactiveView.cs +++ b/src/ReactiveList/Views/SortedReactiveView.cs @@ -7,37 +7,39 @@ 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}")] public sealed class SortedReactiveView : IReadOnlyList, INotifyCollectionChanged, INotifyPropertyChanged, IReactiveView, T> where T : notnull { - /// Holds the synchronization gate and lazy notification relays for this facade. - private readonly FacadeRelayState _relays = new(); + /// The engine that owns sorting and the source subscription. + private readonly SortedViewEngine _engine; - /// The completed state object that owns sorting and source subscriptions. - private readonly State _state; + /// Holds the synchronization gate and lazy notification relays for this facade, created when a handler is first added. + private FacadeRelayState? _relays; /// 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(); + ArgumentExceptionHelper.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(ref _relays, this, _engine.CollectionChanges, value); remove => FacadeNotificationHelper.RemoveCollectionChanged(_relays, value); } @@ -45,25 +47,35 @@ public event NotifyCollectionChangedEventHandler? CollectionChanged /// public event PropertyChangedEventHandler? PropertyChanged { - add => FacadeNotificationHelper.AddPropertyChanged(_relays, this, _state.PropertyChanges, value); + add => FacadeNotificationHelper.AddPropertyChanged(ref _relays, this, _engine.PropertyChanges, value); remove => FacadeNotificationHelper.RemovePropertyChanged(_relays, value); } + /// Gets or sets the size above which one applied batch raises a single reset instead of one notification per item. + /// The value is negative. + /// The default is , so every changed item raises its own notification. A larger batch updates the collection first and then raises one reset. + public int BatchResetLimit + { + get => _engine.Sorted.ResetLimit; + + set => _engine.Sorted.ResetLimit = ReactiveViewHelpers.CheckedResetLimit(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 +83,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 +106,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..31071a0a 100644 --- a/src/ReactiveList/Views/ViewChangeBuffer.cs +++ b/src/ReactiveList/Views/ViewChangeBuffer.cs @@ -8,200 +8,703 @@ 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 { + /// The batch size above which a positionless removal finds its items with one pass over the mirror. + private const int OnePassMinimum = 8; + /// 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 source mirrored by . + private readonly IReactiveSource _source; + + /// Whether the source publishes each change with its version, so the mirror never needs a confirming copy. + private readonly bool _versioned; + + /// Whether the source declares that items cannot change in place. + private readonly bool _ignoreRefreshes; + + /// The notifications retained until the view drains them, created when the first one has to wait. + private Queue>? _pending; + + /// The number of retained notifications, readable without the lock. + private int _pendingCount; + + /// The notification handed straight to the consuming drain, or . Only the consuming thread touches it. + private CacheNotify? _inline; + + /// The source revision of . + private long _inlineVersion; /// 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 more than one batch is unverified, which needs a full comparison instead of a range check. + private bool _verifyFull; + + /// The first mirror index of the range inserted by the unverified batch. + private int _verifyStart; + + /// The length of the range inserted by the unverified batch, or zero for a removal. + private int _verifyLength; + + /// 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. + /// Whether to copy the source now, or leave that to the caller once it is subscribed. + internal ViewChangeBuffer(IReactiveSource source, bool takeSnapshot = true) + { + ArgumentExceptionHelper.ThrowIfNull(source); + _source = source; + _versioned = source is IVersionedSnapshotSource; + _ignoreRefreshes = source is IReactiveSourceWithOptions { Options.ItemsAreImmutable: true }; + if (takeSnapshot) + { + 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. - internal bool HasPending + /// Gets whether notifications remain to be consumed. + internal bool HasPending => Volatile.Read(ref _pendingCount) != 0; + + /// Hands a notification straight to the consuming drain, skipping the queue and its lock. + /// The source notification. + /// The source revision that produced the notification. + /// Only the thread that owns the drain may call this, and only while nothing is retained, so the delivery order holds. + internal void SetInline(CacheNotify notification, long version) + { + _inline = notification; + _inlineVersion = version; + } + + /// Returns the pooled batch of a notification that was handed to the drain but never applied. + internal void ReleaseInline() + { + _inline?.Batch?.Dispose(); + _inline = null; + } + + /// 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) { - get + lock (_gate) { - lock (_gate) + if (!_disposed) { - return _pending.Count > 0; + var pending = _pending ??= new(); + pending.Enqueue(new(notification, version)); + Volatile.Write(ref _pendingCount, pending.Count); + return true; } } + + notification.Batch?.Dispose(); + return false; } - /// Finds an occurrence, preferring reference identity over value equality. - /// The collection to search. - /// The occurrence to locate. - /// The matching index, or -1. - internal static int FindIndex(IEnumerable items, T item) + /// 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 { - var index = 0; - var equalIndex = -1; - foreach (var candidate in items) + if (!TryTake(out var pending)) { - if (!typeof(T).IsValueType && ReferenceEquals(candidate, item)) - { - return index; - } + return false; + } + + try + { + Apply(pending, sink); + } + finally + { + pending.Notification.Batch?.Dispose(); + } + + return true; + } + + /// Replaces the mirror with a consistent snapshot of the source and excludes already covered queued notifications. + internal void Reset() + { + var (snapshot, version) = ViewSourceRules.ReadVersioned(_source); + + lock (_gate) + { + _coveredVersion = version; + } + + _appliedVersion = version; + _verifyPending = false; + _verifyFull = 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 + { + // Versioned notifications are applied exactly once on top of a consistent copy, so there is nothing to confirm. + if (!_verifyPending || _versioned) + { + return; + } + + var version = _source.Version; + if (version != _appliedVersion) + { + return; + } - if (equalIndex < 0 && EqualityComparer.Default.Equals(candidate, item)) + if (!_verifyFull && _source is IReadOnlyList list && ConfirmsBatch(list)) + { + if (version == _source.Version) { - equalIndex = index; + _verifyPending = false; } - index++; + return; + } + + var snapshot = ViewSourceRules.ReadSource(_source); + if (version != _source.Version) + { + return; } - return equalIndex; + _verifyPending = false; + _verifyFull = false; + if (MatchesMirror(snapshot)) + { + return; + } + + ResetFromSource(sink); } - /// 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) + /// Drops every retained notification and stops accepting new ones. + internal void Dispose() { lock (_gate) { - _pending.Enqueue((changes, version)); - } + _disposed = true; + while (_pending is { Count: > 0 } pending) + { + pending.Dequeue().Notification.Batch?.Dispose(); + } - return true; + Volatile.Write(ref _pendingCount, 0); + } } - /// 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) + /// Takes the next notification not already represented by an explicit snapshot, starting with the one handed straight to the drain. + /// The retained notification. + /// Whether a notification was available. + private bool TryTake(out PendingNotification pending) { + if (_inline is { } inline) + { + _inline = null; + if (_inlineVersion > Volatile.Read(ref _coveredVersion)) + { + pending = new(inline, _inlineVersion); + return true; + } + + inline.Batch?.Dispose(); + } + + if (Volatile.Read(ref _pendingCount) == 0) + { + pending = default; + return false; + } + lock (_gate) { - while (_pending.Count > 0) + while (_pending is { Count: > 0 } pendingQueue) { - var pending = _pending.Dequeue(); - if (pending.Version <= _coveredVersion) + var candidate = pendingQueue.Dequeue(); + Volatile.Write(ref _pendingCount, pendingQueue.Count); + 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 { - var version = source.Version; - List snapshot = [.. source]; - while (version != source.Version) + var notification = pending.Notification; + _appliedVersion = pending.Version; + var applied = notification.Action switch { - version = source.Version; - snapshot = [.. source]; + CacheAction.Added => ApplyAdded(notification, sink), + CacheAction.Removed => ApplyRemoved(notification, sink), + CacheAction.Updated => ApplyUpdated(notification, sink), + CacheAction.Moved => ApplyMoved(notification, sink), + CacheAction.Refreshed => _ignoreRefreshes || ApplyRefreshed(notification, sink), + CacheAction.Cleared => ApplyCleared(sink), + CacheAction.Reset => ApplyReset(notification.Batch, sink), + CacheAction.BatchAdded => ApplyBatchAdded(notification, sink), + CacheAction.BatchRemoved => ApplyBatchRemoved(notification, sink), + _ => false + }; + + if (!applied) + { + ResetFromSource(sink); } + } - lock (_gate) + /// Replaces the mirror with the exact contents of a reset batch. + /// The sink type. + /// The source snapshot. + /// The sink that receives structural changes. + /// Whether the reset carried a snapshot. + private bool ApplyReset(PooledBatch? batch, TSink sink) + where TSink : IViewMirrorSink + { + if (batch is null) { - _coveredVersion = version; + return false; } Items.Clear(); - Items.AddRange(snapshot); + for (var i = 0; i < batch.Count; i++) + { + Items.Add(batch.Items[i]); + } + + sink.MirrorReset(); + return true; } - /// Applies a structural change to the logical source order. - /// The change to consume. - internal void Apply(Change change) + /// Applies a single add. + /// The sink type. + /// The notification. + /// The sink. + /// Whether the mirror stayed consistent. + private bool ApplyAdded(CacheNotify notification, TSink sink) + where TSink : IViewMirrorSink { - if (change.Reason is ChangeReason.Add) + if (notification.Item is not { } item) { - var index = change.CurrentIndex; - Items.Insert(index >= 0 && index <= Items.Count ? index : Items.Count, change.Current); + return false; } - else if (change.Reason is ChangeReason.Remove) + + var index = notification.CurrentIndex; + if (index < 0 || index > Items.Count) { - RemoveItem(change); + index = Items.Count; } - else if (change.Reason is ChangeReason.Update) + + Items.Insert(index, item); + sink.ItemsInserted(index, 1); + return true; + } + + /// Applies a single removal. + /// The sink type. + /// The notification. + /// The sink. + /// Whether the mirror stayed consistent. + private bool ApplyRemoved(CacheNotify notification, TSink sink) + where TSink : IViewMirrorSink + { + if (notification.Item is not { } item) { - UpdateItem(change); + return false; } - else if (change.Reason is ChangeReason.Move) + + var index = LocateIndex(notification.CurrentIndex, item); + if (index < 0) + { + return false; + } + + Items.RemoveAt(index); + sink.ItemRemoved(index, item); + return true; + } + + /// Applies a single replacement. + /// The sink type. + /// The notification. + /// The sink. + /// Whether the mirror stayed consistent. + private bool ApplyUpdated(CacheNotify notification, TSink sink) + where TSink : IViewMirrorSink + { + if (notification.Item is not { } current || notification.Previous is not { } previous) { - MoveItem(change); + return false; } - else if (change.Reason is ChangeReason.Clear) + + var index = LocateIndex(notification.CurrentIndex, previous); + if (index < 0) + { + return false; + } + + Items[index] = current; + sink.ItemReplaced(index, previous, current); + return true; + } + + /// Applies a single move. + /// The sink type. + /// The notification. + /// The sink. + /// Whether the mirror stayed consistent. + private bool ApplyMoved(CacheNotify notification, TSink sink) + where TSink : IViewMirrorSink + { + var oldIndex = notification.PreviousIndex; + var newIndex = notification.CurrentIndex; + if (oldIndex < 0 || oldIndex >= Items.Count || newIndex < 0 || newIndex >= Items.Count) { - Items.Clear(); + return false; } + + var item = Items[oldIndex]; + Items.RemoveAt(oldIndex); + Items.Insert(newIndex, item); + sink.ItemMoved(oldIndex, newIndex, item); + return true; } - /// Removes one occurrence from the source mirror. - /// The removal to apply. - private void RemoveItem(Change change) + /// Applies a single in-place refresh. + /// The sink type. + /// The notification. + /// The sink. + /// Whether the mirror stayed consistent. + private bool ApplyRefreshed(CacheNotify notification, TSink sink) + where TSink : IViewMirrorSink { - var index = change.PreviousIndex; - if (index < 0 || index >= Items.Count) + if (notification.Item is not { } item) { - index = FindIndex(Items, change.Current); + return false; } + var index = LocateIndex(notification.CurrentIndex, item); if (index < 0) { - return; + return false; } - Items.RemoveAt(index); + sink.ItemRefreshed(index, item); + return true; } - /// Replaces an occurrence in the source mirror. - /// The update to apply. - private void UpdateItem(Change change) + /// Applies a clear. + /// The sink type. + /// The sink. + /// Always . + private bool ApplyCleared(TSink sink) + where TSink : IViewMirrorSink { - var index = change.CurrentIndex; - if (index < 0 || index >= Items.Count) + Items.Clear(); + sink.MirrorCleared(); + return true; + } + + /// Applies a range add. + /// The sink type. + /// The notification. + /// The sink. + /// Whether the batch carried its items. + private bool ApplyBatchAdded(CacheNotify notification, TSink sink) + where TSink : IViewMirrorSink + { + if (notification.Batch is not { } batch) { - index = change.Previous is null ? -1 : FindIndex(Items, change.Previous); + return false; } - if (index < 0) + var index = notification.CurrentIndex; + if (index < 0 || index > Items.Count) { - return; + index = Items.Count; + } + + Items.InsertRange(index, new ArraySegment(batch.Items, 0, batch.Count)); + MarkUnverified(index, batch.Count); + sink.BatchStarted(batch.Count); + try + { + sink.ItemsInserted(index, batch.Count); + } + finally + { + sink.BatchEnded(); + } + + return true; + } + + /// Applies a range removal by removing each carried item from the mirror. + /// The sink type. + /// The notification. + /// The sink. + /// Whether the batch carried its items and the mirror held every one. + private bool ApplyBatchRemoved(CacheNotify notification, TSink sink) + where TSink : IViewMirrorSink + { + if (notification.Batch is not { } batch) + { + return false; + } + + var start = notification.CurrentIndex; + if (start >= 0 && !MatchesRemovalRange(start, batch)) + { + return false; + } + + return (start < 0 && batch.Count > OnePassMinimum && TryRemoveInOnePass(batch, sink)) + || RemoveOneByOne(batch, start, sink); + } + + /// Removes each carried item from the mirror with its own search, or at the named position. + /// The sink type. + /// The removed items. + /// The mirror index of every removal, or a negative value to search for each item. + /// The sink that receives the structural changes. + /// Whether the mirror held every item. + private bool RemoveOneByOne(PooledBatch batch, int start, TSink sink) + where TSink : IViewMirrorSink + { + var ambiguous = false; + sink.BatchStarted(batch.Count); + try + { + for (var i = 0; i < batch.Count; i++) + { + var item = batch.Items[i]; + var index = start >= 0 ? start : ItemComparison.FindIndex(Items, item); + if (index < 0) + { + return false; + } + + // Legacy notifications without positions may have removed a later equal item. + ambiguous |= !_versioned && start < 0 && HasAnotherOccurrence(index, item); + Items.RemoveAt(index); + sink.ItemRemoved(index, item); + } + } + finally + { + sink.BatchEnded(); + } + + MarkUnverified(0, 0); + _verifyFull |= ambiguous; + return true; + } + + /// + /// Removes the earliest occurrence of every carried item with a single pass over the mirror instead of one search per item. + /// Nothing changes when an item is not found by identity, so the caller can fall back to the searching path. + /// + /// The sink type. + /// The removed items. + /// The sink that receives the structural changes. + /// when every item was found and removed. + private bool TryRemoveInOnePass(PooledBatch batch, TSink sink) + where TSink : IViewMirrorSink + { + var removedAt = new int[batch.Count]; + + // Legacy sources may have removed a later equal item, which only a full comparison with the source can tell. + var found = MirrorRemoval.Find(Items, batch, !_versioned, removedAt, out var repeated); + if (found < batch.Count) + { + return false; + } + + var removed = MirrorRemoval.Compact(Items, removedAt, found); + sink.BatchStarted(batch.Count); + try + { + for (var k = 0; k < found; k++) + { + sink.ItemRemoved(removedAt[k] - k, removed[k]); + } + } + finally + { + sink.BatchEnded(); } - Items[index] = change.Current; + MarkUnverified(0, 0); + _verifyFull |= repeated; + return true; } - /// Moves an occurrence within the source mirror. - /// The move to apply. - private void MoveItem(Change change) + /// Checks that a positional removal matches the mirror before publishing any changes. + /// The first item to remove. + /// The expected removed items. + /// Whether all items match at their original positions. + private bool MatchesRemovalRange(int start, PooledBatch batch) { - var previous = change.PreviousIndex; - var current = change.CurrentIndex; - if (previous < 0 || previous >= Items.Count || current < 0 || current >= Items.Count) + if (start > Items.Count - batch.Count) + { + return false; + } + + for (var i = 0; i < batch.Count; i++) + { + if (!ItemComparison.SameItem(Items[start + i], batch.Items[i])) + { + return false; + } + } + + return true; + } + + /// Checks whether an item occurs again after an index. + /// The index of the occurrence already found. + /// The item. + /// when another occurrence follows. + private bool HasAnotherOccurrence(int index, T item) + { + if (typeof(T).IsValueType) + { + return Items.IndexOf(item, index + 1) >= 0; + } + + for (var i = index + 1; i < Items.Count; i++) + { + if (ItemComparison.SameItem(Items[i], item)) + { + return true; + } + } + + return false; + } + + /// Records that a batch was applied from a notification whose result has not been compared with the source. + /// The first mirror index the batch inserted. + /// The number of items inserted, or zero for a removal. + private void MarkUnverified(int start, int length) + { + if (_versioned) { return; } - var item = Items[previous]; - Items.RemoveAt(previous); - Items.Insert(current, item); + _verifyFull = _verifyPending; + _verifyPending = true; + _verifyStart = start; + _verifyLength = length; + } + + /// Checks the mirror size and the most recently inserted range against the source without copying it. + /// The source viewed as a list. + /// when the size and the inserted range agree. + private bool ConfirmsBatch(IReadOnlyList list) + { + try + { + if (list.Count != Items.Count) + { + return false; + } + + for (var i = _verifyStart; i < _verifyStart + _verifyLength; i++) + { + if (!ItemComparison.SameItem(list[i], Items[i])) + { + return false; + } + } + + return true; + } + catch (ArgumentOutOfRangeException) + { + // The source shrank while it was being read, so the full comparison decides. + return false; + } + } + + /// Finds the mirror index of an item, trusting the notification index when it still holds the item. + /// The index carried by the notification. + /// The item to locate. + /// The index, or -1 when the item is not in the mirror. + private int LocateIndex(int hint, T item) => + hint >= 0 && hint < Items.Count && ItemComparison.SameItem(Items[hint], item) + ? hint + : ItemComparison.FindIndex(Items, item); + + /// Replaces the mirror from the source and tells the sink to rebuild. + /// The sink type. + /// The sink. + private void ResetFromSource(TSink sink) + where TSink : IViewMirrorSink + { + Reset(); + sink.MirrorReset(); + } + + /// Checks whether the mirror holds exactly the supplied items in order. + /// The source snapshot. + /// when the mirror matches. + private bool MatchesMirror(T[] snapshot) + { + if (snapshot.Length != Items.Count) + { + return false; + } + + for (var i = 0; i < snapshot.Length; i++) + { + if (!ItemComparison.SameItem(snapshot[i], Items[i])) + { + return false; + } + } + + return true; } } diff --git a/src/benchmarks/ReactiveList.Benchmarks/BatchResetLimitBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/BatchResetLimitBenchmarks.cs new file mode 100644 index 00000000..cbdb7dfa --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/BatchResetLimitBenchmarks.cs @@ -0,0 +1,89 @@ +// 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. + +using System.Collections.Specialized; +using ReactiveList.Views; +using ReactiveUI.Primitives.Concurrency; + +namespace ReactiveList.Benchmarks; + +/// Measures a filtered view that listens for changes while large batches arrive, with and without a batch reset limit. +[MemoryDiagnoser] +public class BatchResetLimitBenchmarks +{ + /// The limit used when the limit is switched on. + private const int Limit = 32; + + /// The source list the view observes. + private ReactiveList _list = null!; + + /// The view under test. + private ReactiveView? _view; + + /// The items added and removed by each iteration. + private int[] _batch = []; + + /// The number of collection notifications received. + private int _notifications; + + /// Non-zero once disposed. + private int _disposed; + + /// Gets or sets the number of items in each batch. + [Params(1_024, 10_000)] + public int BatchSize { get; set; } + + /// Gets or sets a value indicating whether the view raises one reset for a large batch. + [Params(false, true)] + public bool UseLimit { get; set; } + + /// Builds the view and attaches a change handler. + [GlobalSetup] + public void Setup() + { + _list = []; + _batch = new int[BatchSize]; + for (var i = 0; i < _batch.Length; i++) + { + _batch[i] = i; + } + + _view = ((IReactiveSource)_list).CreateView(static item => (item & 1) == 0, Sequencer.Immediate, throttleMs: 0); + if (UseLimit) + { + _view.BatchResetLimit = Limit; + } + + ((INotifyCollectionChanged)_view.Items).CollectionChanged += OnChanged; + } + + /// Releases the view and the source. + [GlobalCleanup] + public void Cleanup() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + _view?.Dispose(); + _list.Dispose(); + } + + /// Adds a large batch and removes it again. + /// The number of notifications received so far. + [Benchmark] + public int BatchAddRemove() + { + _list.AddRange(_batch); + _list.Remove((IEnumerable)_batch); + return Volatile.Read(ref _notifications); + } + + /// Counts a notification. + /// The collection. + /// The notification. + private void OnChanged(object? sender, NotifyCollectionChangedEventArgs args) => + _ = Interlocked.Increment(ref _notifications); +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/FilteredViewRangeBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/FilteredViewRangeBenchmarks.cs new file mode 100644 index 00000000..f95252e9 --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/FilteredViewRangeBenchmarks.cs @@ -0,0 +1,74 @@ +// 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. + +using ReactiveList.Views; +using ReactiveUI.Primitives.Concurrency; + +namespace ReactiveList.Benchmarks; + +/// Measures a filtered view while a range is inserted into and removed from the middle of its source. +[MemoryDiagnoser] +public class FilteredViewRangeBenchmarks : IDisposable +{ + /// The number of items in the unchanged source. + private const int SourceSize = 10_000; + + /// The index the range is inserted at and removed from. + private const int Middle = SourceSize / 2; + + /// The values are included when they are divisible by this number. + private const int Divisor = 2; + + /// The source list. + private ReactiveList? _source; + + /// The view observing the source. + private FilteredReactiveView? _view; + + /// The values inserted and removed. + private int[] _range = []; + + /// Gets or sets the number of items in the range. + [Params(16, 1_024)] + public int RangeSize { get; set; } + + /// Creates the source and the view. + [GlobalSetup] + public void Setup() + { + _source = [.. Enumerable.Range(0, SourceSize)]; + _range = [.. Enumerable.Range(SourceSize, RangeSize)]; + _view = new(_source, static item => item % Divisor == 0, Sequencer.Immediate, TimeSpan.Zero); + } + + /// Inserts the range in the middle, then removes it by position. + /// The view count afterwards. + [Benchmark] + public int InsertThenRemoveMiddleRange() + { + _source!.InsertRange(Middle, _range); + _source.RemoveRange(Middle, RangeSize); + return _view!.Count; + } + + /// Closes the view and its source. + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// Closes the view and its source. + /// Whether managed resources are released. + protected virtual void Dispose(bool disposing) + { + if (!disposing) + { + return; + } + + _view?.Dispose(); + _source?.Dispose(); + } +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/LiveQueryBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/LiveQueryBenchmarks.cs new file mode 100644 index 00000000..66eb46d5 --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/LiveQueryBenchmarks.cs @@ -0,0 +1,202 @@ +// 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. + +using ReactiveList.Queries; +using ReactiveUI.Primitives.Concurrency; +using ReactiveUI.Primitives.Signals; + +namespace ReactiveList.Benchmarks; + +/// Measures plan creation, view creation and updates to a filtered, ordered window. +[MemoryDiagnoser] +public class LiveQueryBenchmarks : IDisposable +{ + /// The size of a batch added to or removed from the source. + private const int BatchSize = 16; + + /// The maximum number of items displayed. + private const int WindowSize = 32; + + /// The number of groups the group views hold. + private const int GroupCount = 16; + + /// Set to one once the benchmark has been disposed. + private int _disposed; + + /// The source being queried. + private ReactiveList _source = null!; + + /// The ordered list the group and slide views follow. + private ReactiveList _groupList = null!; + + /// The sharded list the group and slide views follow. + private QuaternaryList _groupSharded = null!; + + /// The group view over the ordered list. + private LiveGroupView _listGroups = null!; + + /// The group view over the sharded list. + private LiveGroupView _shardedGroups = null!; + + /// The skip of the window over the ordered list. + private Signal _slideListSkip = null!; + + /// The skip of the window over the sharded list. + private Signal _slideShardedSkip = null!; + + /// The window over the ordered list. + private LiveView _slideList = null!; + + /// The window over the sharded list. + private LiveView _slideSharded = null!; + + /// The active view used by the mutation workload. + private LiveView _view = null!; + + /// The items added and removed by the mutation workload. + private int[] _batch = []; + + /// Gets or sets the size of the source list. + [Params(0, 64, 4_096)] + public int ItemCount { get; set; } + + /// Populates the source and opens the live window. + [GlobalSetup] + public void Setup() + { + _source = [.. Enumerable.Range(0, ItemCount)]; + _batch = [.. Enumerable.Range(ItemCount, BatchSize)]; + _view = BuildPlan().ToView(Sequencer.Immediate, 0); + _groupList = [.. Enumerable.Range(0, ItemCount)]; + _groupSharded = new(); + _groupSharded.AddRange(Enumerable.Range(0, ItemCount)); + _listGroups = _groupList.Live.GroupBy(static value => value % GroupCount).ToView(Sequencer.Immediate, 0); + _shardedGroups = _groupSharded.Live.GroupBy(static value => value % GroupCount).ToView(Sequencer.Immediate, 0); + _slideListSkip = new(); + _slideShardedSkip = new(); + _slideList = _groupList.Live.OrderBy(static value => value).Skip(_slideListSkip).Take(WindowSize).ToView(Sequencer.Immediate, 0); + _slideSharded = _groupSharded.Live.OrderBy(static value => value).Skip(_slideShardedSkip).Take(WindowSize).ToView(Sequencer.Immediate, 0); + _slideListSkip.OnNext(0); + _slideShardedSkip.OnNext(0); + } + + /// Releases the windows, group views, signals and sources. + [GlobalCleanup] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Cleanup() => Dispose(); + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// Records a query without creating a subscription. + /// The query plan. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public WindowedLiveQuery BuildPlan() => + _source.Live.Where(static value => (value & 1) == 0).OrderByDescending(static value => value).Take(WindowSize); + + /// Opens and closes one live window. + /// The number of visible items. + [Benchmark] + public int CreateDispose() + { + using var view = BuildPlan().ToView(Sequencer.Immediate, 0); + return view.Count; + } + + /// Adds and removes a batch that changes the visible window. + /// The number of visible items after removal. + [Benchmark] + public int BatchAddRemove() + { + _source.AddRange(_batch); + _source.RemoveRange(ItemCount, BatchSize); + return _view.Count; + } + + /// Adds then removes one item of an ordered list that a group view follows. + /// The number of groups. + [Benchmark] + public int GroupViewListAddRemove() + { + _groupList.Add(ItemCount); + _groupList.RemoveAt(_groupList.Count - 1); + return _listGroups.Count; + } + + /// Adds then removes one item of a sharded list that a group view follows. + /// The number of groups. + [Benchmark] + public int GroupViewShardedAddRemove() + { + _groupSharded.Add(ItemCount); + _ = _groupSharded.Remove(ItemCount); + return _shardedGroups.Count; + } + + /// Slides a window over an ordered list by one item and back. + /// The number of visible items. + [Benchmark] + public int WindowSlideByOneList() + { + _slideListSkip.OnNext(1); + _slideListSkip.OnNext(0); + return _slideList.Count; + } + + /// Slides a window over an ordered list by a page and back. + /// The number of visible items. + [Benchmark] + public int WindowSlideByPageList() + { + _slideListSkip.OnNext(WindowSize); + _slideListSkip.OnNext(0); + return _slideList.Count; + } + + /// Slides a window over a sharded list by one item and back. + /// The number of visible items. + [Benchmark] + public int WindowSlideByOneSharded() + { + _slideShardedSkip.OnNext(1); + _slideShardedSkip.OnNext(0); + return _slideSharded.Count; + } + + /// Slides a window over a sharded list by a page and back. + /// The number of visible items. + [Benchmark] + public int WindowSlideByPageSharded() + { + _slideShardedSkip.OnNext(WindowSize); + _slideShardedSkip.OnNext(0); + return _slideSharded.Count; + } + + /// Releases the windows, group views, signals and sources. + /// Whether managed resources are released. + protected virtual void Dispose(bool disposing) + { + if (!disposing || Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + _slideListSkip.Dispose(); + _slideShardedSkip.Dispose(); + _view.Dispose(); + _source.Dispose(); + _listGroups.Dispose(); + _shardedGroups.Dispose(); + _slideList.Dispose(); + _slideSharded.Dispose(); + _groupList.Dispose(); + _groupSharded.Dispose(); + } +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/NotificationDeferralBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/NotificationDeferralBenchmarks.cs new file mode 100644 index 00000000..435540e1 --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/NotificationDeferralBenchmarks.cs @@ -0,0 +1,123 @@ +// 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. + +using ReactiveList.Views; +using ReactiveUI.Primitives.Concurrency; + +namespace ReactiveList.Benchmarks; + +/// Compares individual notifications with a single reset for the same writes. +[MemoryDiagnoser] +public class NotificationDeferralBenchmarks : IDisposable +{ + /// The size of the interactive view. + private const int InteractiveCount = 64; + + /// The list receiving the writes. + private ReactiveList _list = null!; + + /// The sharded list receiving writes from several workers. + private QuaternaryList _sharded = null!; + + /// The active view for the interactive case. + private SortedReactiveView? _view; + + /// The write pair executed on each shard worker. + private Action _mutateShard = null!; + + /// The disposal latch. + private int _disposed; + + /// Gets or sets the number of items in the collection. + [Params(1, InteractiveCount, 4_096)] + public int ItemCount { get; set; } + + /// Gets or sets a value indicating whether to defer notifications. + [Params(false, true)] + public bool Deferred { get; set; } + + /// Creates the sources and attaches a view for the interactive case. + [GlobalSetup] + public void Setup() + { + _list = [.. Enumerable.Range(0, ItemCount)]; + _sharded = [.. Enumerable.Range(0, ItemCount)]; + _mutateShard = MutateShard; + if (ItemCount == InteractiveCount) + { + _view = new(_list, Comparer.Default, Sequencer.Immediate, TimeSpan.Zero); + } + } + + /// Disposes the sources and the view. + [GlobalCleanup] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Cleanup() => Dispose(); + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// Adds and removes items with and without a deferral. + /// The number of items after the writes. + [Benchmark] + public int List_AddRemove() + { + using var deferral = Deferred ? _list.DeferNotifications() : default; + for (var i = 0; i < ItemCount; i++) + { + _list.Add(ItemCount + i); + _list.RemoveAt(_list.Count - 1); + } + + return _list.Count; + } + + /// Runs contention on the bulk case and direct writes on smaller cases. + /// The number of items after the writes. + [Benchmark] + public int Sharded_AddRemove() + { + using var deferral = Deferred ? _sharded.DeferNotifications() : default; + if (ItemCount <= InteractiveCount) + { + for (var i = 0; i < ItemCount; i++) + { + MutateShard(i); + } + } + else + { + _ = Parallel.For(0, ItemCount, _mutateShard); + } + + return _sharded.Count; + } + + /// Disposes the managed benchmark state. + /// Whether to release managed state. + protected virtual void Dispose(bool disposing) + { + if (!disposing || Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + _view?.Dispose(); + _list.Dispose(); + _sharded.Dispose(); + } + + /// Writes one distinct item and removes it from the same shard. + /// The offset used to select an item outside the initial contents. + private void MutateShard(int index) + { + var item = ItemCount + index; + _sharded.Add(item); + _ = _sharded.Remove(item); + } +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/QuaternaryContendedBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryContendedBenchmarks.cs new file mode 100644 index 00000000..80ce0178 --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryContendedBenchmarks.cs @@ -0,0 +1,140 @@ +// 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. + +namespace ReactiveList.Benchmarks; + +/// Measures quaternary collections with 1,000 to 10,000 items and several threads writing at once. +[MemoryDiagnoser] +public class QuaternaryContendedBenchmarks : IDisposable +{ + /// The number of concurrent workers. + private const int WorkerCount = 8; + + /// The number of reads performed per write in the mixed benchmark. + private const int ReadsPerWrite = 4; + + /// The list under test. + private QuaternaryList _list = new(); + + /// The dictionary under test. + private QuaternaryDictionary _dictionary = new(); + + /// Gets or sets the number of items written per iteration. + [Params(1_000, 10_000)] + public int ItemCount { get; set; } + + /// Creates the collections. + [GlobalSetup] + public void Setup() + { + _list = new(); + _dictionary = new(); + } + + /// Releases the collections. + [GlobalCleanup] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Cleanup() => Dispose(); + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// Adds items from several threads, then clears the list. + /// The count before clearing. + [Benchmark] + public int List_ParallelAdd_Clear() + { + _ = Parallel.For(0, WorkerCount, WriteListSlice); + var count = _list.Count; + _list.Clear(); + return count; + } + + /// Adds and reads items from several threads, then clears the list. + /// The sum of observed counts. + [Benchmark] + public long List_ParallelMixed_Clear() + { + long observed = 0; + _ = Parallel.For(0, WorkerCount, worker => Interlocked.Add(ref observed, MixedListSlice(worker))); + _list.Clear(); + return observed; + } + + /// Adds entries from several threads, then clears the dictionary. + /// The count before clearing. + [Benchmark] + public int Dictionary_ParallelAdd_Clear() + { + _ = Parallel.For(0, WorkerCount, WriteDictionarySlice); + var count = _dictionary.Count; + _dictionary.Clear(); + return count; + } + + /// Releases the collections. + /// Whether managed resources are being released. + protected virtual void Dispose(bool disposing) + { + if (!disposing) + { + return; + } + + _list.Dispose(); + _dictionary.Dispose(); + } + + /// Gets the number of items each worker writes. + /// The slice size. + private int SliceSize() => ItemCount / WorkerCount; + + /// Adds one worker's slice of items to the list. + /// The worker index. + private void WriteListSlice(int worker) + { + var size = SliceSize(); + var start = worker * size; + for (var i = 0; i < size; i++) + { + _list.Add(start + i); + } + } + + /// Adds one worker's slice of entries to the dictionary. + /// The worker index. + private void WriteDictionarySlice(int worker) + { + var size = SliceSize(); + var start = worker * size; + for (var i = 0; i < size; i++) + { + _dictionary.AddOrUpdate(start + i, i); + } + } + + /// Adds one worker's slice to the list while reading the list between writes. + /// The worker index. + /// The sum of the counts the worker observed. + private long MixedListSlice(int worker) + { + var size = SliceSize(); + var start = worker * size; + long observed = 0; + for (var i = 0; i < size; i++) + { + _list.Add(start + i); + for (var read = 0; read < ReadsPerWrite; read++) + { + observed += _list.Contains(start + read) ? 1 : 0; + } + } + + return observed; + } +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/QuaternaryCreateBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryCreateBenchmarks.cs new file mode 100644 index 00000000..c8ade59e --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryCreateBenchmarks.cs @@ -0,0 +1,63 @@ +// 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. + +namespace ReactiveList.Benchmarks; + +/// Measures the time and bytes needed to create an empty quaternary collection with zero, one or three indexes. +[MemoryDiagnoser] +public class QuaternaryCreateBenchmarks +{ + /// The first index modulus. + private const int FirstModulus = 2; + + /// The second index modulus. + private const int SecondModulus = 3; + + /// The third index modulus. + private const int ThirdModulus = 5; + + /// Gets or sets the number of secondary indexes registered on the new collection. + [Params(0, 1, 3)] + public int IndexCount { get; set; } + + /// Creates a list. + /// The list. + [Benchmark] + public QuaternaryList NewList() + { + var list = new QuaternaryList(); + if (IndexCount > 0) + { + list.AddIndex("A", static i => i % FirstModulus); + } + + if (IndexCount > 1) + { + list.AddIndex("B", static i => i % SecondModulus); + list.AddIndex("C", static i => i % ThirdModulus); + } + + return list; + } + + /// Creates a dictionary. + /// The dictionary. + [Benchmark] + public QuaternaryDictionary NewDictionary() + { + var dictionary = new QuaternaryDictionary(); + if (IndexCount > 0) + { + dictionary.AddValueIndex("A", static i => i % FirstModulus); + } + + if (IndexCount > 1) + { + dictionary.AddValueIndex("B", static i => i % SecondModulus); + dictionary.AddValueIndex("C", static i => i % ThirdModulus); + } + + return dictionary; + } +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/QuaternaryFixedCostBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryFixedCostBenchmarks.cs new file mode 100644 index 00000000..c8af55f5 --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryFixedCostBenchmarks.cs @@ -0,0 +1,165 @@ +// 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. + +namespace ReactiveList.Benchmarks; + +/// Measures the per-call cost of quaternary collections with zero or one item and no observers. +[MemoryDiagnoser] +public class QuaternaryFixedCostBenchmarks : IDisposable +{ + /// The number of key buckets used by the indexed list. + private const int IndexBuckets = 2; + + /// The item added and removed by single-item benchmarks. + private const int Probe = 7; + + /// The key used by dictionary benchmarks. + private const int ProbeKey = 3; + + /// The list under test. + private QuaternaryList _list = new(); + + /// The dictionary under test. + private QuaternaryDictionary _dictionary = new(); + + /// The list holding a secondary index. + private QuaternaryList _indexedList = new(); + + /// Gets or sets the number of items present before each operation. + [Params(0, 1)] + public int ItemCount { get; set; } + + /// Creates the collections with items. + [GlobalSetup] + public void Setup() + { + _list = new(); + _dictionary = new(); + _indexedList = new(); + _indexedList.AddIndex("Mod", static i => i % IndexBuckets); + for (var i = 0; i < ItemCount; i++) + { + _list.Add(i); + _dictionary.Add(i, i); + _indexedList.Add(i); + } + } + + /// Releases the collections. + [GlobalCleanup] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Cleanup() => Dispose(); + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// Adds then removes one list item. + /// The resulting count. + [Benchmark] + public int List_AddRemove() + { + _list.Add(Probe); + _ = _list.Remove(Probe); + return _list.Count; + } + + /// Adds then removes one list item while an index is registered. + /// The resulting count. + [Benchmark] + public int IndexedList_AddRemove() + { + _indexedList.Add(Probe); + _ = _indexedList.Remove(Probe); + return _indexedList.Count; + } + + /// Checks whether the list contains an item. + /// Whether the item is present. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool List_Contains() => _list.Contains(Probe); + + /// Reads the list count. + /// The item count. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int List_Count() => _list.Count; + + /// Adds an empty range to the list. + /// The resulting count. + [Benchmark] + public int List_AddRangeEmpty() + { + _list.AddRange([]); + return _list.Count; + } + + /// Clears the list when it is already empty or holds one item that is restored. + /// The resulting count. + [Benchmark] + public int List_ClearAndRestore() + { + _list.Clear(); + for (var i = 0; i < ItemCount; i++) + { + _list.Add(i); + } + + return _list.Count; + } + + /// Copies the list to an array. + /// The array length. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int List_ToArray() => _list.ToArray().Length; + + /// Enumerates the list. + /// The sum of the items. + [Benchmark] + public int List_Enumerate() + { + var sum = 0; + foreach (var item in _list) + { + sum += item; + } + + return sum; + } + + /// Adds then removes one dictionary entry. + /// The resulting count. + [Benchmark] + public int Dictionary_AddRemove() + { + _ = _dictionary.TryAdd(ProbeKey + ItemCount, Probe); + _ = _dictionary.Remove(ProbeKey + ItemCount); + return _dictionary.Count; + } + + /// Looks up one dictionary key. + /// Whether the key is present. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Dictionary_TryGetValue() => _dictionary.TryGetValue(ProbeKey, out _); + + /// Releases the collections. + /// Whether managed resources are being released. + protected virtual void Dispose(bool disposing) + { + if (!disposing) + { + return; + } + + _list.Dispose(); + _dictionary.Dispose(); + _indexedList.Dispose(); + } +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/QuaternaryListBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryListBenchmarks.cs index 2e50d7bd..b3badf70 100644 --- a/src/benchmarks/ReactiveList.Benchmarks/QuaternaryListBenchmarks.cs +++ b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryListBenchmarks.cs @@ -8,7 +8,7 @@ namespace ReactiveList.Benchmarks; /// Benchmarks operations against comparable list implementations. [MemoryDiagnoser] -public sealed class QuaternaryListBenchmarks +public class QuaternaryListBenchmarks { /// Divides a count in half for partial-removal benchmarks. private const int HalfCountDivisor = 2; diff --git a/src/benchmarks/ReactiveList.Benchmarks/QuaternaryObservedBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryObservedBenchmarks.cs new file mode 100644 index 00000000..a02aa0ff --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryObservedBenchmarks.cs @@ -0,0 +1,170 @@ +// 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. + +using ReactiveList.Core; + +namespace ReactiveList.Benchmarks; + +/// Measures producer-side cost of quaternary collections with 16 to 128 items and an active stream observer. +[MemoryDiagnoser] +public class QuaternaryObservedBenchmarks : IDisposable +{ + /// The divisor that halves the item count. + private const int HalfDivisor = 2; + + /// The divisor selecting items removed by predicate benchmarks. + private const int RemoveDivisor = 4; + + /// The input items. + private int[] _data = []; + + /// The input dictionary entries. + private KeyValuePair[] _pairs = []; + + /// The list under test. + private QuaternaryList _list = new(); + + /// The dictionary under test. + private QuaternaryDictionary _dictionary = new(); + + /// The subscription to the list stream. + private IDisposable? _listSubscription; + + /// The subscription to the dictionary stream. + private IDisposable? _dictionarySubscription; + + /// The number of notifications received. + private int _events; + + /// Gets or sets the number of items used by each benchmark. + [Params(16, 128)] + public int ItemCount { get; set; } + + /// Creates the collections and subscribes to their streams. + [GlobalSetup] + public void Setup() + { + _data = new int[ItemCount]; + _pairs = new KeyValuePair[ItemCount]; + for (var i = 0; i < ItemCount; i++) + { + _data[i] = i; + _pairs[i] = new(i, i); + } + + _list = new(); + _dictionary = new(); + _listSubscription = _list.Stream.SubscribeObserver(CountEvent); + _dictionarySubscription = _dictionary.Stream.SubscribeObserver(CountDictionaryEvent); + } + + /// Releases the subscriptions and collections. + [GlobalCleanup] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Cleanup() => Dispose(); + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// Adds items one at a time and clears the list. + /// The notification count. + [Benchmark] + public int List_AddEach_Clear() + { + for (var i = 0; i < ItemCount; i++) + { + _list.Add(i); + } + + _list.Clear(); + return Volatile.Read(ref _events); + } + + /// Adds the items as one batch and clears the list. + /// The notification count. + [Benchmark] + public int List_AddRange_Clear() + { + _list.AddRange(_data); + _list.Clear(); + return Volatile.Read(ref _events); + } + + /// Adds the items as a batch, removes a quarter by predicate and clears. + /// The notification count. + [Benchmark] + public int List_AddRange_RemoveMany_Clear() + { + _list.AddRange(_data); + _ = _list.RemoveMany(static i => i % RemoveDivisor == 0); + _list.Clear(); + return Volatile.Read(ref _events); + } + + /// Adds the items as a batch, removes half by range and clears. + /// The notification count. + [Benchmark] + public int List_AddRange_RemoveRange_Clear() + { + _list.AddRange(_data); + _list.RemoveRange(_data.AsSpan(0, ItemCount / HalfDivisor).ToArray()); + _list.Clear(); + return Volatile.Read(ref _events); + } + + /// Adds entries as a batch and clears the dictionary. + /// The notification count. + [Benchmark] + public int Dictionary_AddRange_Clear() + { + _dictionary.AddRange(_pairs); + _dictionary.Clear(); + return Volatile.Read(ref _events); + } + + /// Adds entries one at a time, removes a quarter by predicate and clears. + /// The notification count. + [Benchmark] + public int Dictionary_AddEach_RemoveMany_Clear() + { + for (var i = 0; i < ItemCount; i++) + { + _dictionary.AddOrUpdate(i, i); + } + + _ = _dictionary.RemoveMany(static pair => pair.Key % RemoveDivisor == 0); + _dictionary.Clear(); + return Volatile.Read(ref _events); + } + + /// Releases the subscriptions and collections. + /// Whether managed resources are being released. + protected virtual void Dispose(bool disposing) + { + if (!disposing) + { + return; + } + + _listSubscription?.Dispose(); + _dictionarySubscription?.Dispose(); + _list.Dispose(); + _dictionary.Dispose(); + } + + /// Counts a list notification. + /// The notification. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void CountEvent(CacheNotify notification) => Interlocked.Add(ref _events, notification.Action == CacheAction.Cleared ? 1 : 0); + + /// Counts a dictionary notification. + /// The notification. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void CountDictionaryEvent(CacheNotify> notification) => + Interlocked.Add(ref _events, notification.Action == CacheAction.Cleared ? 1 : 0); +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/QuaternaryVersionedBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryVersionedBenchmarks.cs new file mode 100644 index 00000000..a422d74e --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryVersionedBenchmarks.cs @@ -0,0 +1,132 @@ +// 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. + +using ReactiveList.Core; + +namespace ReactiveList.Benchmarks; + +/// Measures the versioned snapshot and the versioned stream against their plain counterparts. +[MemoryDiagnoser] +public class QuaternaryVersionedBenchmarks : IDisposable +{ + /// The item added and removed by the stream benchmarks. + private const int Probe = 1_000_001; + + /// The list under test. + private QuaternaryList _list = new(); + + /// The list whose changes are observed through . + private QuaternaryList _plainStreamList = new(); + + /// The list whose changes are observed through . + private QuaternaryList _versionedStreamList = new(); + + /// The subscription to the plain stream. + private IDisposable? _plainSubscription; + + /// The subscription to the versioned stream. + private IDisposable? _versionedSubscription; + + /// The number of notifications received. + private int _events; + + /// Gets or sets the number of items in the list under test. + [Params(0, 16, 128, 10_000)] + public int ItemCount { get; set; } + + /// Creates the lists and subscribes to the streams. + [GlobalSetup] + public void Setup() + { + _list = new(); + _plainStreamList = new(); + _versionedStreamList = new(); + for (var i = 0; i < ItemCount; i++) + { + _list.Add(i); + } + + _plainSubscription = _plainStreamList.Stream.Subscribe(new CountingObserver>(this)); + _versionedSubscription = _versionedStreamList.VersionedStream.Subscribe(new CountingObserver>(this)); + } + + /// Releases the subscriptions and lists. + [GlobalCleanup] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Cleanup() => Dispose(); + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// Copies the list to an array. + /// The array length. + [Benchmark(Baseline = true)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int ToArray() => _list.ToArray().Length; + + /// Copies the list to an array together with its version. + /// The array length. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int CopyVersioned() => _list.CopyVersioned(out _).Length; + + /// Adds and removes one item with a subscriber on the plain stream. + /// The notification count. + [Benchmark] + public int AddRemove_PlainStream() + { + _plainStreamList.Add(Probe); + _ = _plainStreamList.Remove(Probe); + return Volatile.Read(ref _events); + } + + /// Adds and removes one item with a subscriber on the versioned stream. + /// The notification count. + [Benchmark] + public int AddRemove_VersionedStream() + { + _versionedStreamList.Add(Probe); + _ = _versionedStreamList.Remove(Probe); + return Volatile.Read(ref _events); + } + + /// Releases the subscriptions and lists. + /// Whether managed resources are being released. + protected virtual void Dispose(bool disposing) + { + if (!disposing) + { + return; + } + + _plainSubscription?.Dispose(); + _versionedSubscription?.Dispose(); + _list.Dispose(); + _plainStreamList.Dispose(); + _versionedStreamList.Dispose(); + } + + /// Counts the notifications an observer receives. + /// The notification type. + /// The benchmark that holds the counter. + private sealed class CountingObserver(QuaternaryVersionedBenchmarks owner) : IObserver + { + /// + public void OnNext(T value) => _ = Interlocked.Increment(ref owner._events); + + /// + public void OnError(Exception error) + { + } + + /// + public void OnCompleted() + { + } + } +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/QuaternaryViewCreateBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryViewCreateBenchmarks.cs new file mode 100644 index 00000000..c854a599 --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/QuaternaryViewCreateBenchmarks.cs @@ -0,0 +1,87 @@ +// 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. + +using ReactiveList.Views; +using ReactiveUI.Primitives.Concurrency; +using ReactiveUI.Primitives.Signals; + +namespace ReactiveList.Benchmarks; + +/// Measures building views over a populated , whose notifications arrive on a background pump. +[MemoryDiagnoser] +public class QuaternaryViewCreateBenchmarks : IDisposable +{ + /// The name of the secondary index. + private const string IndexName = "bucket"; + + /// The number of buckets the index holds. + private const int BucketCount = 3; + + /// The source list. + private readonly QuaternaryList _list = []; + + /// Supplies the index keys. + private readonly BehaviorSignal _keys = new([1]); + + /// Non-zero once disposed. + private int _disposed; + + /// Gets or sets the number of items the source holds. + [Params(1, 64, 4_096)] + public int ItemCount { get; set; } + + /// Builds the source. + [GlobalSetup] + public void Setup() + { + _list.AddIndex(IndexName, static item => item % BucketCount); + for (var i = 0; i < ItemCount; i++) + { + _list.Add(i); + } + } + + /// Releases the source. + [GlobalCleanup] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Cleanup() => Dispose(); + + /// Creates and disposes a filtered view over the quaternary source. + /// The source count. + [Benchmark] + public int FilteredViewCreateDispose() + { + using var view = ((IReactiveSource)_list).CreateView(static item => (item & 1) == 0, Sequencer.Immediate, throttleMs: 0); + return _list.Count; + } + + /// Creates and disposes a secondary index view over the quaternary source. + /// The source count. + [Benchmark] + public int SecondaryIndexViewCreateDispose() + { + using var view = new DynamicSecondaryIndexReactiveView(_list, IndexName, _keys, Sequencer.Immediate, TimeSpan.Zero); + return _list.Count; + } + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// Releases the source. + /// Whether managed resources are released. + protected virtual void Dispose(bool disposing) + { + if (!disposing || Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + _keys.Dispose(); + _list.Dispose(); + } +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/Reactive2DListBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/Reactive2DListBenchmarks.cs new file mode 100644 index 00000000..5534eb80 --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/Reactive2DListBenchmarks.cs @@ -0,0 +1,105 @@ +// 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. + +namespace ReactiveList.Benchmarks; + +/// Measures adding, removing and flattening rows of a . +[MemoryDiagnoser] +public class Reactive2DListBenchmarks : IDisposable +{ + /// The number of items in each row. + private const int RowSize = 4; + + /// The offset of the second item in a row. + private const int Second = 1; + + /// The offset of the third item in a row. + private const int Third = 2; + + /// The offset of the fourth item in a row. + private const int Fourth = 3; + + /// The first item of the spare row. + private const int SpareFirst = 1; + + /// The second item of the spare row. + private const int SpareSecond = 2; + + /// Holds the list under test. + private Reactive2DList _list = []; + + /// Holds the row that is added and removed. + private ReactiveList _row = new(); + + /// Gets or sets the number of rows in the list. + [Params(0, 16, 128)] + public int Rows { get; set; } + + /// Creates a populated list. + [GlobalSetup] + public void Setup() + { + var rows = new ReactiveList[Rows]; + for (var i = 0; i < rows.Length; i++) + { + rows[i] = new([i, i + Second, i + Third, i + Fourth]); + } + + _list = new(rows); + _row = new([SpareFirst, SpareSecond, RowSize]); + } + + /// Releases the list. + [GlobalCleanup] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Cleanup() => Dispose(); + + /// Adds a row and removes it again. + [Benchmark] + public void Add_Remove_Row() + { + _list.Add(_row); + _ = _list.Remove(_row); + } + + /// Flattens every row. + /// The number of flattened items. + [Benchmark] + public int Flatten() + { + var count = 0; + foreach (var item in _list.Flatten()) + { + count += item & 1; + } + + return count; + } + + /// Counts the items in every row. + /// The total count. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int TotalCount() => _list.TotalCount(); + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// Releases the lists. + /// Whether managed resources are released. + protected virtual void Dispose(bool disposing) + { + if (!disposing) + { + return; + } + + _list.Dispose(); + _row.Dispose(); + } +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/ReactiveListBulkBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/ReactiveListBulkBenchmarks.cs new file mode 100644 index 00000000..d98ab75d --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/ReactiveListBulkBenchmarks.cs @@ -0,0 +1,185 @@ +// 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. + +namespace ReactiveList.Benchmarks; + +/// Measures bulk operations and concurrent access at large sizes. +[MemoryDiagnoser] +public class ReactiveListBulkBenchmarks : IDisposable +{ + /// Selects every second value. + private const int ParityDivisor = 2; + + /// The number of concurrent readers in the contended benchmark. + private const int ReaderCount = 2; + + /// Holds the prepared values. + private int[] _data = []; + + /// Holds the even values removed by the bulk-remove benchmark. + private int[] _evens = []; + + /// Holds a populated list for the read benchmarks. + private ReactiveList _list = new(); + + /// Gets or sets the number of items. + [Params(1_000, 10_000)] + public int Count { get; set; } + + /// Prepares the values and the read list. + [GlobalSetup] + public void Setup() + { + _data = new int[Count]; + var evens = new List(); + for (var i = 0; i < _data.Length; i++) + { + _data[i] = i; + if (i % ParityDivisor == 0) + { + evens.Add(i); + } + } + + _evens = [.. evens]; + _list = new(_data); + } + + /// Releases the read list. + [GlobalCleanup] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Cleanup() => Dispose(); + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// Benchmarks building a list from values with no observers. + /// The item count. + [Benchmark] + public int AddRange_NoObservers() + { + using var list = new ReactiveList(); + list.AddRange(_data); + return list.Count; + } + + /// Benchmarks removing every even value with a predicate. + /// The item count. + [Benchmark] + public int RemoveMany_Predicate() + { + using var list = new ReactiveList(_data); + _ = list.RemoveMany(static value => value % ParityDivisor == 0); + return list.Count; + } + + /// Benchmarks removing every even value by value. + /// The item count. + [Benchmark] + public int Remove_Enumerable() + { + using var list = new ReactiveList(_data); + list.Remove(_evens); + return list.Count; + } + + /// Benchmarks replacing all contents. + /// The item count. + [Benchmark] + public int ReplaceAll_NoObservers() + { + using var list = new ReactiveList(_data); + list.ReplaceAll(_evens); + return list.Count; + } + + /// Benchmarks clearing a populated list. + /// The item count. + [Benchmark] + public int Clear_Populated() + { + using var list = new ReactiveList(_data); + list.Clear(); + return list.Count; + } + + /// Benchmarks a batch edit that clears the list. + /// The item count. + [Benchmark] + public int Edit_Clear() + { + using var list = new ReactiveList(_data); + list.Edit(static editor => editor.Clear()); + return list.Count; + } + + /// Benchmarks enumerating the populated list. + /// The sum of the items. + [Benchmark] + public int Enumerate() + { + var sum = 0; + foreach (var item in _list) + { + sum += item; + } + + return sum; + } + + /// Benchmarks reading the contents as a span. + /// The sum of the items. + [Benchmark] + public int AsSpan_Sum() + { + var sum = 0; + foreach (var item in _list.AsSpan()) + { + sum += item; + } + + return sum; + } + + /// Benchmarks copying the contents to a new array. + /// The array length. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int ToArray_Populated() => _list.ToArray().Length; + + /// Benchmarks readers racing one writer on the same list. + /// The sum of the reader results. + [Benchmark] + public int Contended_Readers_Writer() + { + var list = _list; + var total = 0; + _ = Parallel.For(0, ReaderCount + 1, i => + { + if (i == 0) + { + list.Add(-1); + _ = list.Remove(-1); + return; + } + + _ = Interlocked.Add(ref total, list.Count + list[0]); + }); + return total; + } + + /// Releases the read list. + /// Whether managed resources are released. + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + _list.Dispose(); + } + } +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/ReactiveListFloorBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/ReactiveListFloorBenchmarks.cs new file mode 100644 index 00000000..f0813594 --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/ReactiveListFloorBenchmarks.cs @@ -0,0 +1,140 @@ +// 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. + +namespace ReactiveList.Benchmarks; + +/// Measures the fixed cost of single-item operations when nothing observes the list. +[MemoryDiagnoser] +public class ReactiveListFloorBenchmarks : IDisposable +{ + /// Holds the list shared by the steady-state benchmarks. + private ReactiveList _list = new(); + + /// Holds a list that already contains one item. + private ReactiveList _single = new(1); + + /// Creates the shared lists. + [GlobalSetup] + public void Setup() + { + _list = new(); + _single = new(1); + } + + /// Releases the shared lists. + [GlobalCleanup] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Cleanup() => Dispose(); + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// Benchmarks creating and disposing an empty list. + /// The item count. + [Benchmark] + public int Create_Dispose() + { + using var list = new ReactiveList(); + return list.Count; + } + + /// Benchmarks adding then removing one item. + /// The item count after the removal. + [Benchmark] + public int Add_Remove_Single() + { + _list.Add(1); + _ = _list.Remove(1); + return _list.Count; + } + + /// Benchmarks inserting then removing one item by index. + /// The item count after the removal. + [Benchmark] + public int Insert_RemoveAt_Single() + { + _list.Insert(0, 1); + _list.RemoveAt(0); + return _list.Count; + } + + /// Benchmarks clearing a list that is already empty. + /// The item count. + [Benchmark] + public int Clear_Empty() + { + _list.Clear(); + return _list.Count; + } + + /// Benchmarks reading the count. + /// The item count. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Count_Read() => _single.Count; + + /// Benchmarks reading one item through the indexer. + /// The item. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Indexer_Read() => _single[0]; + + /// Benchmarks replacing one item in place. + /// The item count. + [Benchmark] + public int Indexer_Write() + { + _single[0] = 1; + return _single.Count; + } + + /// Benchmarks enumerating a one-item list. + /// The sum of the items. + [Benchmark] + public int Enumerate_Single() + { + var sum = 0; + foreach (var item in _single) + { + sum += item; + } + + return sum; + } + + /// Benchmarks searching a one-item list. + /// Whether the item was found. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains_Single() => _single.Contains(1); + + /// Benchmarks finding the index of an item in a one-item list. + /// The index. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int IndexOf_Single() => _single.IndexOf(1); + + /// Benchmarks reading the contents as a span. + /// The span length. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int AsSpan_Single() => _single.AsSpan().Length; + + /// Releases the shared lists. + /// Whether managed resources are released. + protected virtual void Dispose(bool disposing) + { + if (!disposing) + { + return; + } + + _list.Dispose(); + _single.Dispose(); + } +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/ReactiveListInteractiveBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/ReactiveListInteractiveBenchmarks.cs new file mode 100644 index 00000000..b843032a --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/ReactiveListInteractiveBenchmarks.cs @@ -0,0 +1,175 @@ +// 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. + +using System.Collections.Specialized; + +namespace ReactiveList.Benchmarks; + +/// Measures operations at interactive sizes while a UI-style observer is attached. +[MemoryDiagnoser] +public class ReactiveListInteractiveBenchmarks : IDisposable +{ + /// The value toggled in and out of the list. + private const int ProbeValue = -1; + + /// Divides the count to get the size of a batch. + private const int HalfDivisor = 2; + + /// Holds the list under test. + private ReactiveList _list = new(); + + /// Holds the subscription to the stream. + private IDisposable? _subscription; + + /// Counts the notifications seen by the observers. + private int _notifications; + + /// Gets or sets the number of items in the list. + [Params(16, 128)] + public int Count { get; set; } + + /// Creates a populated list with a collection-changed handler and a stream subscriber. + [GlobalSetup] + public void Setup() + { + var data = new int[Count]; + for (var i = 0; i < data.Length; i++) + { + data[i] = i; + } + + _list = new(data); + _list.CollectionChanged += OnCollectionChanged; + _subscription = _list.Stream.SubscribeObserver(OnStream); + } + + /// Releases the list and subscription. + [GlobalCleanup] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Cleanup() => Dispose(); + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// Benchmarks adding then removing one item with observers attached. + /// The notification count. + [Benchmark] + public int Add_Remove_Observed() + { + _list.Add(ProbeValue); + _ = _list.Remove(ProbeValue); + return _notifications; + } + + /// Benchmarks inserting then removing at the front with observers attached. + /// The notification count. + [Benchmark] + public int Insert_RemoveAt_Observed() + { + _list.Insert(0, ProbeValue); + _list.RemoveAt(0); + return _notifications; + } + + /// Benchmarks moving one item and moving it back with observers attached. + /// The notification count. + [Benchmark] + public int Move_Observed() + { + _list.Move(0, Count - 1); + _list.Move(Count - 1, 0); + return _notifications; + } + + /// Benchmarks replacing the whole contents with observers attached. + /// The notification count. + [Benchmark] + public int ReplaceAll_Observed() + { + _list.ReplaceAll(_list.ToArray()); + return _notifications; + } + + /// Benchmarks removing and re-adding a batch with observers attached. + /// The notification count. + [Benchmark] + public int RemoveRange_AddRange_Observed() + { + var half = Count / HalfDivisor; + var removed = _list.ToArray()[..half]; + _list.RemoveRange(0, half); + _list.InsertRange(0, removed); + return _notifications; + } + + /// Benchmarks a batch edit whose changes cancel out, which announces nothing. + /// The notification count. + [Benchmark] + public int Edit_NetZero_Observed() + { + _list.Edit(static editor => + { + editor.Add(ProbeValue); + _ = editor.Remove(ProbeValue); + }); + return _notifications; + } + + /// Benchmarks two batch edits, one adding and one removing an item, with observers attached. + /// The notification count. + [Benchmark] + public int Edit_NetChange_Observed() + { + _list.Edit(static editor => editor.Add(ProbeValue)); + _list.Edit(static editor => _ = editor.Remove(ProbeValue)); + return _notifications; + } + + /// Benchmarks taking a snapshot array. + /// The snapshot length. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int ToArray_Snapshot() => _list.ToArray().Length; + + /// Benchmarks enumerating the list. + /// The sum of the items. + [Benchmark] + public int Enumerate() + { + var sum = 0; + foreach (var item in _list) + { + sum += item; + } + + return sum; + } + + /// Releases the list and subscription. + /// Whether managed resources are released. + protected virtual void Dispose(bool disposing) + { + if (!disposing) + { + return; + } + + _subscription?.Dispose(); + _list.CollectionChanged -= OnCollectionChanged; + _list.Dispose(); + } + + /// Counts a collection-changed notification. + /// The list. + /// The notification arguments. + private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs args) => _notifications++; + + /// Counts a stream notification. + /// The notification. + private void OnStream(ReactiveList.Core.CacheNotify notification) => _notifications++; +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/ReactiveListMirrorBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/ReactiveListMirrorBenchmarks.cs new file mode 100644 index 00000000..fd6d4a0a --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/ReactiveListMirrorBenchmarks.cs @@ -0,0 +1,96 @@ +// 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. + +namespace ReactiveList.Benchmarks; + +/// Measures range operations on a whose mirror is active and whose history mirrors are not. +[MemoryDiagnoser] +public class ReactiveListMirrorBenchmarks : IDisposable +{ + /// Divides the count to get the size of a batch. + private const int HalfDivisor = 2; + + /// Holds the list under test. + private ReactiveList _list = new(); + + /// Holds every item the list starts with. + private int[] _all = []; + + /// Holds the items inserted and removed by the benchmarks. + private int[] _half = []; + + /// Gets or sets the number of items in the list. + [Params(16, 128, 1_000)] + public int Count { get; set; } + + /// Creates a populated list and starts its items mirror. + [GlobalSetup] + public void Setup() + { + var data = new int[Count]; + for (var i = 0; i < data.Length; i++) + { + data[i] = i; + } + + _all = data; + _list = new(data); + _half = data[..(Count / HalfDivisor)]; + _ = _list.Items; + } + + /// Releases the list. + [GlobalCleanup] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Cleanup() => Dispose(); + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// Benchmarks removing and re-inserting half of the items with the mirror active. + /// The mirror count. + [Benchmark] + public int RemoveRange_InsertRange_Mirror() + { + _list.RemoveRange(0, _half.Length); + _list.InsertRange(0, _half); + return _list.Items.Count; + } + + /// Benchmarks replacing the whole contents with the mirror active. + /// The mirror count. + [Benchmark] + public int ReplaceAll_Mirror() + { + _list.ReplaceAll(_half); + _list.ReplaceAll(_all); + return _list.Items.Count; + } + + /// Benchmarks a single add and remove with the mirror active. + /// The mirror count. + [Benchmark] + public int Add_Remove_Mirror() + { + _list.Add(-1); + _ = _list.Remove(-1); + return _list.Items.Count; + } + + /// Releases the list. + /// Whether managed resources are released. + protected virtual void Dispose(bool disposing) + { + if (!disposing) + { + return; + } + + _list.Dispose(); + } +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/ReactiveViewBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/ReactiveViewBenchmarks.cs new file mode 100644 index 00000000..717fb38a --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/ReactiveViewBenchmarks.cs @@ -0,0 +1,157 @@ +// 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. + +using ReactiveList.Views; +using ReactiveUI.Primitives.Concurrency; +using ReactiveUI.Primitives.Signals; + +namespace ReactiveList.Benchmarks; + +/// +/// Measures each view over a at three sizes: a fixed-cost floor of one item, an interactive +/// list of 64 items and a bulk list of 4096 items. +/// +[MemoryDiagnoser] +public class ReactiveViewBenchmarks +{ + /// The number of items added and removed by the batch benchmark. + private const int BatchSize = 16; + + /// The number of groups items fall into. + private const int GroupCount = 8; + + /// The items added by the batch benchmark. + private readonly int[] _batch = new int[BatchSize]; + + /// The source list the view observes. + private ReactiveList _list = null!; + + /// Supplies the filter to views that follow a filter observable, and is released with the list. + private IObservable> _filters = null!; + + /// The view under test. + private IDisposable? _view; + + /// The next value a single-item benchmark adds. + private int _next; + + /// Non-zero once disposed. + private int _disposed; + + /// The view kinds under test. + public enum ViewKind + { + /// A view built by the list extension. + Source = 0, + + /// A filtered view built through the source interface. + Filtered = 1, + + /// A sorted view. + Sorted = 2, + + /// A grouped view. + Grouped = 3, + + /// A filtered view that follows a filter observable. + DynamicFiltered = 4, + + /// A view that follows a filter observable. + Dynamic = 5, + } + + /// Gets or sets the view kind. + [Params(ViewKind.Source, ViewKind.Filtered, ViewKind.Sorted, ViewKind.Grouped, ViewKind.DynamicFiltered, ViewKind.Dynamic)] + public ViewKind Kind { get; set; } + + /// Gets or sets the number of items the source holds. + [Params(1, 64, 4_096)] + public int ItemCount { get; set; } + + /// Fills the source and builds the view. + [GlobalSetup] + public void Setup() + { + _list = []; + _filters = new BehaviorSignal>(IsEven); + for (var i = 0; i < ItemCount; i++) + { + _list.Add(i); + } + + for (var i = 0; i < _batch.Length; i++) + { + _batch[i] = ItemCount + i; + } + + _next = ItemCount + BatchSize; + _view = CreateView(); + } + + /// Releases the view and the source. + [GlobalCleanup] + public void Cleanup() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + _view?.Dispose(); + (_filters as IDisposable)?.Dispose(); + _list.Dispose(); + } + + /// Adds one item and removes it again, which sends one single-item notification each way. + /// The source count. + [Benchmark] + public int SingleAddRemove() + { + _list.Add(_next); + _list.RemoveAt(_list.Count - 1); + return _list.Count; + } + + /// Adds a batch and removes it again, which sends one batch notification each way. + /// The source count. + [Benchmark] + public int BatchAddRemove() + { + _list.AddRange(_batch); + _list.RemoveRange(_list.Count - BatchSize, BatchSize); + return _list.Count; + } + + /// Creates and disposes a view over the populated source. + /// The source count. + [Benchmark] + public int CreateDispose() + { + using var view = CreateView(); + return _list.Count; + } + + /// Gets whether an item passes the shared filter. + /// The item. + /// for even items. + private static bool IsEven(int item) => (item & 1) == 0; + + /// Gets the group an item falls into. + /// The item. + /// The group key. + private static int GroupOf(int item) => item % GroupCount; + + /// Creates the view under test. + /// The view. + private IDisposable CreateView() => + Kind switch + { + ViewKind.Source => _list.CreateView(IsEven, Sequencer.Immediate, throttleMs: 0), + ViewKind.Filtered => ((IReactiveSource)_list).CreateView(IsEven, Sequencer.Immediate, throttleMs: 0), + ViewKind.Sorted => new SortedReactiveView(_list, Comparer.Default, Sequencer.Immediate, TimeSpan.Zero), + ViewKind.Grouped => new GroupedReactiveView(_list, GroupOf, Sequencer.Immediate, TimeSpan.Zero), + ViewKind.DynamicFiltered => new DynamicFilteredReactiveView(_list, _filters, Sequencer.Immediate, TimeSpan.Zero), + _ => new DynamicReactiveView(_list, _filters, TimeSpan.Zero, Sequencer.Immediate), + }; +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/SecondaryIndexBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/SecondaryIndexBenchmarks.cs new file mode 100644 index 00000000..07094c45 --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/SecondaryIndexBenchmarks.cs @@ -0,0 +1,93 @@ +// 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. + +using ReactiveList.Core; + +namespace ReactiveList.Benchmarks; + +/// Measures add, remove and lookup cost. +[MemoryDiagnoser] +public class SecondaryIndexBenchmarks +{ + /// The number of distinct keys. + private const int KeyCount = 8; + + /// The key looked up by the lookup benchmarks. + private const int ProbeKey = 3; + + /// The input items. + private int[] _data = []; + + /// The populated index. + private SecondaryIndex _index = new(static i => i % KeyCount); + + /// Gets or sets the number of items used by each benchmark. + [Params(1, 128, 10_000)] + public int ItemCount { get; set; } + + /// Creates the input and a populated index. + [GlobalSetup] + public void Setup() + { + _data = new int[ItemCount]; + _index = new(static i => i % KeyCount); + for (var i = 0; i < ItemCount; i++) + { + _data[i] = i; + _index.OnAdded(i); + } + } + + /// Adds every item to a new index. + /// The number of items added. + [Benchmark] + public int Index_AddAll() + { + var index = new SecondaryIndex(static i => i % KeyCount); + for (var i = 0; i < _data.Length; i++) + { + index.OnAdded(_data[i]); + } + + return _data.Length; + } + + /// Removes every item from a populated index and restores it. + /// The number of items processed. + [Benchmark] + public int Index_RemoveAllAndRestore() + { + for (var i = 0; i < _data.Length; i++) + { + _index.OnRemoved(_data[i]); + } + + for (var i = 0; i < _data.Length; i++) + { + _index.OnAdded(_data[i]); + } + + return _data.Length; + } + + /// Looks up one key. + /// The number of items found. + [Benchmark] + public int Index_Lookup() + { + var found = 0; + foreach (var item in _index.Lookup(ProbeKey)) + { + found += item >= 0 ? 1 : 0; + } + + return found; + } + + /// Checks one item against one key. + /// Whether the item matches. + [Benchmark] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Index_MatchesKey() => _index.MatchesKey(ProbeKey, ProbeKey); +} diff --git a/src/benchmarks/ReactiveList.Benchmarks/ViewBulkRemovalBenchmarks.cs b/src/benchmarks/ReactiveList.Benchmarks/ViewBulkRemovalBenchmarks.cs new file mode 100644 index 00000000..b12d2ff4 --- /dev/null +++ b/src/benchmarks/ReactiveList.Benchmarks/ViewBulkRemovalBenchmarks.cs @@ -0,0 +1,64 @@ +// 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. + +using ReactiveList.Views; +using ReactiveUI.Primitives.Concurrency; + +namespace ReactiveList.Benchmarks; + +/// Measures the cost of removing a large batch by value from sorted and grouped views. +[MemoryDiagnoser] +public class ViewBulkRemovalBenchmarks +{ + /// The number of items in the unchanged source. + private const int SourceSize = 4_096; + + /// The number of items added and removed each time. + private const int BatchSize = 1_024; + + /// The number of groups. + private const int GroupCount = 8; + + /// The source list. + private ReactiveList _source = null!; + + /// The view observing the source. + private IDisposable _view = null!; + + /// The values to append and remove by value. + private int[] _batch = []; + + /// Gets or sets a value indicating whether to use grouping instead of sorting. + [Params(false, true)] + public bool Grouped { get; set; } + + /// Creates the source and attaches one observer. + [GlobalSetup] + public void Setup() + { + _source = [.. Enumerable.Range(0, SourceSize)]; + _batch = [.. Enumerable.Range(SourceSize, BatchSize)]; + _view = Grouped + ? new GroupedReactiveView(_source, static item => item % GroupCount, Sequencer.Immediate, TimeSpan.Zero) + : new SortedReactiveView(_source, Comparer.Default, Sequencer.Immediate, TimeSpan.Zero); + } + + /// Adds a batch and removes its items by value. + /// The source count after removal. + [Benchmark] + public int BatchAddRemoveByValue() + { + _source.AddRange(_batch); + _source.Remove((IEnumerable)_batch); + return _source.Count; + } + + /// Closes the view and its source. + [GlobalCleanup] + public void Cleanup() + { + _view.Dispose(); + _source.Dispose(); + } +} diff --git a/src/examples/ReactiveListTestApp/MainWindowViewModel.cs b/src/examples/ReactiveListTestApp/MainWindowViewModel.cs index 40d5346e..8daf1cde 100644 --- a/src/examples/ReactiveListTestApp/MainWindowViewModel.cs +++ b/src/examples/ReactiveListTestApp/MainWindowViewModel.cs @@ -818,7 +818,7 @@ private void RecordStream(string source, CacheAction action, int count) var detail = (source.StartsWith("Connect()", StringComparison.Ordinal), action) switch { (true, _) => "ChangeSet projection", - (false, CacheAction.BatchAdded or CacheAction.BatchRemoved) => "Pooled batch notification", + (false, CacheAction.BatchAdded or CacheAction.BatchRemoved or CacheAction.Reset) => "Pooled batch notification", _ => "Single cache notification" }; diff --git a/src/tests/ReactiveList.Reactive.Tests/ReactiveList.Reactive.Tests.csproj b/src/tests/ReactiveList.Reactive.Tests/ReactiveList.Reactive.Tests.csproj index dbff67ce..6de9b1c2 100644 --- a/src/tests/ReactiveList.Reactive.Tests/ReactiveList.Reactive.Tests.csproj +++ b/src/tests/ReactiveList.Reactive.Tests/ReactiveList.Reactive.Tests.csproj @@ -13,6 +13,11 @@ + + + + + @@ -25,11 +30,14 @@ + + + @@ -48,6 +56,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -55,6 +94,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -63,6 +140,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -72,6 +184,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/tests/ReactiveList.Tests/BatchObservableCollectionQuietTests.cs b/src/tests/ReactiveList.Tests/BatchObservableCollectionQuietTests.cs new file mode 100644 index 00000000..2f33ba95 --- /dev/null +++ b/src/tests/ReactiveList.Tests/BatchObservableCollectionQuietTests.cs @@ -0,0 +1,63 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks that applies changes silently during a quiet batch and raises one reset at its end. +public class BatchObservableCollectionQuietTests +{ + /// The value inserted at the front. + private const int Front = 9; + + /// The value written over the first position. + private const int Replacement = 5; + + /// The index the first item is moved to. + private const int MoveTarget = 2; + + /// Every kind of change made while quiet raises nothing until the batch ends, then one reset. + /// Whether the collection publishes reads from other threads. + /// A task representing the asynchronous test. + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task QuietBatch_AllChangeKinds_RaiseOneResetAtTheEnd(bool synchronizeReads) + { + BatchObservableCollection collection = new(synchronizeReads); + collection.Populate([1, MoveTarget, MoveTarget + 1]); + var raised = 0; + collection.CollectionChanged += (_, _) => raised++; + collection.BeginQuiet(); + + collection.Insert(0, Front); + collection.RemoveAt(0); + collection[0] = Replacement; + collection.Move(0, MoveTarget); + collection.Clear(); + var quietEvents = raised; + collection.EndBatch(); + + await Assert.That(quietEvents).IsEqualTo(0); + await Assert.That(raised).IsEqualTo(1); + await Assert.That(collection.Count).IsEqualTo(0); + } + + /// A quiet batch that ends after the owning gate closed raises nothing. + /// A task representing the asynchronous test. + [Test] + public async Task EndBatch_GateClosedDuringQuietBatch_RaisesNothing() + { + DisposalGate gate = new(); + BatchObservableCollection collection = new() { Gate = gate }; + var raised = 0; + collection.CollectionChanged += (_, _) => raised++; + collection.BeginQuiet(); + collection.Insert(0, Front); + + gate.Close(); + collection.EndBatch(); + + await Assert.That(raised).IsEqualTo(0); + } +} diff --git a/src/tests/ReactiveList.Tests/BatchObservableCollectionTests.cs b/src/tests/ReactiveList.Tests/BatchObservableCollectionTests.cs new file mode 100644 index 00000000..40551e12 --- /dev/null +++ b/src/tests/ReactiveList.Tests/BatchObservableCollectionTests.cs @@ -0,0 +1,94 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies silent batches, population and disposal gating of . +public sealed class BatchObservableCollectionTests +{ + /// The first item the collections start with. + private const int First = 1; + + /// The second item the collections start with. + private const int Second = 2; + + /// The third item the collections start with. + private const int Third = 3; + + /// An item inserted at the front. + private const int Inserted = 9; + + /// An item written over an existing one. + private const int Replacement = 10; + + /// The index of the last of the starting items. + private const int LastIndex = 2; + + /// An item added to the collection after it was emptied. + private const int FinalItem = 5; + + /// Verifies every kind of change applied silently is announced by one reset when the batch ends. + /// Whether the collection publishes snapshots for other threads. + /// A task representing the asynchronous test. + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task EndBatch_AfterSilentChanges_RaisesOneReset(bool synchronizeReads) + { + var collection = new BatchObservableCollection(synchronizeReads); + collection.Add(First); + collection.Add(Second); + collection.Add(Third); + List actions = []; + ((INotifyCollectionChanged)collection).CollectionChanged += (_, args) => actions.Add(args.Action); + + collection.BeginQuiet(); + collection.Insert(0, Inserted); + collection[1] = Replacement; + collection.Move(0, LastIndex); + collection.RemoveAt(1); + collection.Clear(); + collection.Add(FinalItem); + + await Assert.That(actions).IsEmpty(); + + collection.EndBatch(); + + await Assert.That(actions).IsEquivalentTo([NotifyCollectionChangedAction.Reset]); + await Assert.That(collection).IsEquivalentTo([FinalItem], CollectionOrdering.Matching); + } + + /// Verifies a batch that ends after the gate closed raises nothing. + /// A task representing the asynchronous test. + [Test] + public async Task EndBatch_GateClosed_RaisesNothing() + { + var gate = new DisposalGate(); + var collection = new BatchObservableCollection { Gate = gate }; + var raised = 0; + ((INotifyCollectionChanged)collection).CollectionChanged += (_, _) => raised++; + collection.BeginQuiet(); + collection.Add(First); + gate.Close(); + + collection.EndBatch(); + + await Assert.That(raised).IsEqualTo(0); + } + + /// Verifies populating adds the items without raising an event. + /// A task representing the asynchronous test. + [Test] + public async Task Populate_Items_AddsThemWithoutEvents() + { + var collection = new BatchObservableCollection(); + var raised = 0; + ((INotifyCollectionChanged)collection).CollectionChanged += (_, _) => raised++; + + collection.Populate([First, Second, Third]); + + await Assert.That(collection).IsEquivalentTo([First, Second, Third], CollectionOrdering.Matching); + await Assert.That(raised).IsEqualTo(0); + } +} diff --git a/src/tests/ReactiveList.Tests/CacheActionHelperTests.cs b/src/tests/ReactiveList.Tests/CacheActionHelperTests.cs index 20a13998..bcc870d4 100644 --- a/src/tests/ReactiveList.Tests/CacheActionHelperTests.cs +++ b/src/tests/ReactiveList.Tests/CacheActionHelperTests.cs @@ -21,6 +21,7 @@ public class CacheActionHelperTests [Arguments(CacheAction.BatchOperation, true)] [Arguments(CacheAction.BatchAdded, true)] [Arguments(CacheAction.BatchRemoved, true)] + [Arguments(CacheAction.Reset, true)] [Arguments((CacheAction)(-1), false)] [Arguments((CacheAction)99, false)] public async Task RequiresIndexRebuild_Action_ReturnsExpectedDecision(CacheAction action, bool expected) => diff --git a/src/tests/ReactiveList.Tests/CacheActionTests.cs b/src/tests/ReactiveList.Tests/CacheActionTests.cs index a5f5c369..a2478dc5 100644 --- a/src/tests/ReactiveList.Tests/CacheActionTests.cs +++ b/src/tests/ReactiveList.Tests/CacheActionTests.cs @@ -30,8 +30,11 @@ public class CacheActionTests /// The batch removed action value. private const int BatchRemovedActionValue = 8; + /// The reset action value. + private const int ResetActionValue = 9; + /// The defined action count. - private const int DefinedActionCount = 9; + private const int DefinedActionCount = 10; /// CacheAction should have correct values. /// A task representing the asynchronous test. @@ -46,7 +49,7 @@ public async Task CacheAction_ShouldHaveCorrectValues() #endif var values = Array.ConvertAll(actions, static action => (int)action); await Assert.That(values).IsEquivalentTo( - [0, 1, UpdatedActionValue, MovedActionValue, RefreshedActionValue, ClearedActionValue, BatchOperationActionValue, BatchAddedActionValue, BatchRemovedActionValue], + [0, 1, UpdatedActionValue, MovedActionValue, RefreshedActionValue, ClearedActionValue, BatchOperationActionValue, BatchAddedActionValue, BatchRemovedActionValue, ResetActionValue], CollectionOrdering.Matching); } @@ -72,6 +75,7 @@ public async Task CacheAction_AllValuesShouldBeDefined() await Assert.That(values).Contains(CacheAction.BatchOperation); await Assert.That(values).Contains(CacheAction.BatchAdded); await Assert.That(values).Contains(CacheAction.BatchRemoved); + await Assert.That(values).Contains(CacheAction.Reset); } #if NETFRAMEWORK diff --git a/src/tests/ReactiveList.Tests/CollidingItem.cs b/src/tests/ReactiveList.Tests/CollidingItem.cs new file mode 100644 index 00000000..ce8f1feb --- /dev/null +++ b/src/tests/ReactiveList.Tests/CollidingItem.cs @@ -0,0 +1,36 @@ +// 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. + +namespace ReactiveList.Tests; + +/// An item whose hash code takes only a few values, so many distinct items collide. +internal sealed class CollidingItem : IEquatable +{ + /// Initializes a new instance of the class. + /// The identity of the item. + /// The group that also determines the hash code. + internal CollidingItem(int id, int group) + { + Id = id; + Group = group; + } + + /// Gets the identity of the item. + internal int Id { get; } + + /// Gets the group that determines the hash code. + internal int Group { get; } + + /// + public bool Equals(CollidingItem? other) => other is not null && Id == other.Id && Group == other.Group; + + /// + public override bool Equals(object? obj) => obj is CollidingItem other && Equals(other); + + /// + public override int GetHashCode() => Group; + + /// + public override string ToString() => $"{Id}/{Group}"; +} diff --git a/src/tests/ReactiveList.Tests/ConcurrencyFuzzHelpers.cs b/src/tests/ReactiveList.Tests/ConcurrencyFuzzHelpers.cs new file mode 100644 index 00000000..5e6a58df --- /dev/null +++ b/src/tests/ReactiveList.Tests/ConcurrencyFuzzHelpers.cs @@ -0,0 +1,184 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Provides comparisons and conflicting write workloads for the concurrency tests. +internal static class ConcurrencyFuzzHelpers +{ + /// The modulus that groups items in the race indexes. + internal const int IndexModulus = 16; + + /// The name of the modulus index. + internal const string ModIndex = "mod"; + + /// The odds against a clear in the dictionary replay workload. + private const int ClearOdds = 20; + + /// Compares two lists by contents. + /// The first list. + /// The second list. + /// when both hold the same items with the same multiplicities. + internal static bool SameListContents(QuaternaryList left, QuaternaryList right) + { + var a = left.ToArray(); + var b = right.ToArray(); + Array.Sort(a); + Array.Sort(b); + return left.Count == a.Length && right.Count == b.Length && a.AsSpan().SequenceEqual(b); + } + + /// Compares two dictionaries by contents. + /// The first dictionary. + /// The second dictionary. + /// when both hold the same pairs. + internal static bool SameDictionaryContents(QuaternaryDictionary left, QuaternaryDictionary right) + { + var a = left.ToArray().OrderBy(static p => p.Key).ToArray(); + var b = right.ToArray().OrderBy(static p => p.Key).ToArray(); + return left.Count == a.Length && right.Count == b.Length && a.AsSpan().SequenceEqual(b); + } + + /// Checks whether a replayed dictionary equals the dictionary it follows. + /// The dictionary that was mutated. + /// The replayed copy. + /// The lock guarding the replica. + /// when both hold the same pairs. + internal static bool ReplicaMatches(QuaternaryDictionary dictionary, Dictionary replica, Lock gate) + { + lock (gate) + { + var actual = dictionary.ToArray(); + return actual.Length == replica.Count && Enumerable.All(actual, p => replica.TryGetValue(p.Key, out var v) && v == p.Value); + } + } + + /// Checks that the "mod" index of a list matches its contents. + /// The list to check. + internal static void AssertIndexMatchesContents(QuaternaryList list) + { + var contents = list.ToArray(); + FuzzSupport.AreEqual(list.Count, contents.Length, "Count equals contents"); + for (var key = 0; key < IndexModulus; key++) + { + FuzzSupport.SameMultiset( + list.GetItemsBySecondaryIndex(ModIndex, key), + contents.Where(i => i % IndexModulus == key), + $"index key {key}"); + } + } + + /// Performs conflicting writes on a small item universe. + /// The list to mutate. + /// The random source for this worker. + internal static void ConflictingWrites(QuaternaryList list, StressRandom random) + { + Action[] actions = + [ + list.Add, + list.Add, + list.Add, + i => _ = list.Remove(i), + i => _ = list.Remove(i), + i => list.AddRange([i, i + 1, i]), + i => list.RemoveRange([i, i + 1]), + i => _ = list.RemoveMany(x => x % StressSettings.RemoveModulus == i % StressSettings.RemoveModulus), + i => + { + if (random.OneIn(StressSettings.RareOdds)) + { + list.Clear(); + } + }, + ]; + + for (var i = 0; i < StressSettings.OperationsPerWorker; i++) + { + actions[random.Next(actions.Length)](random.Next(StressSettings.Universe)); + } + } + + /// Performs conflicting writes on a small key universe. + /// The dictionary to mutate. + /// The random source for this worker. + internal static void ConflictingDictionaryWrites(QuaternaryDictionary dictionary, StressRandom random) + { + Action[] actions = + [ + k => dictionary.AddOrUpdate(k, random.Next(StressSettings.ValueRange)), + k => dictionary.AddOrUpdate(k, random.Next(StressSettings.ValueRange)), + k => _ = dictionary.TryAdd(k, random.Next(StressSettings.ValueRange)), + k => _ = dictionary.Remove(k), + k => _ = dictionary.Remove(k), + k => dictionary.AddRange([new(k, 1), new(k + 1, 1)]), + k => dictionary.RemoveKeys([k, k + 1]), + k => + { + if (random.OneIn(ClearOdds)) + { + dictionary.Clear(); + } + }, + ]; + + for (var i = 0; i < StressSettings.OperationsPerWorker; i++) + { + actions[random.Next(actions.Length)](random.Next(StressSettings.Universe)); + } + } + + /// Applies a dictionary notification to a replica of the dictionary. + /// The replica to update. + /// The lock guarding the replica. + /// The notification to apply. + internal static void ApplyToReplica(Dictionary replica, Lock gate, CacheNotify> notification) + { + lock (gate) + { + switch (notification.Action) + { + case CacheAction.Added or CacheAction.Updated: + { + replica[notification.Item.Key] = notification.Item.Value; + break; + } + + case CacheAction.Removed: + { + _ = replica.Remove(notification.Item.Key); + break; + } + + case CacheAction.Cleared: + { + replica.Clear(); + break; + } + + case CacheAction.BatchAdded: + { + for (var i = 0; i < notification.Batch!.Count; i++) + { + replica[notification.Batch.Items[i].Key] = notification.Batch.Items[i].Value; + } + + break; + } + + case CacheAction.BatchRemoved: + { + for (var i = 0; i < notification.Batch!.Count; i++) + { + _ = replica.Remove(notification.Batch.Items[i].Key); + } + + break; + } + + default: + break; + } + } + } +} diff --git a/src/tests/ReactiveList.Tests/ControllableSequencer.cs b/src/tests/ReactiveList.Tests/ControllableSequencer.cs new file mode 100644 index 00000000..816dae9c --- /dev/null +++ b/src/tests/ReactiveList.Tests/ControllableSequencer.cs @@ -0,0 +1,119 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Holds scheduled work until a test runs it, and lets a test interleave other calls while a schedule request is in progress. +internal sealed class ControllableSequencer : ISequencer +{ + /// Guards . + private readonly Lock _gate = new(); + + /// The work waiting to run. + private readonly Queue _queued = []; + + /// The number of schedule requests received. + private int _requests; + + /// + public DateTimeOffset Now => Sequencer.Immediate.Now; + +#if !REACTIVELIST_REACTIVE + /// + public long Timestamp => Sequencer.Immediate.Timestamp; +#endif + + /// Gets or sets the callback that decides whether the request with the given one-based ordinal runs inline before the schedule call returns. + internal Func? RunInline { get; set; } + + /// Gets or sets the callback invoked with the ordinal of each request after it was accepted and before the schedule call returns. + internal Action? Accepted { get; set; } + + /// Gets the number of schedule requests received. + internal int Requests => Volatile.Read(ref _requests); + + /// Gets the number of work items waiting to run. + internal int QueuedCount + { + get + { + lock (_gate) + { + return _queued.Count; + } + } + } + +#if REACTIVELIST_REACTIVE + /// + public IDisposable Schedule(TState state, Func action) + { + var ticket = new System.Reactive.Disposables.BooleanDisposable(); + Accept(() => + { + if (!ticket.IsDisposed) + { + _ = action(this, state); + } + }); + return ticket; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IDisposable Schedule(TState state, TimeSpan dueTime, Func action) => Schedule(state, action); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IDisposable Schedule(TState state, DateTimeOffset dueTime, Func action) => Schedule(state, action); +#else + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Schedule(IWorkItem item) => Accept(item.Execute); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Schedule(IWorkItem item, long dueTimestamp) => Accept(item.Execute); +#endif + + /// Runs every queued work item, including work queued while running. + internal void RunAll() + { + while (true) + { + Action next; + lock (_gate) + { + if (_queued.Count == 0) + { + return; + } + + next = _queued.Dequeue(); + } + + next(); + } + } + + /// Accepts one schedule request. + /// Runs the requested work. + private void Accept(Action run) + { + var ordinal = Interlocked.Increment(ref _requests); + if (RunInline?.Invoke(ordinal) == true) + { + run(); + } + else + { + lock (_gate) + { + _queued.Enqueue(run); + } + } + + Accepted?.Invoke(ordinal); + } +} diff --git a/src/tests/ReactiveList.Tests/CoreCoverageTests.cs b/src/tests/ReactiveList.Tests/CoreCoverageTests.cs index 955345fd..faa9d9f0 100644 --- a/src/tests/ReactiveList.Tests/CoreCoverageTests.cs +++ b/src/tests/ReactiveList.Tests/CoreCoverageTests.cs @@ -157,14 +157,14 @@ public async Task CacheNotifyExtensions_ShouldFilterProjectAndCountNotifications public async Task CacheNotifyExtensions_ShouldBufferThrottleObserveAndDisposeBatches() { var notification = new CacheNotify(CacheAction.Added, 1); - var buffered = Collect(ObservableMixins.ToEnumerable(new[] { notification }.ToObservable() - .BufferNotifications(TimeSpan.FromMilliseconds(1)))); - var emptyBuffered = Collect(ObservableMixins.ToEnumerable(Array.Empty>().ToObservable() - .BufferNotifications(TimeSpan.FromMilliseconds(1)))); - var throttled = Collect(ObservableMixins.ToEnumerable(new[] { notification }.ToObservable() - .ThrottleNotifications(TimeSpan.Zero))); - var observed = Collect(ObservableMixins.ToEnumerable(new[] { notification }.ToObservable() - .ObserveOnScheduler(Sequencer.Immediate))); + var buffered = Collect(new[] { notification }.ToObservable() + .BufferNotifications(TimeSpan.FromMilliseconds(1))); + var emptyBuffered = Collect(Array.Empty>().ToObservable() + .BufferNotifications(TimeSpan.FromMilliseconds(1))); + var throttled = Collect(new[] { notification }.ToObservable() + .ThrottleNotifications(TimeSpan.Zero)); + var observed = Collect(new[] { notification }.ToObservable() + .ObserveOnScheduler(Sequencer.Immediate)); await Assert.That(await Assert.That(await Assert.That(buffered).HasSingleItem()).HasSingleItem()).IsSameReferenceAs(notification); await Assert.That(emptyBuffered).IsEmpty(); @@ -270,8 +270,8 @@ public async Task ToChangeSets_ShouldExpandBatchesSinglesAndFilterEmptyChanges() new CacheNotify(CacheAction.BatchRemoved, default), }; - var changeSets = Collect(ObservableMixins.ToEnumerable(notifications.ToObservable() - .ToChangeSets())); + var changeSets = Collect(notifications.ToObservable() + .ToChangeSets()); await Assert.That(changeSets).Count().IsEqualTo(CoverageValueFive); await Assert.That(changeSets[0]).Count().IsEqualTo(CoverageValueTwo); @@ -585,7 +585,7 @@ public async Task ObservableMixins_ShouldCoverErrorAndCompletionBranches() return ReactiveUI.Primitives.Disposables.Scope.Empty; }); - Action enumerate = () => _ = Collect(ObservableMixins.ToEnumerable(throwing)); + Action enumerate = () => _ = Collect(throwing); await Assert.That(enumerate).Throws(); #if !REACTIVELIST_REACTIVE @@ -699,10 +699,10 @@ public async Task GroupBy_ShouldPropagateErrorsToGroupsAndOuterSubscriber() public async Task SelectChanges_ShouldReturnEmptyChangeSetForEmptyInput() { var source = new[] { ChangeSet.Empty }.ToObservable(); - var results = Collect(ObservableMixins.ToEnumerable( + var results = Collect( ReactiveListExtensions.SelectChanges( source, - (Func)(static value => value.ToString())))); + (Func)(static value => value.ToString()))); await Assert.That((await Assert.That(results).HasSingleItem()).Count).IsEqualTo(0); } @@ -744,6 +744,29 @@ private static PooledBatch CreateStringBatch(params string[] values) /// The materialized items. private static List Collect(IEnumerable source) => new(source); + /// Collects everything a source that completes synchronously delivers, rethrowing its error. + /// The item type. + /// The observable to subscribe to. + /// The delivered items. + /// Thrown when the source has not completed once subscribing returns. + private static List Collect(IObservable source) + { + List values = []; + Exception? error = null; + var completed = false; + using var subscription = source.Subscribe( + values.Add, + ex => error = ex, + () => completed = true); + + if (error is not null) + { + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(error).Throw(); + } + + return completed ? values : throw new InvalidOperationException("The source did not complete synchronously."); + } + /// Materializes a non-generic sequence through explicit iteration. /// The expected sequence item type. /// The sequence to materialize. diff --git a/src/tests/ReactiveList.Tests/DictionaryModelRun.cs b/src/tests/ReactiveList.Tests/DictionaryModelRun.cs new file mode 100644 index 00000000..09a4612b --- /dev/null +++ b/src/tests/ReactiveList.Tests/DictionaryModelRun.cs @@ -0,0 +1,408 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Runs generated operations against a and a model dictionary. +/// The key type. +internal sealed class DictionaryModelRun + where TKey : notnull +{ + /// The key modulus of the first value index. + internal const int FirstModulus = 3; + + /// The name of the first value index. + private const string FirstIndex = "first"; + + /// The name of the second value index. + private const string SecondIndex = "second"; + + /// The name of the value index added part way through a run. + private const string LateIndex = "late"; + + /// The key modulus of the second value index. + private const int SecondModulus = 5; + + /// The key combination multiplier of the late index. + private const int LateMultiplier = 100; + + /// A value index key that no generated value produces. + private const int AbsentKey = -7; + + /// The number of argument collection shapes the operations rotate through. + private const int ShapeCount = 3; + + /// The divisor that decides whether an edit clears the dictionary. + private const int ClearDivisor = 4; + + /// The smallest modulus a remove-by-predicate operation uses. + private const int MinimumRemoveModulus = 2; + + /// The operation kind that adds a new key and throws for an existing one. + private const int AddKind = 0; + + /// The operation kind that tries to add a key. + private const int TryAddKind = 1; + + /// The operation kind that adds or updates a key. + private const int AddOrUpdateKind = 2; + + /// The operation kind that sets through the indexer. + private const int IndexerSetKind = 3; + + /// The operation kind that removes a key. + private const int RemoveKind = 4; + + /// The operation kind that removes a key and value pair. + private const int RemovePairKind = 5; + + /// The operation kind that adds a batch. + private const int AddRangeKind = 6; + + /// The operation kind that removes a batch of keys. + private const int RemoveKeysKind = 7; + + /// The operation kind that removes by predicate. + private const int RemoveManyKind = 8; + + /// The operation kind that edits in a batch. + private const int EditKind = 9; + + /// The operation kind that clears the dictionary. + private const int ClearKind = 10; + + /// The operation kind that adds the late value index. + private const int AddLateIndexKind = 11; + + /// Creates a key from an identity. + private readonly Func _make; + + /// Initializes a new instance of the class. + /// Creates a key from an identity. + internal DictionaryModelRun(Func make) => _make = make; + + /// Applies the operations to both the dictionary and the model, checking after each one. + /// The operations to apply. + internal void Execute(List operations) + { + using var dictionary = new QuaternaryDictionary(); + var model = new Dictionary(); + dictionary.AddValueIndex(FirstIndex, static v => v % FirstModulus); + dictionary.AddValueIndex(SecondIndex, static v => v % SecondModulus); + var hasLateIndex = false; + + foreach (var operation in operations) + { + hasLateIndex |= Apply(dictionary, model, operation); + Verify(dictionary, model, hasLateIndex); + } + } + + /// Runs two actions and checks they throw the same exception type, or both succeed. + /// The action on the collection under test. + /// The action on the model. + /// A description of the operation. + private static void SameOutcome(Action actual, Action expected, string what) + { + var actualType = Capture(actual); + var expectedType = Capture(expected); + FuzzSupport.AreEqual(actualType, expectedType, $"{what} exception"); + } + + /// Runs an action and reports the type of any exception it throws. + /// The action to run. + /// The exception type name, or an empty string when none was thrown. + private static string Capture(Action action) + { + try + { + action(); + return string.Empty; + } + catch (ArgumentException) + { + return nameof(ArgumentException); + } + } + + /// Applies the edit operation to a dictionary. + /// The dictionary to edit. + /// The first key. + /// The second key. + /// The third key. + /// The operation describing the edit. + private static void Edit(IDictionary target, TKey key, TKey other, TKey third, FuzzOperation operation) + { + target[key] = operation.B; + _ = target.Remove(other); + _ = Capture(() => target.Add(third, operation.A)); + if (operation.C % ClearDivisor == 0) + { + target.Clear(); + } + + target[third] = operation.A; + } + + /// Removes a batch with a repeated key from the dictionary and the model. + /// The dictionary under test. + /// The model dictionary. + /// The operation choosing the collection shape. + /// The first key. + /// The second key. + private static void RemoveKeys(QuaternaryDictionary dictionary, Dictionary model, FuzzOperation operation, TKey key, TKey other) + { + var keys = new[] { key, other, key }; + dictionary.RemoveKeys(operation.C % ShapeCount == 0 ? keys : new List(keys)); + foreach (var k in keys) + { + _ = model.Remove(k); + } + } + + /// Removes entries by value predicate from the dictionary and the model. + /// The dictionary under test. + /// The model dictionary. + /// The operation choosing the predicate. + private static void RemoveMany(QuaternaryDictionary dictionary, Dictionary model, FuzzOperation operation) + { + var modulus = (operation.B % FirstModulus) + MinimumRemoveModulus; + var remainder = operation.A % modulus; + var expected = new List(); + foreach (var pair in model) + { + if (pair.Value % modulus == remainder) + { + expected.Add(pair.Key); + } + } + + foreach (var k in expected) + { + _ = model.Remove(k); + } + + FuzzSupport.AreEqual(dictionary.RemoveMany(p => p.Value % modulus == remainder), expected.Count, "RemoveMany count"); + } + + /// Wraps pairs in one of several collection shapes the dictionary accepts. + /// The operation choosing the shape. + /// The pairs. + /// The pairs as an array, a list, or a lazy sequence. + private static IEnumerable> Argument(FuzzOperation operation, KeyValuePair[] pairs) => + (operation.A % ShapeCount) switch + { + 0 => pairs, + 1 => new List>(pairs), + _ => Enumerable.Select(pairs, static p => p), + }; + + /// Adds a batch with a repeated key to the dictionary and the model. + /// The dictionary under test. + /// The model dictionary. + /// The operation choosing the collection shape. + /// The first key. + /// The second key. + private static void AddRange(QuaternaryDictionary dictionary, Dictionary model, FuzzOperation operation, TKey key, TKey other) + { + KeyValuePair[] pairs = + [ + new(key, operation.B), + new(other, operation.C), + new(key, operation.C), + ]; + dictionary.AddRange(Argument(operation, pairs)); + foreach (var pair in pairs) + { + model[pair.Key] = pair.Value; + } + } + + /// Applies one single-entry operation to the dictionary and the model. + /// The dictionary under test. + /// The model dictionary. + /// The operation to apply. + /// The key the operation targets. + private static void ApplySingle(QuaternaryDictionary dictionary, Dictionary model, FuzzOperation operation, TKey key) + { + switch (operation.Kind) + { + case AddKind: + { + SameOutcome(() => dictionary.Add(key, operation.B), () => model.Add(key, operation.B), "Add"); + break; + } + + case TryAddKind: + { + FuzzSupport.AreEqual(dictionary.TryAdd(key, operation.B), model.TryAdd(key, operation.B), "TryAdd"); + break; + } + + case AddOrUpdateKind: + { + dictionary.AddOrUpdate(key, operation.B); + model[key] = operation.B; + break; + } + + case IndexerSetKind: + { + dictionary[key] = operation.C; + model[key] = operation.C; + break; + } + + case RemoveKind: + { + FuzzSupport.AreEqual(dictionary.Remove(key), model.Remove(key), "Remove"); + break; + } + + default: + { + var pair = new KeyValuePair(key, operation.B); + FuzzSupport.AreEqual(dictionary.Remove(pair), ((ICollection>)model).Remove(pair), "Remove pair"); + break; + } + } + } + + /// Checks the lookups for one key. + /// The dictionary under test. + /// The model dictionary. + /// The key to query. + private static void VerifyKey(QuaternaryDictionary dictionary, Dictionary model, TKey key) + { + var found = model.TryGetValue(key, out var expected); + FuzzSupport.AreEqual(dictionary.TryGetValue(key, out var actual), found, $"TryGetValue {key}"); + FuzzSupport.AreEqual(actual, found ? expected : 0, $"TryGetValue value {key}"); + FuzzSupport.AreEqual(dictionary.ContainsKey(key), found, $"ContainsKey {key}"); + FuzzSupport.AreEqual(dictionary.Lookup(key).HasValue, found, $"Lookup {key}"); + FuzzSupport.AreEqual(dictionary.Contains(new(key, expected)), found, $"Contains pair {key}"); + } + + /// Checks the value index lookups for the keys of one value. + /// The dictionary under test. + /// The model dictionary. + /// The value whose index keys are queried. + /// Whether the late index exists. + private static void VerifyValueIndexes(QuaternaryDictionary dictionary, Dictionary model, int value, bool hasLateIndex) + { + var first = value % FirstModulus; + var second = value % SecondModulus; + FuzzSupport.SameMultiset( + dictionary.GetValuesBySecondaryIndex(FirstIndex, first), + model.Values.Where(v => v % FirstModulus == first), + $"first value index {first}"); + FuzzSupport.SameMultiset( + dictionary.GetValuesBySecondaryIndex(SecondIndex, second), + model.Values.Where(v => v % SecondModulus == second), + $"second value index {second}"); + FuzzSupport.IsTrue(dictionary.ValueMatchesSecondaryIndex(FirstIndex, value, first), "value matches its own key"); + if (!hasLateIndex) + { + return; + } + + var late = (first * LateMultiplier) + second; + FuzzSupport.SameMultiset( + dictionary.GetValuesBySecondaryIndex(LateIndex, late), + model.Values.Where(v => (((v % FirstModulus) * LateMultiplier) + (v % SecondModulus)) == late), + $"late value index {late}"); + } + + /// Applies one operation to the dictionary and the model. + /// The dictionary under test. + /// The model dictionary. + /// The operation to apply. + /// when the operation added the late index. + private bool Apply(QuaternaryDictionary dictionary, Dictionary model, FuzzOperation operation) + { + var key = _make(operation.A); + var other = _make(operation.B); + if (operation.Kind <= RemovePairKind) + { + ApplySingle(dictionary, model, operation, key); + return false; + } + + switch (operation.Kind) + { + case AddRangeKind: + { + AddRange(dictionary, model, operation, key, other); + break; + } + + case RemoveKeysKind: + { + RemoveKeys(dictionary, model, operation, key, other); + break; + } + + case RemoveManyKind: + { + RemoveMany(dictionary, model, operation); + break; + } + + case EditKind: + { + var third = _make(operation.C); + dictionary.Edit(d => Edit(d, key, other, third, operation)); + Edit(model, key, other, third, operation); + break; + } + + case ClearKind: + { + dictionary.Clear(); + model.Clear(); + break; + } + + case AddLateIndexKind: + { + dictionary.AddValueIndex(LateIndex, static v => ((v % FirstModulus) * LateMultiplier) + (v % SecondModulus)); + return true; + } + + default: + { + dictionary.AddOrUpdate(other, operation.C); + model[other] = operation.C; + break; + } + } + + return false; + } + + /// Checks every observable aspect of the dictionary against the model. + /// The dictionary under test. + /// The model dictionary. + /// Whether the late index exists. + private void Verify(QuaternaryDictionary dictionary, Dictionary model, bool hasLateIndex) + { + FuzzSupport.AreEqual(dictionary.Count, model.Count, "Count"); + FuzzSupport.SameMultiset(dictionary, model, "enumeration"); + FuzzSupport.SameMultiset(dictionary.ToArray(), model, "ToArray"); + FuzzSupport.SameMultiset(dictionary.Keys, model.Keys, "Keys"); + FuzzSupport.SameMultiset(dictionary.Values, model.Values, "Values"); + + var copy = new KeyValuePair[model.Count + ShapeCount - 1]; + dictionary.CopyTo(copy, 1); + FuzzSupport.SameMultiset(copy.AsSpan(1, model.Count).ToArray(), model, "CopyTo"); + + for (var id = 0; id < FuzzSupport.Universe; id++) + { + VerifyKey(dictionary, model, _make(id)); + VerifyValueIndexes(dictionary, model, id, hasLateIndex); + } + + FuzzSupport.IsTrue(!dictionary.GetValuesBySecondaryIndex(FirstIndex, AbsentKey).Any(), "absent first key is empty"); + FuzzSupport.IsTrue(!dictionary.GetValuesBySecondaryIndex("missing", 1).Any(), "unknown index is empty"); + } +} diff --git a/src/tests/ReactiveList.Tests/DictionaryStressWorkload.cs b/src/tests/ReactiveList.Tests/DictionaryStressWorkload.cs new file mode 100644 index 00000000..5d43cc66 --- /dev/null +++ b/src/tests/ReactiveList.Tests/DictionaryStressWorkload.cs @@ -0,0 +1,145 @@ +// 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. + +namespace ReactiveList.Tests; + +/// A multi-threaded mixed workload against a dictionary with value indexes and streams. +internal sealed class DictionaryStressWorkload +{ + /// The seed multiplier that separates the workers. + private const int SeedFactor = 37; + + /// The number of keys the value index uses. + private const int ValueIndexKeys = 4; + + /// The name of the value index. + private const string ModIndex = "mod"; + + /// The seed that makes each worker's operation sequence reproducible. + private readonly int _seed; + + /// The dictionary under stress. + private readonly QuaternaryDictionary _dictionary = []; + + /// Initializes a new instance of the class. + /// The seed for the workers. + internal DictionaryStressWorkload(int seed) => _seed = seed; + + /// Runs the workload and checks the dictionary at quiescence. + /// A task that completes when the checks pass. + /// The workload did not finish in time. + internal async Task RunAsync() + { + _dictionary.AddValueIndex(ModIndex, static v => v % ValueIndexKeys); + var workers = new Task[StressSettings.WorkerCount]; + for (var worker = 0; worker < workers.Length; worker++) + { + var random = new StressRandom(unchecked((_seed * SeedFactor) + worker)); + workers[worker] = Task.Run(() => Work(random)); + } + + try + { + await Task.WhenAll(workers).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + } + catch (TimeoutException) + { + throw new InvalidOperationException($"Dictionary workload did not finish in time (seed {_seed}): deadlock suspected."); + } + + Verify(); + _dictionary.Dispose(); + } + + /// Checks Count, contents, and every value index at quiescence. + private void Verify() + { + var contents = _dictionary.ToArray(); + FuzzSupport.AreEqual(_dictionary.Count, contents.Length, "Count equals contents"); + FuzzSupport.AreEqual(_dictionary.Keys.Count, contents.Length, "Keys count equals contents"); + for (var key = 0; key < ValueIndexKeys; key++) + { + FuzzSupport.SameMultiset( + _dictionary.GetValuesBySecondaryIndex(ModIndex, key), + contents.Select(static p => p.Value).Where(v => v % ValueIndexKeys == key), + $"value index {key}"); + } + } + + /// Performs random operations until the budget is spent. + /// The random source for this worker. + private void Work(StressRandom random) + { + Action[] actions = + [ + _dictionary.AddOrUpdate, + _dictionary.AddOrUpdate, + (key, value) => _ = _dictionary.TryAdd(key, value), + (key, value) => _ = _dictionary.Remove(key), + (key, value) => _ = _dictionary.Remove(key), + (key, value) => _dictionary.AddRange([new(key, value), new(key + 1, value + 1)]), + (key, value) => _dictionary.RemoveKeys([key, key + 1]), + (key, value) => _ = _dictionary.RemoveMany(p => p.Value % StressSettings.RemoveModulus == value % StressSettings.RemoveModulus), + (key, value) => _dictionary.Edit(d => + { + d[key] = value; + _ = d.Remove(key + 1); + }), + (key, value) => + { + if (random.OneIn(StressSettings.RareOdds)) + { + _dictionary.Clear(); + } + }, + (key, value) => _ = _dictionary.ToArray(), + (key, value) => Enumerate(), + (key, value) => _ = _dictionary.Keys.Count + _dictionary.Values.Count, + (key, value) => _ = _dictionary.TryGetValue(key, out _) && _dictionary.GetValuesBySecondaryIndex(ModIndex, value % ValueIndexKeys).Any(), + SubscribeBriefly, + (key, value) => _dictionary[key] = value, + (key, value) => CopyWhileSized(), + (key, value) => _ = _dictionary.ContainsKey(key), + ]; + + for (var i = 0; i < StressSettings.OperationsPerWorker; i++) + { + actions[random.Next(actions.Length)](random.Next(StressSettings.Universe), random.Next(StressSettings.ValueRange)); + } + } + + /// Enumerates the dictionary while it changes. + private void Enumerate() + { + foreach (var pair in _dictionary) + { + _ = pair.Key; + } + } + + /// Subscribes to the stream, writes an entry, and unsubscribes. + /// The key to write. + /// The value to write. + private void SubscribeBriefly(int key, int value) + { + using (_dictionary.Stream.Subscribe(static _ => { })) + { + _dictionary.AddOrUpdate(key, value); + } + } + + /// Copies the dictionary into an array sized from an earlier count. + private void CopyWhileSized() + { + var copy = new KeyValuePair[_dictionary.Count + StressSettings.CopySpare]; + try + { + _dictionary.CopyTo(copy, 0); + } + catch (ArgumentException) + { + // The dictionary grew after the array was sized. + } + } +} diff --git a/src/tests/ReactiveList.Tests/DisposalGateTests.cs b/src/tests/ReactiveList.Tests/DisposalGateTests.cs new file mode 100644 index 00000000..95395d8f --- /dev/null +++ b/src/tests/ReactiveList.Tests/DisposalGateTests.cs @@ -0,0 +1,27 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies the open and closed states of . +public sealed class DisposalGateTests +{ + /// Verifies the gate reports closed only after it was closed and then refuses work. + /// A task representing the asynchronous test. + [Test] + public async Task Close_OpenGate_ReportsClosedAndRefusesWork() + { + var gate = new DisposalGate(); + + await Assert.That(gate.IsClosed).IsFalse(); + await Assert.That(gate.TryEnter()).IsTrue(); + gate.Exit(); + + gate.Close(); + + await Assert.That(gate.IsClosed).IsTrue(); + await Assert.That(gate.TryEnter()).IsFalse(); + await Assert.That(gate.IsIdle).IsTrue(); + } +} diff --git a/src/tests/ReactiveList.Tests/DisposedCollectionSubscriptionTests.cs b/src/tests/ReactiveList.Tests/DisposedCollectionSubscriptionTests.cs new file mode 100644 index 00000000..de342677 --- /dev/null +++ b/src/tests/ReactiveList.Tests/DisposedCollectionSubscriptionTests.cs @@ -0,0 +1,215 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Subscribing to any stream of a disposed collection must complete the observer immediately, without throwing. +public sealed class DisposedCollectionSubscriptionTests +{ + /// The number of subscribe-versus-dispose races per run. + private const int RaceIterations = 400; + + /// The number of threads that start a race together. + private const int RaceParticipants = 2; + + /// Every stream of a disposed completes a new subscriber, whether or not the stream was used before disposal. + /// Whether the streams were subscribed to before the list was disposed. + /// A task representing the asynchronous test. + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task ReactiveList_SubscribeAfterDispose_CompletesEveryStream(bool usedBeforeDispose) + { + var list = new ReactiveList([1]); + if (usedBeforeDispose) + { + UseEveryStream(list); + } + + list.Dispose(); + + var probes = new List(); + Action subscribeAll = () => SubscribeEveryStream(list, probes); + + await Assert.That(subscribeAll).ThrowsNothing(); + foreach (var probe in probes) + { + await Assert.That(probe.Completed()).IsTrue(); + await Assert.That(probe.Error()).IsNull(); + } + } + + /// Every stream of a disposed completes a new subscriber. + /// Whether the streams were subscribed to before the list was disposed. + /// A task representing the asynchronous test. + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task QuaternaryList_SubscribeAfterDispose_CompletesEveryStream(bool usedBeforeDispose) + { + var list = new QuaternaryList(); + if (usedBeforeDispose) + { + using var warmUp = list.Stream.Subscribe(static _ => { }); + using var versionedWarmUp = list.VersionedStream.Subscribe(static _ => { }); + } + + list.Dispose(); + + var stream = new LiveQueryRecorder>(); + var versioned = new LiveQueryRecorder>(); + Action subscribeAll = () => + { + using var first = list.Stream.Subscribe(stream); + using var second = list.VersionedStream.Subscribe(versioned); + list.CollectionChanged += static (_, _) => { }; + }; + + await Assert.That(subscribeAll).ThrowsNothing(); + await Assert.That(stream.Completed).IsTrue(); + await Assert.That(versioned.Completed).IsTrue(); + } + + /// Every stream of a disposed completes a new subscriber. + /// Whether the streams were subscribed to before the dictionary was disposed. + /// A task representing the asynchronous test. + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task QuaternaryDictionary_SubscribeAfterDispose_CompletesEveryStream(bool usedBeforeDispose) + { + var dictionary = new QuaternaryDictionary(); + if (usedBeforeDispose) + { + using var warmUp = dictionary.Stream.Subscribe(static _ => { }); + using var versionedWarmUp = dictionary.VersionedStream.Subscribe(static _ => { }); + } + + dictionary.Dispose(); + + var stream = new LiveQueryRecorder>>(); + var versioned = new LiveQueryRecorder>>(); + Action subscribeAll = () => + { + using var first = dictionary.Stream.Subscribe(stream); + using var second = dictionary.VersionedStream.Subscribe(versioned); + dictionary.CollectionChanged += static (_, _) => { }; + }; + + await Assert.That(subscribeAll).ThrowsNothing(); + await Assert.That(stream.Completed).IsTrue(); + await Assert.That(versioned.Completed).IsTrue(); + } + + /// Creating a view over a disposed list does not throw, because reads keep working after disposal. + /// A task representing the asynchronous test. + [Test] + public async Task CreateView_OverDisposedList_DoesNotThrow() + { + var list = new ReactiveList([1]); + list.Dispose(); + + Action create = () => list.CreateView(static _ => true, Sequencer.Immediate).Dispose(); + + await Assert.That(create).ThrowsNothing(); + } + + /// A subscription that races disposal either receives the completion or is completed on the spot, and never throws. + /// A task representing the asynchronous test. + [Test] + public async Task ReactiveList_SubscribeRacingDispose_NeverThrowsAndAlwaysCompletes() + { + for (var i = 0; i < RaceIterations; i++) + { + var list = new ReactiveList([1]); + using var start = new Barrier(RaceParticipants); + var probes = new List(); + var subscribing = Task.Run(() => + { + start.SignalAndWait(); + SubscribeEveryStream(list, probes); + }); + var disposing = Task.Run(() => + { + start.SignalAndWait(); + list.Dispose(); + }); + + await Task.WhenAll(subscribing, disposing); + await TestWaitHelpers.WaitUntilAsync(() => probes.TrueForAll(static probe => probe.Completed())); + } + } + + /// A subscription that races disposal of a sharded list never throws and always completes. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryList_SubscribeRacingDispose_NeverThrowsAndAlwaysCompletes() + { + for (var i = 0; i < RaceIterations; i++) + { + var list = new QuaternaryList { 1 }; + using var start = new Barrier(RaceParticipants); + var stream = new LiveQueryRecorder>(); + var versioned = new LiveQueryRecorder>(); + var subscribing = Task.Run(() => + { + start.SignalAndWait(); + _ = list.Stream.Subscribe(stream); + _ = list.VersionedStream.Subscribe(versioned); + }); + var disposing = Task.Run(() => + { + start.SignalAndWait(); + list.Dispose(); + }); + + await Task.WhenAll(subscribing, disposing); + await TestWaitHelpers.WaitUntilAsync(() => stream.Completed && versioned.Completed); + } + } + + /// Subscribes to every stream of a list once so its lazily created state exists. + /// The list. + private static void UseEveryStream(ReactiveList list) + { + using var stream = list.Stream.Subscribe(static _ => { }); + using var added = list.Added.Subscribe(static _ => { }); + using var removed = list.Removed.Subscribe(static _ => { }); + using var changed = list.Changed.Subscribe(static _ => { }); + using var current = list.CurrentItems.Subscribe(static _ => { }); + using var versioned = list.VersionedStream.Subscribe(static _ => { }); + } + + /// Subscribes a recorder to every stream of a list. + /// The list. + /// Receives a probe for each subscription. + private static void SubscribeEveryStream(ReactiveList list, List probes) + { + probes.Add(Track(list.Stream)); + probes.Add(Track(list.Added)); + probes.Add(Track(list.Removed)); + probes.Add(Track(list.Changed)); + probes.Add(Track(list.CurrentItems)); + probes.Add(Track(list.VersionedStream)); + var direct = new LiveQueryRecorder>(); + _ = list.Subscribe(direct); + probes.Add(new(() => direct.Completed, () => direct.Error)); + } + + /// Subscribes a new recorder to a stream. + /// The element type. + /// The stream. + /// A probe for the subscription. + private static Probe Track(IObservable stream) + { + var recorder = new LiveQueryRecorder(); + _ = stream.Subscribe(recorder); + return new(() => recorder.Completed, () => recorder.Error); + } + + /// Reads what one subscription saw. + /// Reports whether completion was delivered. + /// Reports the delivered error, if any. + private readonly record struct Probe(Func Completed, Func Error); +} diff --git a/src/tests/ReactiveList.Tests/DrainStateTests.cs b/src/tests/ReactiveList.Tests/DrainStateTests.cs new file mode 100644 index 00000000..b70d1574 --- /dev/null +++ b/src/tests/ReactiveList.Tests/DrainStateTests.cs @@ -0,0 +1,97 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks the hand-off between the delivering thread and publishers in . +public class DrainStateTests +{ + /// The state with one change queued behind the delivering thread. + private const int OneQueued = DrainState.DrainingBit + DrainState.QueuedStep; + + /// The state with two changes queued behind the delivering thread. + private const int TwoQueued = OneQueued + DrainState.QueuedStep; + + /// An item value placed in the queue. + private const int Item = 7; + + /// A queued item is counted and enqueued when the state did not move. + /// A task representing the asynchronous test. + [Test] + public async Task QueueBehind_StateUnchanged_CountsAndEnqueues() + { + var state = DrainState.DrainingBit; + Queue? pending = null; + var item = Item; + + var owner = DrainState.QueueBehind(ref state, ref pending, in item, DrainState.DrainingBit); + + await Assert.That(owner).IsFalse(); + await Assert.That(state).IsEqualTo(OneQueued); + await Assert.That(pending!.Dequeue()).IsEqualTo(Item); + } + + /// The caller becomes the delivering thread when ownership was released after the state was read. + /// A task representing the asynchronous test. + [Test] + public async Task QueueBehind_OwnershipReleased_BecomesOwner() + { + var state = 0; + Queue? pending = null; + var item = Item; + + var owner = DrainState.QueueBehind(ref state, ref pending, in item, DrainState.DrainingBit); + + await Assert.That(owner).IsTrue(); + await Assert.That(state).IsEqualTo(DrainState.DrainingBit); + await Assert.That(pending).IsNull(); + } + + /// The queue count is raised from the state that was seen when the state moved on after it was read. + /// A task representing the asynchronous test. + [Test] + public async Task QueueBehind_StateMovedOn_RetriesFromTheSeenState() + { + var state = OneQueued; + Queue? pending = null; + var item = Item; + + var owner = DrainState.QueueBehind(ref state, ref pending, in item, DrainState.DrainingBit); + + await Assert.That(owner).IsFalse(); + await Assert.That(state).IsEqualTo(TwoQueued); + await Assert.That(pending!.Count).IsEqualTo(1); + } + + /// A queued item is handed to the delivering thread and the queue count goes down. + /// A task representing the asynchronous test. + [Test] + public async Task TakeNext_QueuedItem_DequeuesAndLowersTheCount() + { + var state = OneQueued; + Queue? pending = new(); + pending.Enqueue(Item); + + var taken = DrainState.TakeNext(ref state, ref pending, new(), out var next); + + await Assert.That(taken).IsTrue(); + await Assert.That(next).IsEqualTo(Item); + await Assert.That(state).IsEqualTo(DrainState.DrainingBit); + } + + /// Ownership is released when nothing was queued. + /// A task representing the asynchronous test. + [Test] + public async Task TakeNext_NothingQueued_ReleasesOwnership() + { + var state = DrainState.DrainingBit; + Queue? pending = null; + + var taken = DrainState.TakeNext(ref state, ref pending, new(), out var next); + + await Assert.That(taken).IsFalse(); + await Assert.That(next).IsEqualTo(0); + await Assert.That(state).IsEqualTo(0); + } +} diff --git a/src/tests/ReactiveList.Tests/DynamicFilterRelayTests.cs b/src/tests/ReactiveList.Tests/DynamicFilterRelayTests.cs new file mode 100644 index 00000000..cce6bc3c --- /dev/null +++ b/src/tests/ReactiveList.Tests/DynamicFilterRelayTests.cs @@ -0,0 +1,42 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies how treats failures and completion. +public sealed class DynamicFilterRelayTests +{ + /// Verifies the first filter is recorded while probing and a probe failure or completion changes nothing. + /// A task representing the asynchronous test. + [Test] + public async Task OnNext_FirstFilter_IsRecordedWhileProbing() + { + using var source = new ScriptedViewSource(); + var relay = new DynamicFilterRelay(source); + + relay.OnNext(static _ => true); + relay.OnError(new InvalidOperationException()); + relay.OnCompleted(); + + await Assert.That(relay.HasInitial).IsTrue(); + } + + /// Verifies a failure while probing is ignored, and a failure after attaching is rethrown. + /// A task representing the asynchronous test. + [Test] + public async Task OnError_FailureIsRethrownOnlyWhenAttached() + { + using var source = new ScriptedViewSource(); + var relay = new DynamicFilterRelay(source); + relay.OnError(new InvalidOperationException()); + relay.OnCompleted(); + + await Assert.That(relay.HasInitial).IsFalse(); + + using var projection = new StreamProjection(source, static item => item, ViewSourceRules.Create(source, static _ => true), "Count"); + relay.Attach(projection); + + await Assert.That(() => relay.OnError(new InvalidOperationException())).Throws(); + } +} diff --git a/src/tests/ReactiveList.Tests/DynamicFilterSubscriptionTests.cs b/src/tests/ReactiveList.Tests/DynamicFilterSubscriptionTests.cs new file mode 100644 index 00000000..315d2691 --- /dev/null +++ b/src/tests/ReactiveList.Tests/DynamicFilterSubscriptionTests.cs @@ -0,0 +1,126 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies how ends when the stream or the predicates fail or complete. +public sealed class DynamicFilterSubscriptionTests +{ + /// Verifies a predicate sequence that fails while subscribing ends the subscription before the stream is observed. + /// A task representing the asynchronous test. + [Test] + public async Task Connect_PredicatesFailImmediately_EndsWithTheError() + { + var observer = new CountingObserver(); + using var subscription = new DynamicFilterSubscription(observer); + var stream = new ManualObservable>(); + var filters = Signal.Create>(static emit => + { + emit.OnError(new InvalidOperationException()); + return Scope.Empty; + }); + + subscription.Connect(stream, filters); + + await Assert.That(observer.Errors).IsEqualTo(1); + await Assert.That(stream.HasObserver).IsFalse(); + } + + /// Verifies a predicate failure that arrives while a stream failure is being delivered is ignored. + /// A task representing the asynchronous test. + [Test] + public async Task Fail_WhileAnotherFailureIsDelivered_IsIgnored() + { + var observer = new CountingObserver(); + using var subscription = new DynamicFilterSubscription(observer); + var stream = new ManualObservable>(); + var filters = new ManualObservable>(); + subscription.Connect(stream, filters); + observer.OnTerminal = () => filters.Fail(new InvalidOperationException()); + + stream.Fail(new InvalidOperationException()); + + await Assert.That(observer.Errors).IsEqualTo(1); + } + + /// Verifies a stream completion that arrives while a predicate failure is being delivered is ignored. + /// A task representing the asynchronous test. + [Test] + public async Task Complete_WhileAFailureIsDelivered_IsIgnored() + { + var observer = new CountingObserver(); + using var subscription = new DynamicFilterSubscription(observer); + var stream = new ManualObservable>(); + var filters = new ManualObservable>(); + subscription.Connect(stream, filters); + observer.OnTerminal = stream.Complete; + + filters.Fail(new InvalidOperationException()); + + await Assert.That(observer.Errors).IsEqualTo(1); + await Assert.That(observer.Completions).IsEqualTo(0); + } + + /// Verifies a failure or completion called directly after the subscription ended is ignored. + /// A task representing the asynchronous test. + [Test] + public async Task EndingTwice_ReportsOnlyTheFirstEnd() + { + var completedObserver = new CountingObserver(); + using var completing = new DynamicFilterSubscription(completedObserver); + var completingStream = new ManualObservable>(); + completing.Connect(completingStream, new ManualObservable>()); + completingStream.Complete(); + completing.Complete(); + + var failedObserver = new CountingObserver(); + using var failing = new DynamicFilterSubscription(failedObserver); + var failingStream = new ManualObservable>(); + failing.Connect(failingStream, new ManualObservable>()); + failingStream.Fail(new InvalidOperationException()); + failing.Fail(new ArgumentException()); + + await Assert.That(completedObserver.Completions).IsEqualTo(1); + await Assert.That(failedObserver.Errors).IsEqualTo(1); + } + + /// Counts the terminal calls an observer receives. + private sealed class CountingObserver : IObserver> + { + /// The number of failures received. + private int _errors; + + /// The number of completions received. + private int _completions; + + /// Gets the number of failures received. + internal int Errors => Volatile.Read(ref _errors); + + /// Gets the number of completions received. + internal int Completions => Volatile.Read(ref _completions); + + /// Gets or sets an action that runs while a terminal call is being delivered. + internal Action? OnTerminal { get; set; } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnNext(CacheNotify value) + { + } + + /// + public void OnError(Exception error) + { + _ = Interlocked.Increment(ref _errors); + OnTerminal?.Invoke(); + } + + /// + public void OnCompleted() + { + _ = Interlocked.Increment(ref _completions); + OnTerminal?.Invoke(); + } + } +} diff --git a/src/tests/ReactiveList.Tests/DynamicViewFuzzTests.cs b/src/tests/ReactiveList.Tests/DynamicViewFuzzTests.cs new file mode 100644 index 00000000..a94e6262 --- /dev/null +++ b/src/tests/ReactiveList.Tests/DynamicViewFuzzTests.cs @@ -0,0 +1,172 @@ +// 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. + +using CsCheck; + +namespace ReactiveList.Tests; + +/// Model-based fuzz tests for the dynamic filtered view with filter changes interleaved between mutations. +public class DynamicViewFuzzTests +{ + /// The number of generated cases per immediate property. + private const int Iterations = 150; + + /// The number of generated cases per throttled property. + private const int ThrottledIterations = 25; + + /// The longest generated mutation sequence. + private const int MaxOps = 25; + + /// The coalescing window for throttled cases, in milliseconds. + private const int ThrottleMilliseconds = 5; + + /// A filter change is generated for every operation whose second number is a multiple of this. + private const int FilterChangePeriod = 3; + + /// The smallest divisor a generated filter rejects. + private const int DivisorBase = 2; + + /// The number of distinct divisors a generated filter rejects. + private const int DivisorSpan = 5; + + /// A sentinel that passes every generated filter. + private const int MatchingSentinel = 1009; + + /// The dynamic filtered view follows both source mutations and filter changes when applied immediately. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task DynamicFilteredView_Immediate_ConvergesToFilteredSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static (initial, ops) => RunAsync(initial, ops, TimeSpan.Zero, Sequencer.Immediate), + iter: Iterations, + threads: 1); + + /// The dynamic filtered view converges when a throttle window coalesces changes on a background scheduler. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task DynamicFilteredView_Throttled_ConvergesToFilteredSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static (initial, ops) => RunAsync(initial, ops, TimeSpan.FromMilliseconds(ThrottleMilliseconds), ReactiveListScheduler.Default), + iter: ThrottledIterations, + threads: 1); + + /// A dynamic view over a reactive list follows both source mutations and filter changes. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task DynamicReactiveView_OverReactiveList_ConvergesToFilteredSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static async (initial, ops) => + { + using var list = new ReactiveList(); + list.AddRange(initial); + await RunUnorderedAsync(list, op => ViewFuzzSupport.Apply(list, op), ops, TimeSpan.Zero, Sequencer.Immediate); + }, + iter: Iterations, + threads: 1); + + /// A dynamic view over a quaternary list follows both source mutations and filter changes. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task DynamicReactiveView_OverQuaternaryList_ConvergesToFilteredSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static async (initial, ops) => + { + using var list = new QuaternaryList(); + list.AddRange(initial); + await RunUnorderedAsync(list, op => ViewFuzzSupport.Apply(list, op), ops, TimeSpan.Zero, Sequencer.Immediate); + }, + iter: Iterations, + threads: 1); + + /// A throttled dynamic view over a quaternary list converges on a background scheduler. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task DynamicReactiveView_OverQuaternaryList_Throttled_ConvergesToFilteredSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static async (initial, ops) => + { + using var list = new QuaternaryList(); + list.AddRange(initial); + await RunUnorderedAsync(list, op => ViewFuzzSupport.Apply(list, op), ops, TimeSpan.FromMilliseconds(ThrottleMilliseconds), ReactiveListScheduler.Default); + }, + iter: ThrottledIterations, + threads: 1); + + /// Applies the mutations and filter changes and checks the view against the source. + /// The initial items. + /// The mutations. + /// The coalescing window. + /// The scheduler that applies view changes. + /// A task representing the asynchronous check. + private static async Task RunAsync(int[] initial, ViewFuzzOp[] ops, TimeSpan throttle, ISequencer scheduler) + { + using var list = new ReactiveList(); + list.AddRange(initial); + var currentDivisor = DivisorBase; + using var filters = new BehaviorSignal>(static item => item % DivisorBase != 0); + using var view = new DynamicFilteredReactiveView(list, filters, scheduler, throttle); + + foreach (var op in ops) + { + ViewFuzzSupport.Apply(list, op); + if (op.B % FilterChangePeriod != 0) + { + continue; + } + + currentDivisor = DivisorBase + (op.A % DivisorSpan); + var divisor = currentDivisor; + filters.OnNext(item => item % divisor != 0); + } + + var snapshot = await ViewFuzzSupport.CaptureAfterDrainAsync(view, view.Items, MatchingSentinel, () => list.Add(MatchingSentinel)); + var expected = list.Where(item => item % currentDivisor != 0).ToArray(); + await Assert.That(snapshot).IsEquivalentTo(expected, CollectionOrdering.Matching); + } + + /// Applies the mutations and filter changes to a dynamic view and checks its items against the source, ignoring order. + /// The source the view observes. + /// Applies one mutation to the source. + /// The mutations. + /// The coalescing window. + /// The scheduler that applies view changes. + /// A task representing the asynchronous check. + private static async Task RunUnorderedAsync( + IReactiveSource source, + Action mutate, + ViewFuzzOp[] ops, + TimeSpan throttle, + ISequencer scheduler) + { + var currentDivisor = DivisorBase; + using var filters = new BehaviorSignal>(static item => item % DivisorBase != 0); + using var view = new DynamicReactiveView(source, filters, throttle, scheduler); + + foreach (var op in ops) + { + mutate(op); + if (op.B % FilterChangePeriod != 0) + { + continue; + } + + currentDivisor = DivisorBase + (op.A % DivisorSpan); + var divisor = currentDivisor; + filters.OnNext(item => item % divisor != 0); + } + + var finalDivisor = currentDivisor; + await ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Sorted(view.Items).SequenceEqual(ViewFuzzSupport.Sorted(source.ToArray().Where(item => item % finalDivisor != 0)))); + } +} diff --git a/src/tests/ReactiveList.Tests/EqualityCountingItem.cs b/src/tests/ReactiveList.Tests/EqualityCountingItem.cs new file mode 100644 index 00000000..7b384cf9 --- /dev/null +++ b/src/tests/ReactiveList.Tests/EqualityCountingItem.cs @@ -0,0 +1,38 @@ +// 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. + +namespace ReactiveList.Tests; + +/// A reference item that counts how often it is compared by value, so tests can detect linear searches. +/// The identity of the item. +internal sealed class EqualityCountingItem(int id) : IEquatable +{ + /// The number of value comparisons made since the last reset. + private static int _comparisons; + + /// Gets the number of value comparisons made since the last reset. + internal static int Comparisons => Volatile.Read(ref _comparisons); + + /// Gets the identity of the item. + internal int Id { get; } = id; + + /// + public bool Equals(EqualityCountingItem? other) + { + _ = Interlocked.Increment(ref _comparisons); + return other is not null && other.Id == Id; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override bool Equals(object? obj) => Equals(obj as EqualityCountingItem); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override int GetHashCode() => Id; + + /// Starts counting value comparisons from zero. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void ResetComparisons() => Volatile.Write(ref _comparisons, 0); +} diff --git a/src/tests/ReactiveList.Tests/ExtensionCoverageTests.cs b/src/tests/ReactiveList.Tests/ExtensionCoverageTests.cs index fc07e755..1d590ef1 100644 --- a/src/tests/ReactiveList.Tests/ExtensionCoverageTests.cs +++ b/src/tests/ReactiveList.Tests/ExtensionCoverageTests.cs @@ -178,7 +178,7 @@ public async Task FilterDynamic_DictionaryStream_ShouldFilterAddsBatchesAndPassR stream.OnNext(new(CacheAction.Cleared, default)); await Assert.That(GetActions(received)) - .IsEquivalentTo([CacheAction.Added, CacheAction.Removed, CacheAction.BatchOperation, CacheAction.BatchOperation, CacheAction.Cleared], CollectionOrdering.Matching); + .IsEquivalentTo([CacheAction.Added, CacheAction.Removed, CacheAction.BatchAdded, CacheAction.BatchRemoved, CacheAction.Cleared], CollectionOrdering.Matching); await Assert.That(received[0].Item.Value).IsEqualTo(AlphaItem); await Assert.That(received[1].Item.Value).IsEqualTo("beta"); var addedBatch = received[CoverageValueTwo].Batch!; @@ -387,7 +387,7 @@ public async Task QuaternaryListSecondaryIndexFilter_ShouldPassMatchingSingleAnd await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref singleCount) == CoverageValueFour && Volatile.Read(ref multipleCount) == CoverageValueFive); - await Assert.That(GetActions(singleKey)).IsEquivalentTo([CacheAction.Added, CacheAction.Removed, CacheAction.BatchOperation, CacheAction.BatchOperation], CollectionOrdering.Matching); + await Assert.That(GetActions(singleKey)).IsEquivalentTo([CacheAction.Added, CacheAction.Removed, CacheAction.BatchAdded, CacheAction.BatchRemoved], CollectionOrdering.Matching); await Assert.That(singleKey[0].Item).IsEqualTo(north); await Assert.That(singleKey[1].Item).IsEqualTo(north); var singleAddedBatch = singleKey[CoverageValueTwo].Batch!; @@ -396,7 +396,7 @@ public async Task QuaternaryListSecondaryIndexFilter_ShouldPassMatchingSingleAnd await Assert.That(await Assert.That(CopyBatchItems(singleRemovedBatch)).HasSingleItem()).IsEqualTo(northBatch); await Assert.That(GetActions(multipleKeys)) - .IsEquivalentTo([CacheAction.Added, CacheAction.Added, CacheAction.Removed, CacheAction.BatchOperation, CacheAction.BatchOperation], CollectionOrdering.Matching); + .IsEquivalentTo([CacheAction.Added, CacheAction.Added, CacheAction.Removed, CacheAction.BatchAdded, CacheAction.BatchRemoved], CollectionOrdering.Matching); var multipleAddedBatch = multipleKeys[CoverageValueThree].Batch!; var multipleRemovedBatch = multipleKeys[CoverageValueFour].Batch!; await Assert.That(CopyBatchItems(multipleAddedBatch)).IsEquivalentTo([northBatch, eastBatch]); @@ -449,13 +449,13 @@ public async Task QuaternaryDictionarySecondaryIndexFilter_ShouldPassMatchingSin await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref singleCount) == CoverageValueThree && Volatile.Read(ref multipleCount) == CoverageValueFour); - await Assert.That(GetActions(singleKey)).IsEquivalentTo([CacheAction.Added, CacheAction.Removed, CacheAction.BatchOperation], CollectionOrdering.Matching); + await Assert.That(GetActions(singleKey)).IsEquivalentTo([CacheAction.Added, CacheAction.Removed, CacheAction.BatchAdded], CollectionOrdering.Matching); await Assert.That(singleKey[0].Item.Value).IsEqualTo(north); await Assert.That(singleKey[1].Item.Value).IsEqualTo(north); var dictionarySingleBatch = singleKey[CoverageValueTwo].Batch!; await Assert.That(await Assert.That(CopyBatchItems(dictionarySingleBatch)).HasSingleItem()).IsEqualTo(northBatch); - await Assert.That(GetActions(multipleKeys)).IsEquivalentTo([CacheAction.Added, CacheAction.Added, CacheAction.Removed, CacheAction.BatchOperation], CollectionOrdering.Matching); + await Assert.That(GetActions(multipleKeys)).IsEquivalentTo([CacheAction.Added, CacheAction.Added, CacheAction.Removed, CacheAction.BatchAdded], CollectionOrdering.Matching); var dictionaryMultipleBatch = multipleKeys[CoverageValueThree].Batch!; await Assert.That(CopyBatchItems(dictionaryMultipleBatch)).IsEquivalentTo([northBatch, eastBatch]); diff --git a/src/tests/ReactiveList.Tests/FilteredViewEngineTests.cs b/src/tests/ReactiveList.Tests/FilteredViewEngineTests.cs new file mode 100644 index 00000000..be3a8b1c --- /dev/null +++ b/src/tests/ReactiveList.Tests/FilteredViewEngineTests.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. + +namespace ReactiveList.Tests; + +/// Verifies how follows refreshed items and replaced filters. +public sealed class FilteredViewEngineTests +{ + /// The smallest value the starting filter accepts. + private const int Threshold = 5; + + /// A value below the threshold that the first item starts with. + private const int Low = 1; + + /// A value the starting filter accepts and the second item starts with. + private const int Included = 6; + + /// A value below the threshold that the third item starts with. + private const int LowThird = 3; + + /// A value the starting filter accepts. + private const int Accepted = 9; + + /// The values the source starts with. + private static readonly int[] _initialValues = [Low, Included, LowThird]; + + /// Verifies a refreshed item enters, stays in and leaves the view as its value changes. + /// A task representing the asynchronous test. + [Test] + public async Task ItemRefreshed_ValueChanges_UpdatesMembership() + { + var (list, engine) = Create(); + using (list) + using (engine) + { + list[0].Value = Accepted; + engine.ItemRefreshed(0, list[0]); + await Assert.That(MutableValue.Values(engine.Filtered)).IsEquivalentTo([Accepted, Included], CollectionOrdering.Matching); + + engine.ItemRefreshed(1, list[1]); + await Assert.That(MutableValue.Values(engine.Filtered)).IsEquivalentTo([Accepted, Included], CollectionOrdering.Matching); + + list[1].Value = Low; + engine.ItemRefreshed(1, list[1]); + await Assert.That(MutableValue.Values(engine.Filtered)).IsEquivalentTo([Accepted], CollectionOrdering.Matching); + } + } + + /// Verifies a replacement filter that flips more items than the reset limit replaces the view in one step. + /// A task representing the asynchronous test. + [Test] + public async Task SetFilter_FlipsMoreThanTheResetLimit_ReplacesTheView() + { + var (list, engine) = Create(); + using (list) + using (engine) + { + engine.Start(TimeSpan.Zero, ReactiveListScheduler.Immediate); + engine.Filtered.ResetLimit = 1; + List actions = []; + ((INotifyCollectionChanged)engine.Filtered).CollectionChanged += (_, args) => actions.Add(args.Action); + + engine.SetFilter(static item => item.Value < Threshold); + + await Assert.That(MutableValue.Values(engine.Filtered)).IsEquivalentTo([Low, LowThird], CollectionOrdering.Matching); + await Assert.That(actions).IsEquivalentTo([NotifyCollectionChangedAction.Reset]); + } + } + + /// Creates a list of the initial values and an engine that accepts values from the threshold up. + /// The list and the engine. + private static (ReactiveList List, FilteredViewEngine Engine) Create() + { + ReactiveList list = []; + foreach (var value in _initialValues) + { + list.Add(new(value)); + } + + return (list, new(list, static item => item.Value >= Threshold)); + } +} diff --git a/src/tests/ReactiveList.Tests/FilteredViewRangeTests.cs b/src/tests/ReactiveList.Tests/FilteredViewRangeTests.cs new file mode 100644 index 00000000..05cbcae8 --- /dev/null +++ b/src/tests/ReactiveList.Tests/FilteredViewRangeTests.cs @@ -0,0 +1,81 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies a filtered view stays exact when a range is inserted into or removed from the middle of its source. +public sealed class FilteredViewRangeTests +{ + /// The number of items the source starts with. + private const int Initial = 1_000; + + /// The index the range is inserted at and removed from. + private const int Middle = 500; + + /// The number of items in the inserted and removed ranges. + private const int RangeSize = 300; + + /// The distance between the values removed one at a time. + private const int Stride = 3; + + /// The number of values removed one at a time. + private const int ByValueCount = 50; + + /// The values are included when they are divisible by this number. + private const int Divisor = 3; + + /// A range inserted in the middle lands in source order. + /// A task representing the asynchronous test. + [Test] + public async Task InsertRange_InTheMiddle_KeepsSourceOrder() + { + using var list = new ReactiveList(); + list.AddRange(Enumerable.Range(0, Initial).ToArray()); + using var view = new FilteredReactiveView(list, Included, Sequencer.Immediate, TimeSpan.Zero); + + list.InsertRange(Middle, Enumerable.Range(Initial, RangeSize).ToArray()); + + await Assert.That(view.Items).IsEquivalentTo(list.ToArray().Where(Included), CollectionOrdering.Matching); + } + + /// A range removed from the middle by position leaves the other items in source order. + /// A task representing the asynchronous test. + [Test] + public async Task RemoveRange_FromTheMiddle_KeepsSourceOrder() + { + using var list = new ReactiveList(); + list.AddRange(Enumerable.Range(0, Initial).ToArray()); + using var view = new FilteredReactiveView(list, Included, Sequencer.Immediate, TimeSpan.Zero); + + list.RemoveRange(Middle, RangeSize); + + await Assert.That(view.Items).IsEquivalentTo(list.ToArray().Where(Included), CollectionOrdering.Matching); + } + + /// Items removed by value, in an order unrelated to their positions, leave the other items in source order. + /// A task representing the asynchronous test. + [Test] + public async Task RemoveByValue_ScatteredItems_KeepsSourceOrder() + { + using var list = new ReactiveList(); + list.AddRange(Enumerable.Range(0, Initial).ToArray()); + using var view = new FilteredReactiveView(list, Included, Sequencer.Immediate, TimeSpan.Zero); + + var removed = new int[ByValueCount]; + for (var i = 0; i < removed.Length; i++) + { + removed[i] = (ByValueCount - i) * Stride * Stride; + } + + list.Remove(removed.AsEnumerable()); + + await Assert.That(view.Items).IsEquivalentTo(list.ToArray().Where(Included), CollectionOrdering.Matching); + } + + /// Tells whether a value belongs in the view. + /// The value. + /// when the value is divisible by the divisor. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool Included(int value) => value % Divisor == 0; +} diff --git a/src/tests/ReactiveList.Tests/FirstValueRelayTests.cs b/src/tests/ReactiveList.Tests/FirstValueRelayTests.cs new file mode 100644 index 00000000..70a6bb7e --- /dev/null +++ b/src/tests/ReactiveList.Tests/FirstValueRelayTests.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. + +namespace ReactiveList.Tests; + +/// Verifies how treats failures and completion. +public sealed class FirstValueRelayTests +{ + /// The first value a relay records. + private const int FirstValue = 7; + + /// Verifies the first value is recorded and later values reach the view, skipping the replay of the first. + /// A task representing the asynchronous test. + [Test] + public async Task OnNext_AfterAttach_ForwardsLaterValuesAndSkipsTheReplay() + { + var relay = new FirstValueRelay(); + List applied = []; + + relay.OnNext(FirstValue); + relay.OnNext(FirstValue + 1); + relay.Attach(applied.Add); + relay.OnNext(FirstValue); + relay.OnNext(FirstValue + 1); + + await Assert.That(relay.Initial).IsEqualTo(FirstValue); + await Assert.That(applied).IsEquivalentTo([FirstValue + 1], CollectionOrdering.Matching); + } + + /// Verifies a failure while probing is ignored, and a failure after attaching is rethrown. + /// A task representing the asynchronous test. + [Test] + public async Task OnError_FailureIsRethrownOnlyWhenAttached() + { + var relay = new FirstValueRelay(); + relay.OnNext(FirstValue); + relay.OnError(new InvalidOperationException()); + relay.OnCompleted(); + + await Assert.That(relay.HasInitial).IsTrue(); + await Assert.That(relay.Initial).IsEqualTo(FirstValue); + + relay.Attach(static _ => { }); + + await Assert.That(() => relay.OnError(new InvalidOperationException())).Throws(); + } +} diff --git a/src/tests/ReactiveList.Tests/FuzzOperation.cs b/src/tests/ReactiveList.Tests/FuzzOperation.cs new file mode 100644 index 00000000..47565776 --- /dev/null +++ b/src/tests/ReactiveList.Tests/FuzzOperation.cs @@ -0,0 +1,12 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Describes one randomly generated collection operation. +/// The operation kind selector. +/// The first item identity argument. +/// The second item identity argument. +/// The third item identity argument. +internal readonly record struct FuzzOperation(int Kind, int A, int B, int C); diff --git a/src/tests/ReactiveList.Tests/FuzzSupport.cs b/src/tests/ReactiveList.Tests/FuzzSupport.cs new file mode 100644 index 00000000..43edd6a5 --- /dev/null +++ b/src/tests/ReactiveList.Tests/FuzzSupport.cs @@ -0,0 +1,113 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Provides generators and assertions shared by the CsCheck based collection tests. +internal static class FuzzSupport +{ + /// The number of operation kinds the model based generators can produce. + internal const int OperationKindCount = 14; + + /// The number of distinct item identities in a generated universe. + internal const int Universe = 12; + + /// The default number of iterations for a model based sample. + internal const int DefaultIterations = 150; + + /// The maximum number of operations in one generated sequence. + internal const int MaxOperations = 40; + + /// Creates a generator for sequences of random collection operations. + /// A generator of operation lists. + internal static Gen> Operations() + { + var operation = Gen.Select( + Gen.Int[0, OperationKindCount - 1], + Gen.Int[0, Universe - 1], + Gen.Int[0, Universe - 1], + Gen.Int[0, Universe - 1], + static (kind, a, b, c) => new FuzzOperation(kind, a, b, c)); + return operation.List[1, MaxOperations]; + } + + /// Formats an operation list for failure reports. + /// The operations to describe. + /// A readable description of the operations. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static string Describe(List operations) => + string.Join("; ", operations); + + /// Throws when two sequences do not hold the same items with the same multiplicities. + /// The item type. + /// The sequence produced by the collection under test. + /// The sequence produced by the model. + /// A description of what is compared. + /// The sequences differ. + internal static void SameMultiset(IEnumerable actual, IEnumerable expected, string what) + where T : notnull + { + var counts = new Dictionary(); + foreach (var item in expected) + { + counts[item] = counts.TryGetValue(item, out var existing) ? existing + 1 : 1; + } + + var surplus = new List(); + foreach (var item in actual) + { + if (counts.TryGetValue(item, out var remaining) && remaining > 0) + { + counts[item] = remaining - 1; + } + else + { + surplus.Add(item); + } + } + + var missing = new List(); + foreach (var pair in counts) + { + for (var i = 0; i < pair.Value; i++) + { + missing.Add(pair.Key); + } + } + + if (surplus.Count == 0 && missing.Count == 0) + { + return; + } + + throw new InvalidOperationException( + $"{what}: unexpected [{string.Join(", ", surplus)}] missing [{string.Join(", ", missing)}]"); + } + + /// Throws when two values differ. + /// The value type. + /// The value produced by the collection under test. + /// The value produced by the model. + /// A description of what is compared. + /// The values differ. + internal static void AreEqual(T actual, T expected, string what) + { + if (!EqualityComparer.Default.Equals(actual, expected)) + { + throw new InvalidOperationException($"{what}: expected {expected} but was {actual}"); + } + } + + /// Throws when a condition does not hold. + /// The condition that must be true. + /// A description of the expectation. + /// The condition is false. + internal static void IsTrue(bool condition, string what) + { + if (!condition) + { + throw new InvalidOperationException(what); + } + } +} diff --git a/src/tests/ReactiveList.Tests/GroupedReactiveViewFuzzTests.cs b/src/tests/ReactiveList.Tests/GroupedReactiveViewFuzzTests.cs new file mode 100644 index 00000000..ccbe1108 --- /dev/null +++ b/src/tests/ReactiveList.Tests/GroupedReactiveViewFuzzTests.cs @@ -0,0 +1,79 @@ +// 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. + +using CsCheck; + +namespace ReactiveList.Tests; + +/// Model-based fuzz tests for the grouped view. +public class GroupedReactiveViewFuzzTests +{ + /// The number of generated cases per immediate property. + private const int Iterations = 150; + + /// The number of generated cases per throttled property. + private const int ThrottledIterations = 25; + + /// The longest generated mutation sequence. + private const int MaxOps = 25; + + /// The coalescing window for throttled cases, in milliseconds. + private const int ThrottleMilliseconds = 5; + + /// The number of groups. + private const int GroupCount = 3; + + /// Groups hold the same members as a brute-force grouping when notifications are applied immediately. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task GroupedView_Immediate_ConvergesToGroupedSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static (initial, ops) => RunAsync(initial, ops, TimeSpan.Zero, Sequencer.Immediate), + iter: Iterations, + threads: 1); + + /// Groups converge when a throttle window coalesces changes on a background scheduler. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task GroupedView_Throttled_ConvergesToGroupedSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static (initial, ops) => RunAsync(initial, ops, TimeSpan.FromMilliseconds(ThrottleMilliseconds), ReactiveListScheduler.Default), + iter: ThrottledIterations, + threads: 1); + + /// Applies the mutations and checks the groups against the source. + /// The initial items. + /// The mutations. + /// The coalescing window. + /// The scheduler that applies view changes. + /// A task representing the asynchronous check. + private static async Task RunAsync(int[] initial, ViewFuzzOp[] ops, TimeSpan throttle, ISequencer scheduler) + { + using var list = new ReactiveList(); + list.AddRange(initial); + using var view = new GroupedReactiveView(list, static item => item % GroupCount, scheduler, throttle); + + foreach (var op in ops) + { + ViewFuzzSupport.Apply(list, op); + } + + list.Add(ViewFuzzSupport.Sentinel); + await ViewFuzzSupport.SettleAsync(() => view.TryGetValue(ViewFuzzSupport.Sentinel % GroupCount, out var members) && members.Contains(ViewFuzzSupport.Sentinel)); + + var expected = list.ToArray().GroupBy(static item => item % GroupCount).ToDictionary(static group => group.Key, ViewFuzzSupport.Sorted); + await Assert.That(view.Count).IsEqualTo(expected.Count); + foreach (var pair in expected) + { + await Assert.That(view.ContainsKey(pair.Key)).IsTrue(); + await Assert.That(ViewFuzzSupport.Sorted(view[pair.Key])).IsEquivalentTo(pair.Value, CollectionOrdering.Matching); + } + + await Assert.That(view.Groups.Count).IsEqualTo(expected.Count); + } +} diff --git a/src/tests/ReactiveList.Tests/GroupedViewEngineSinkTests.cs b/src/tests/ReactiveList.Tests/GroupedViewEngineSinkTests.cs new file mode 100644 index 00000000..77a17336 --- /dev/null +++ b/src/tests/ReactiveList.Tests/GroupedViewEngineSinkTests.cs @@ -0,0 +1,95 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks how keeps its groups when the mirror reports changes for items it may not hold. +public class GroupedViewEngineSinkTests +{ + /// The first group key. + private const string Red = "red"; + + /// The second group key. + private const string Blue = "blue"; + + /// A refresh of an item the engine never saw adds it to its group. + /// A task representing the asynchronous test. + [Test] + public async Task ItemRefreshed_UnknownItem_AddsItToItsGroup() + { + using ReactiveList source = []; + using GroupedViewEngine engine = new(source, static item => item.Color); + + engine.ItemRefreshed(0, new(Red)); + + await Assert.That(engine.Count).IsEqualTo(1); + await Assert.That(engine.ContainsKey(Red)).IsTrue(); + } + + /// A refresh keeps an item in its group while its key is unchanged and moves it when the key changed. + /// A task representing the asynchronous test. + [Test] + public async Task ItemRefreshed_KnownItem_StaysOrMovesWithItsKey() + { + Painted item = new(Red); + using ReactiveList source = [item]; + using GroupedViewEngine engine = new(source, static painted => painted.Color); + Painted other = new(Blue); + engine.ItemRefreshed(0, other); + + engine.ItemRefreshed(0, item); + var stayed = engine.ContainsKey(Red); + item.Color = Blue; + engine.ItemRefreshed(0, item); + + await Assert.That(stayed).IsTrue(); + await Assert.That(engine.ContainsKey(Red)).IsFalse(); + await Assert.That(engine.GetItems(Blue).Count).IsEqualTo(1 + 1); + } + + /// A replacement of an item the engine does not hold adds the new item, and a replacement with a new key moves it. + /// A task representing the asynchronous test. + [Test] + public async Task ItemReplaced_UnknownOrReKeyedItem_AddsOrMovesTheCurrentItem() + { + Painted item = new(Red); + using ReactiveList source = [item]; + using GroupedViewEngine engine = new(source, static painted => painted.Color); + Painted stranger = new(Blue); + Painted added = new(Blue); + + engine.ItemReplaced(0, stranger, added); + engine.ItemReplaced(0, item, new(Blue)); + + await Assert.That(engine.ContainsKey(Red)).IsFalse(); + await Assert.That(engine.GetItems(Blue).Count).IsEqualTo(1 + 1); + } + + /// A batch large enough to be applied silently also silences a group created during it. + /// A task representing the asynchronous test. + [Test] + public async Task BatchStarted_GroupCreatedDuringQuietBatch_RaisesOneResetAtTheEnd() + { + using ReactiveList source = []; + using GroupedViewEngine engine = new(source, static painted => painted.Color) { ResetLimit = 0 }; + var raised = 0; + ((INotifyCollectionChanged)engine.Groups).CollectionChanged += (_, _) => raised++; + + engine.BatchStarted(1); + engine.ItemRefreshed(0, new(Red)); + var quietEvents = raised; + engine.BatchEnded(); + + await Assert.That(quietEvents).IsEqualTo(0); + await Assert.That(raised).IsEqualTo(1); + } + + /// An item that can change its group key. + /// The key the item is grouped by. + private sealed class Painted(string color) + { + /// Gets or sets the key the item is grouped by. + public string Color { get; set; } = color; + } +} diff --git a/src/tests/ReactiveList.Tests/GroupedViewEngineTests.cs b/src/tests/ReactiveList.Tests/GroupedViewEngineTests.cs new file mode 100644 index 00000000..fc0f0b6f --- /dev/null +++ b/src/tests/ReactiveList.Tests/GroupedViewEngineTests.cs @@ -0,0 +1,147 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies how finds items whose group key changed and groups created inside a silent batch. +public sealed class GroupedViewEngineTests +{ + /// The key of the first group. + private const int FirstKey = 1; + + /// The key of the second group. + private const int SecondKey = 2; + + /// The key a changed item moves to. + private const int MovedKey = 5; + + /// The key of a group that does not exist yet. + private const int NewKey = 8; + + /// The number of members of a group that holds two items. + private const int PairSize = 2; + + /// The number of groups the initial values form. + private const int GroupCount = 2; + + /// The divisor that turns a value into a group key. + private const int KeyDivisor = 10; + + /// The values the source starts with. + private static readonly int[] _initialValues = [FirstKey, SecondKey, FirstKey + KeyDivisor]; + + /// Verifies a replacement of an item the groups do not hold adds the new item. + /// A task representing the asynchronous test. + [Test] + public async Task ItemReplaced_PreviousNotInGroups_AddsTheNewItem() + { + var (list, engine) = Create(); + using (list) + using (engine) + { + engine.ItemReplaced(0, new(NewKey), new(NewKey)); + + await Assert.That(engine.ContainsKey(NewKey)).IsTrue(); + } + } + + /// Verifies a refreshed item that the groups do not hold is added. + /// A task representing the asynchronous test. + [Test] + public async Task ItemRefreshed_ItemNotInGroups_AddsIt() + { + var (list, engine) = Create(); + using (list) + using (engine) + { + engine.ItemRefreshed(0, new(NewKey)); + engine.ItemRefreshed(0, new(SecondKey)); + + await Assert.That(engine.ContainsKey(NewKey)).IsTrue(); + await Assert.That(engine.GetItems(SecondKey).Count).IsEqualTo(PairSize); + } + } + + /// Verifies a refreshed item keeps its group while its key is unchanged. + /// A task representing the asynchronous test. + [Test] + public async Task ItemRefreshed_KeyUnchanged_StaysInItsGroup() + { + var (list, engine) = Create(); + using (list) + using (engine) + { + engine.ItemRefreshed(0, list[0]); + + await Assert.That(engine.GetItems(FirstKey).Count).IsEqualTo(PairSize); + } + } + + /// Verifies a refreshed item whose key changed is found in its old group and moved. + /// A task representing the asynchronous test. + [Test] + public async Task ItemRefreshed_KeyChanged_MovesToTheNewGroup() + { + var (list, engine) = Create(); + using (list) + using (engine) + { + list[0].Value = MovedKey; + + engine.ItemRefreshed(0, list[0]); + + await Assert.That(engine.GetItems(FirstKey).Count).IsEqualTo(1); + await Assert.That(engine.GetItems(MovedKey).Count).IsEqualTo(1); + } + } + + /// Verifies a removal of an item that no group holds changes nothing. + /// A task representing the asynchronous test. + [Test] + public async Task ItemRemoved_ItemNotInGroups_ChangesNothing() + { + var (list, engine) = Create(); + using (list) + using (engine) + { + engine.ItemRemoved(0, new(NewKey)); + + await Assert.That(engine.Count).IsEqualTo(GroupCount); + } + } + + /// Verifies a group created inside a silent batch is silent too and announced when the batch ends. + /// A task representing the asynchronous test. + [Test] + public async Task BatchStarted_NewGroupInsideSilentBatch_IsAnnouncedByTheReset() + { + var (list, engine) = Create(); + using (list) + using (engine) + { + engine.ResetLimit = 0; + engine.BatchStarted(1); + engine.ItemReplaced(0, new(NewKey), new(NewKey)); + List actions = []; + ((INotifyCollectionChanged)engine.GetItems(NewKey)).CollectionChanged += (_, args) => actions.Add(args.Action); + + engine.BatchEnded(); + + await Assert.That(actions).IsEquivalentTo([NotifyCollectionChangedAction.Reset]); + } + } + + /// Creates a list of the initial values and an engine that groups it by the last digit. + /// The list and the engine. + private static (ReactiveList List, GroupedViewEngine Engine) Create() + { + ReactiveList list = []; + foreach (var value in _initialValues) + { + list.Add(new(value)); + } + + return (list, new(list, static item => item.Value % KeyDivisor)); + } +} diff --git a/src/tests/ReactiveList.Tests/IndexModelRun.cs b/src/tests/ReactiveList.Tests/IndexModelRun.cs new file mode 100644 index 00000000..187ed110 --- /dev/null +++ b/src/tests/ReactiveList.Tests/IndexModelRun.cs @@ -0,0 +1,106 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Runs generated operations against a and a multiset model. +/// The item type. +internal sealed class IndexModelRun + where T : notnull +{ + /// The key modulus of the test index. + internal const int KeyModulus = 3; + + /// The operation kind that removes an item. + private const int RemoveKind = 1; + + /// The operation kind that updates an item. + private const int UpdateKind = 2; + + /// The operation kind that clears the index. + private const int ClearKind = 3; + + /// Creates an item from an identity. + private readonly Func _make; + + /// Computes the index key. + private readonly Func _key; + + /// Initializes a new instance of the class. + /// Creates an item from an identity. + /// Computes the index key. + internal IndexModelRun(Func make, Func key) + { + _make = make; + _key = key; + } + + /// Applies the operations to both the index and the model, checking after each one. + /// The operations to apply. + internal void Execute(List operations) + { + var index = new SecondaryIndex(_key); + var model = new List(); + foreach (var operation in operations) + { + Apply(index, model, operation); + Verify(index, model); + } + } + + /// Applies one operation to the index and the model. + /// The index under test. + /// The model multiset. + /// The operation to apply. + private void Apply(SecondaryIndex index, List model, FuzzOperation operation) + { + var first = _make(operation.A); + var second = _make(operation.B); + switch (operation.Kind) + { + case RemoveKind: + { + index.OnRemoved(first); + _ = model.Remove(first); + break; + } + + case UpdateKind: + { + index.OnUpdated(first, second); + _ = model.Remove(first); + model.Add(second); + break; + } + + case ClearKind: + { + index.Clear(); + model.Clear(); + break; + } + + default: + { + index.OnAdded(first); + model.Add(first); + break; + } + } + } + + /// Checks the lookup for every key and the key matching. + /// The index under test. + /// The model multiset. + private void Verify(SecondaryIndex index, List model) + { + for (var id = 0; id < FuzzSupport.Universe; id++) + { + var key = _key(_make(id)); + FuzzSupport.SameMultiset(index.Lookup(key), model.Where(i => _key(i) == key), $"lookup {key}"); + FuzzSupport.IsTrue(index.MatchesKey(_make(id), key), "item matches its key"); + FuzzSupport.IsTrue(!index.MatchesKey(_make(id), "not an int"), "item does not match a key of the wrong type"); + } + } +} diff --git a/src/tests/ReactiveList.Tests/InternalDeduplicationHelpersTests.cs b/src/tests/ReactiveList.Tests/InternalDeduplicationHelpersTests.cs index 4f286f8a..1ca2a2b6 100644 --- a/src/tests/ReactiveList.Tests/InternalDeduplicationHelpersTests.cs +++ b/src/tests/ReactiveList.Tests/InternalDeduplicationHelpersTests.cs @@ -17,9 +17,6 @@ public class InternalDeduplicationHelpersTests /// Sample string beta. private const string Beta = "beta"; - /// Sample string gamma. - private const string Gamma = "gamma"; - /// Sample string apricot. private const string Apricot = "apricot"; @@ -115,74 +112,38 @@ public async Task FacadeNotificationHelper_AddAndRemoveHandlers_ManagesSubscript await Assert.That(state.HasPropertySubscription).IsFalse(); } - /// Verifies flag transitions and record value semantics. + /// Verifies keeps source order across inserts, updates, moves and refresh. /// A task representing the asynchronous test. [Test] - public async Task FilteredViewBufferState_FlagTransitionsAndEquality_WorkAsExpected() - { - using var source = new ReactiveList([1, ValueTwo]); - var filtered = new ObservableCollection(); - var changes = new ViewChangeBuffer(source); - var stateA = new FilteredViewBufferState(source, filtered, changes); - var stateB = new FilteredViewBufferState(source, filtered, changes); - - await Assert.That(stateA).IsEqualTo(stateB); - await Assert.That(stateA.RebuildRequested).IsFalse(); - await Assert.That(stateA.RefreshFromSource).IsFalse(); - await Assert.That(stateA.IsRebuilding).IsFalse(); - - stateA.MarkRefreshFromSource(); - await Assert.That(stateA.RefreshFromSource).IsTrue(); - await Assert.That(stateA.RebuildRequested).IsTrue(); - await Assert.That(stateA.ConsumeRefreshFromSource()).IsTrue(); - await Assert.That(stateA.ConsumeRefreshFromSource()).IsFalse(); - await Assert.That(stateA.ConsumeRebuildRequested()).IsTrue(); - await Assert.That(stateA.ConsumeRebuildRequested()).IsFalse(); - - await Assert.That(stateA.TryBeginRebuild()).IsTrue(); - await Assert.That(stateA.IsRebuilding).IsTrue(); - await Assert.That(stateA.TryBeginRebuild()).IsFalse(); - stateA.EndRebuild(); - await Assert.That(stateA.IsRebuilding).IsFalse(); - } - - /// Verifies incremental deltas, snapshot reconciliation, and reentrancy protection. - /// A task representing the asynchronous test. - [Test] - public async Task FilteredViewReconciler_ProcessChangesAndReconcileSnapshot_PreservesFilteredOrder() + public async Task FilteredViewEngine_ProcessesChangesInSourceOrder() { using var source = new ReactiveList([1, ValueTwo, ValueThree, ValueFour]); - var filtered = new ObservableCollection(); - var state = new FilteredViewBufferState(source, filtered, new(source)); - static bool IsEven(int value) => value % ValueTwo == 0; + using var engine = new FilteredViewEngine(source, static value => value % ValueTwo == 0); + engine.Start(TimeSpan.Zero, Sequencer.Immediate); + await Assert.That(engine.Filtered).IsEquivalentTo([ValueTwo, ValueFour], CollectionOrdering.Matching); - FilteredViewReconciler.RequestRebuild(state, IsEven); - await Assert.That(filtered).IsEquivalentTo([ValueTwo, ValueFour]); + source.Insert(1, ValueSix); + await Assert.That(engine.Filtered).IsEquivalentTo([ValueSix, ValueTwo, ValueFour], CollectionOrdering.Matching); - FilteredViewReconciler.ProcessChange(state, Change.CreateAdd(ValueSix, ValueFour), IsEven); - FilteredViewReconciler.ProcessChange(state, new(ChangeReason.Update, ValueFive, ValueTwo, 1, 1), IsEven); - FilteredViewReconciler.ProcessChange(state, new(ChangeReason.Update, ValueEight, ValueFour, ValueThree, ValueThree), IsEven); - FilteredViewReconciler.ProcessChange(state, Change.CreateRemove(ValueSix, ValueFour), IsEven); - await Assert.That(filtered).IsEquivalentTo([ValueEight]); + source.Update(ValueTwo, ValueFive); + source.Update(ValueFour, ValueEight); + await Assert.That(engine.Filtered).IsEquivalentTo([ValueSix, ValueEight], CollectionOrdering.Matching); - _ = state.TryBeginRebuild(); - state.MarkRebuildRequested(); - FilteredViewReconciler.ApplyUpdates(state, IsEven); - await Assert.That(state.RebuildRequested).IsTrue(); - state.EndRebuild(); + source.Move(0, source.Count - 1); + await Assert.That(engine.Filtered).IsEquivalentTo([ValueSix, ValueEight], CollectionOrdering.Matching); source.ReplaceAll([ValueTen, ValueEleven, ValueTwelve]); - FilteredViewReconciler.RefreshFromSource(state, IsEven); - await Assert.That(filtered).IsEquivalentTo([ValueTen, ValueTwelve]); + engine.Refresh(); + await Assert.That(engine.Filtered).IsEquivalentTo([ValueTen, ValueTwelve], CollectionOrdering.Matching); - FilteredViewReconciler.ProcessChange(state, new(ChangeReason.Clear, 0), IsEven); - await Assert.That(filtered).IsEmpty(); + source.Clear(); + await Assert.That(engine.Filtered).IsEmpty(); } /// Verifies , , and operations. /// A task representing the asynchronous test. [Test] - public async Task ReactiveViewHelpers_ProbeOptionsAndBatchMutations_WorkAsExpected() + public async Task ReactiveViewHelpers_ProbeOptionsAndBinding_WorkAsExpected() { using var list = new ReactiveList([Alpha]); var options = ReactiveViewHelpers.ResolveListViewOptions(list, static (string _) => true, null, ThrottleMs); @@ -203,16 +164,6 @@ public async Task ReactiveViewHelpers_ProbeOptionsAndBatchMutations_WorkAsExpect var returned = ReactiveViewHelpers.BindToProperty(ViewTag, readOnly, value => bound = value); await Assert.That(returned).IsEqualTo(ViewTag); await Assert.That(bound).IsSameReferenceAs(readOnly); - - using var addBatch = new PooledBatch([Alpha, Beta, Gamma], ValueThree, ReturnToPool: false); - ReactiveViewHelpers.AddMatchingBatch(target, addBatch, static s => s.Length == ValueFive); - await Assert.That(target).IsEquivalentTo([Alpha, Gamma]); - - using var removeBatch = new PooledBatch([Alpha], 1, ReturnToPool: false); - ReactiveViewHelpers.RemoveBatch(target, removeBatch); - ReactiveViewHelpers.AddMatchingBatch(target, null, static _ => true); - ReactiveViewHelpers.RemoveBatch(target, null); - await Assert.That(target).IsEquivalentTo([Gamma]); } /// Verifies and filtering. @@ -241,8 +192,15 @@ public async Task BatchFilterHelper_FilterBatchAndStream_NarrowsMatchingNotifica var matched = BatchFilterHelper.FilterBatch(batchNotification, 'a', static (item, prefix) => item[0] == prefix); await Assert.That(matched).IsNotNull(); await Assert.That(matched!.Batch!.Count).IsEqualTo(ValueTwo); + await Assert.That(matched.Action).IsEqualTo(CacheAction.BatchAdded); matched.Batch.Dispose(); + using var removedBatch = new PooledBatch([Alpha, Beta, Apricot], ValueThree, ReturnToPool: false); + var removedNotification = new CacheNotify(CacheAction.BatchRemoved, null, removedBatch); + var removedMatched = BatchFilterHelper.FilterBatch(removedNotification, 'a', static (item, prefix) => item[0] == prefix); + await Assert.That(removedMatched!.Action).IsEqualTo(CacheAction.BatchRemoved); + removedMatched.Batch!.Dispose(); + using var stream = new Signal>(); var received = new List(); using var sub = BatchFilterHelper diff --git a/src/tests/ReactiveList.Tests/InternalValueEqualityTests.cs b/src/tests/ReactiveList.Tests/InternalValueEqualityTests.cs new file mode 100644 index 00000000..a988a48d --- /dev/null +++ b/src/tests/ReactiveList.Tests/InternalValueEqualityTests.cs @@ -0,0 +1,80 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks the equality members of the internal counters and comparers. +public class InternalValueEqualityTests +{ + /// The capacity of the counts used by the tests. + private const int Capacity = 4; + + /// The text used as both key and value. + private const string Text = "text"; + + /// Counts compare by their arrays and the hash code is stable. + /// A task representing the asynchronous test. + [Test] + public async Task PooledItemCounts_Equality_ComparesTheBackingArrays() + { + var first = PooledItemCounts.Create(Capacity); + var second = PooledItemCounts.Create(Capacity); + try + { + using (Assert.Multiple()) + { + await Assert.That(first.Equals(first)).IsTrue(); + await Assert.That(first.Equals((object)first)).IsTrue(); + await Assert.That(first.Equals(second)).IsFalse(); + await Assert.That(first.Equals("other")).IsFalse(); + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + } + } + finally + { + first.Dispose(); + second.Dispose(); + } + } + + /// Shard counters compare by their version and the hash code is stable. + /// A task representing the asynchronous test. + [Test] + public async Task ShardCounter_Equality_ComparesTheVersion() + { + ShardCounter first = default; + ShardCounter second = default; + second.BumpVersion(); + + using (Assert.Multiple()) + { + await Assert.That(first.Equals(first)).IsTrue(); + await Assert.That(first.Equals((object)first)).IsTrue(); + await Assert.That(first.Equals(second)).IsFalse(); + await Assert.That(first.Equals("other")).IsFalse(); + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + } + } + + /// The key-value comparer hashes equal entries alike, including entries with null values. + /// A task representing the asynchronous test. + [Test] + public async Task KeyValueItemComparer_GetHashCode_MatchesForEqualEntries() + { + var comparer = KeyValueItemComparer.Instance; + KeyValuePair entry = new(Text, Text); + KeyValuePair same = new(Text, Text); + KeyValuePair withoutValue = new(Text, null!); + KeyValuePair withoutKey = new(null!, Text); + + using (Assert.Multiple()) + { + await Assert.That(comparer.GetHashCode(entry)).IsEqualTo(comparer.GetHashCode(same)); + await Assert.That(comparer.GetHashCode(withoutValue)).IsNotEqualTo(comparer.GetHashCode(entry)); + await Assert.That(comparer.GetHashCode(withoutKey)).IsNotEqualTo(comparer.GetHashCode(entry)); + await Assert.That(comparer.Equals(entry, same)).IsTrue(); + await Assert.That(comparer.Equals(entry, withoutValue)).IsFalse(); + } + } +} diff --git a/src/tests/ReactiveList.Tests/ItemComparisonTests.cs b/src/tests/ReactiveList.Tests/ItemComparisonTests.cs new file mode 100644 index 00000000..3a087de8 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ItemComparisonTests.cs @@ -0,0 +1,162 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks how locates items by identity for references and by value for structs. +public class ItemComparisonTests +{ + /// A value present in the value-type lists. + private const int Present = 10; + + /// A value present in the value-type lists after . + private const int Later = 20; + + /// A value absent from the value-type lists. + private const int Absent = 30; + + /// The index of the last in the three-item lists. + private const int LastPresentIndex = 2; + + /// The enumerable search finds a reference by identity before an equal value. + /// A task representing the asynchronous test. + [Test] + public async Task FindIndex_Enumerable_PrefersIdentityOverEquality() + { + var equalOnly = Name("a"); + var target = Name("a"); + IEnumerable items = [equalOnly, target]; + + await Assert.That(ItemComparison.FindIndex(items, target)).IsEqualTo(1); + } + + /// The enumerable search falls back to the first equal reference and reports a miss as -1. + /// A task representing the asynchronous test. + [Test] + public async Task FindIndex_Enumerable_FallsBackToEqualReferenceThenMisses() + { + var equalOnly = Name("a"); + IEnumerable items = [Name("b"), equalOnly, Name("a")]; + + using (Assert.Multiple()) + { + await Assert.That(ItemComparison.FindIndex(items, Name("a"))).IsEqualTo(1); + await Assert.That(ItemComparison.FindIndex(items, Name("z"))).IsEqualTo(-1); + } + } + + /// The enumerable search compares value types by value. + /// A task representing the asynchronous test. + [Test] + public async Task FindIndex_Enumerable_ComparesValueTypesByValue() + { + IEnumerable items = [Later, Present]; + + using (Assert.Multiple()) + { + await Assert.That(ItemComparison.FindIndex(items, Present)).IsEqualTo(1); + await Assert.That(ItemComparison.FindIndex(items, Absent)).IsEqualTo(-1); + } + } + + /// The list search finds a reference by identity, then by equality, and reports a miss as -1. + /// A task representing the asynchronous test. + [Test] + public async Task FindIndex_List_ReferenceTypes_PreferIdentityThenEquality() + { + var equalOnly = Name("a"); + var target = Name("a"); + IList items = [equalOnly, target]; + IList equalItems = [Name("b"), equalOnly]; + + using (Assert.Multiple()) + { + await Assert.That(ItemComparison.FindIndex(items, target)).IsEqualTo(1); + await Assert.That(ItemComparison.FindIndex(equalItems, Name("a"))).IsEqualTo(1); + await Assert.That(ItemComparison.FindIndex(items, Name("z"))).IsEqualTo(-1); + } + } + + /// The list search uses the list's own index lookup for value types. + /// A task representing the asynchronous test. + [Test] + public async Task FindIndex_List_ValueTypes_UseIndexOf() + { + IList items = [Later, Present]; + + await Assert.That(ItemComparison.FindIndex(items, Present)).IsEqualTo(1); + } + + /// The last-index search handles reference types, equatable structs in a list and in an array, and structs without equality support. + /// A task representing the asynchronous test. + [Test] + public async Task FindLastIndex_CoversReferenceEquatableAndBoxedItems() + { + var equalOnly = Name("a"); + var target = Name("a"); + IList references = [target, equalOnly]; + IList equalReferences = [equalOnly, Name("b")]; + List equatableList = [Present, Later, Present]; + int[] equatableArray = [Present, Later, Present]; + int[] equatableMiss = [Present, Later]; + IList> boxed = [Pair(Present), Pair(Later), Pair(Present)]; + + using (Assert.Multiple()) + { + await Assert.That(ItemComparison.FindLastIndex(references, target)).IsEqualTo(0); + await Assert.That(ItemComparison.FindLastIndex(equalReferences, Name("a"))).IsEqualTo(0); + await Assert.That(ItemComparison.FindLastIndex(references, Name("z"))).IsEqualTo(-1); + await Assert.That(ItemComparison.FindLastIndex(equatableList, Present)).IsEqualTo(LastPresentIndex); + await Assert.That(ItemComparison.FindLastIndex(equatableArray, Present)).IsEqualTo(LastPresentIndex); + await Assert.That(ItemComparison.FindLastIndex(equatableMiss, Absent)).IsEqualTo(-1); + await Assert.That(ItemComparison.FindLastIndex(boxed, Pair(Present))).IsEqualTo(LastPresentIndex); + await Assert.That(ItemComparison.FindLastIndex(boxed, Pair(Absent))).IsEqualTo(-1); + } + } + + /// The last-index search with a comparer stops at the last match and reports a miss as -1. + /// A task representing the asynchronous test. + [Test] + public async Task FindLastIndex_WithComparer_UsesTheComparer() + { + IList items = [Present, Later, Present]; + var comparer = EqualityComparer.Default; + + using (Assert.Multiple()) + { + await Assert.That(ItemComparison.FindLastIndex(items, Present, comparer)).IsEqualTo(LastPresentIndex); + await Assert.That(ItemComparison.FindLastIndex(items, Absent, comparer)).IsEqualTo(-1); + } + } + + /// Two items are the same occurrence by identity for references and by value for structs. + /// A task representing the asynchronous test. + [Test] + public async Task SameItem_ComparesReferencesByIdentityAndStructsByValue() + { + var first = Name("a"); + + using (Assert.Multiple()) + { + await Assert.That(ItemComparison.SameItem(first, first)).IsTrue(); + await Assert.That(ItemComparison.SameItem(first, Name("a"))).IsFalse(); + await Assert.That(ItemComparison.SameItem(Present, Present)).IsTrue(); + await Assert.That(ItemComparison.SameItem(Present, Later)).IsFalse(); + } + } + + /// Creates a reference item with value equality. + /// The name. + /// A new item. + private static Named Name(string name) => new(name); + + /// Creates a struct that does not implement . + /// The value. + /// The struct. + private static KeyValuePair Pair(int value) => new(value, value); + + /// A reference type with value equality. + /// The name. + private sealed record Named(string Name); +} diff --git a/src/tests/ReactiveList.Tests/ListModelRun.cs b/src/tests/ReactiveList.Tests/ListModelRun.cs new file mode 100644 index 00000000..363d06e7 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ListModelRun.cs @@ -0,0 +1,331 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Runs generated operations against a and a model list. +/// The item type. +internal sealed class ListModelRun + where T : notnull +{ + /// The key modulus used by the int based index selectors. + internal const int FirstModulus = 3; + + /// The key modulus of the second int index. + internal const int SecondModulus = 5; + + /// The name of the first index. + private const string FirstIndex = "first"; + + /// The name of the second index. + private const string SecondIndex = "second"; + + /// The name of the index added part way through a run. + private const string LateIndex = "late"; + + /// The key combination multiplier of the late index. + private const int LateMultiplier = 100; + + /// A key that no generated item produces. + private const int AbsentKey = -7; + + /// The number of argument collection shapes the operations rotate through. + private const int ShapeCount = 3; + + /// The number of items a batch operation carries at most. + private const int BatchSizes = 5; + + /// The divisor that decides whether an edit clears the list. + private const int ClearDivisor = 4; + + /// The smallest modulus a remove-by-predicate operation uses. + private const int MinimumRemoveModulus = 2; + + /// The operation kind that adds one item. + private const int AddKind = 0; + + /// The operation kind that removes one item. + private const int RemoveKind = 1; + + /// The operation kind that adds a range. + private const int AddRangeKind = 2; + + /// The operation kind that removes a range. + private const int RemoveRangeKind = 3; + + /// The operation kind that removes by predicate. + private const int RemoveManyKind = 4; + + /// The operation kind that edits in a batch. + private const int EditKind = 5; + + /// The operation kind that replaces all items. + private const int ReplaceAllKind = 6; + + /// The operation kind that clears the list. + private const int ClearKind = 7; + + /// The operation kind that adds the late index. + private const int AddLateIndexKind = 8; + + /// Creates an item from an identity. + private readonly Func _make; + + /// Computes the first index key. + private readonly Func _firstKey; + + /// Computes the second index key. + private readonly Func _secondKey; + + /// Initializes a new instance of the class. + /// Creates an item from an identity. + /// Computes the first index key. + /// Computes the second index key. + internal ListModelRun(Func make, Func firstKey, Func secondKey) + { + _make = make; + _firstKey = firstKey; + _secondKey = secondKey; + } + + /// Applies the operations to both the list and the model, checking after each one. + /// The operations to apply. + internal void Execute(List operations) + { + using var list = new QuaternaryList(); + var model = new List(); + list.AddIndex(FirstIndex, _firstKey); + list.AddIndex(SecondIndex, _secondKey); + var hasLateIndex = false; + + foreach (var operation in operations) + { + hasLateIndex |= Apply(list, model, operation); + Verify(list, model, hasLateIndex); + } + } + + /// Wraps items in one of several collection shapes the list accepts. + /// The operation choosing the shape. + /// The items. + /// The items as an array, a list, or a lazy sequence. + private static IEnumerable AsArgument(FuzzOperation operation, T[] items) => + (operation.A % ShapeCount) switch + { + 0 => items, + 1 => new List(items), + _ => Enumerable.Select(items, static i => i), + }; + + /// Checks that keys no item produces return nothing. + /// The list under test. + /// Whether the late index exists. + private static void VerifyAbsentKeys(QuaternaryList list, bool hasLateIndex) + { + FuzzSupport.IsTrue(!list.GetItemsBySecondaryIndex(FirstIndex, AbsentKey).Any(), "absent first key is empty"); + FuzzSupport.IsTrue(!list.GetItemsBySecondaryIndex(SecondIndex, AbsentKey).Any(), "absent second key is empty"); + FuzzSupport.IsTrue(!list.GetItemsBySecondaryIndex("missing", 1).Any(), "unknown index is empty"); + FuzzSupport.IsTrue(!list.GetItemsBySecondaryIndex(FirstIndex, "wrong key type").Any(), "wrong key type is empty"); + if (hasLateIndex) + { + FuzzSupport.IsTrue(!list.GetItemsBySecondaryIndex(LateIndex, AbsentKey).Any(), "absent late key is empty"); + } + } + + /// Applies one operation to the list and the model. + /// The list under test. + /// The model list. + /// The operation to apply. + /// when the operation added the late index. + private bool Apply(QuaternaryList list, List model, FuzzOperation operation) + { + if (operation.Kind is RemoveKind or AddKind or > AddLateIndexKind) + { + ApplySingle(list, model, operation); + return false; + } + + switch (operation.Kind) + { + case AddRangeKind: + { + list.AddRange(AsArgument(operation, Items(operation))); + model.AddRange(Items(operation)); + break; + } + + case RemoveRangeKind: + { + list.RemoveRange(AsArgument(operation, Items(operation))); + foreach (var item in Items(operation)) + { + _ = model.Remove(item); + } + + break; + } + + case RemoveManyKind: + { + RemoveMany(list, model, operation); + break; + } + + case EditKind: + { + list.Edit(c => Edit(c, operation)); + Edit(model, operation); + break; + } + + case ReplaceAllKind: + { + list.ReplaceAll(AsArgument(operation, Items(operation))); + model.Clear(); + model.AddRange(Items(operation)); + break; + } + + case ClearKind: + { + list.Clear(); + model.Clear(); + break; + } + + case AddLateIndexKind: + { + list.AddIndex(LateIndex, i => (_firstKey(i) * LateMultiplier) + _secondKey(i)); + return true; + } + } + + return false; + } + + /// Adds or removes one item in the list and the model. + /// The list under test. + /// The model list. + /// The operation to apply. + private void ApplySingle(QuaternaryList list, List model, FuzzOperation operation) + { + if (operation.Kind != RemoveKind) + { + var id = operation.Kind == AddKind ? operation.A : operation.B; + list.Add(_make(id)); + model.Add(_make(id)); + return; + } + + FuzzSupport.AreEqual(list.Remove(_make(operation.A)), model.Remove(_make(operation.A)), "Remove result"); + } + + /// Removes items by key predicate from the list and the model. + /// The list under test. + /// The model list. + /// The operation choosing the predicate. + private void RemoveMany(QuaternaryList list, List model, FuzzOperation operation) + { + var modulus = (operation.B % FirstModulus) + MinimumRemoveModulus; + var remainder = operation.A % modulus; + var expectedRemoved = model.RemoveAll(i => _secondKey(i) % modulus == remainder); + FuzzSupport.AreEqual(list.RemoveMany(i => _secondKey(i) % modulus == remainder), expectedRemoved, "RemoveMany count"); + } + + /// Applies the edit operation to a collection. + /// The collection to edit. + /// The operation describing the edit. + private void Edit(ICollection collection, FuzzOperation operation) + { + collection.Add(_make(operation.A)); + _ = collection.Remove(_make(operation.B)); + if (operation.C % ClearDivisor == 0) + { + collection.Clear(); + } + + collection.Add(_make(operation.C)); + collection.Add(_make(operation.C)); + } + + /// Creates the items an operation carries. + /// The operation. + /// The generated items, which may contain duplicates. + private T[] Items(FuzzOperation operation) + { + var count = operation.C % BatchSizes; + var items = new T[count]; + for (var i = 0; i < count; i++) + { + items[i] = _make(i % ShapeCount == 0 ? operation.A : operation.B); + } + + return items; + } + + /// Checks every observable aspect of the list against the model. + /// The list under test. + /// The model list. + /// Whether the late index exists. + private void Verify(QuaternaryList list, List model, bool hasLateIndex) + { + FuzzSupport.AreEqual(list.Count, model.Count, "Count"); + FuzzSupport.SameMultiset(list.Snapshot(), model, "Snapshot"); + FuzzSupport.SameMultiset(list.ToArray(), model, "ToArray"); + FuzzSupport.SameMultiset(list, model, "enumeration"); + + var copy = new T[model.Count + ShapeCount - 1]; + list.CopyTo(copy, 1); + FuzzSupport.SameMultiset(copy.AsSpan(1, model.Count).ToArray(), model, "CopyTo"); + + var byIndexer = new List(model.Count); + for (var i = 0; i < list.Count; i++) + { + byIndexer.Add(list[i]); + } + + FuzzSupport.SameMultiset(byIndexer, model, "indexer"); + + for (var id = 0; id < FuzzSupport.Universe; id++) + { + var item = _make(id); + FuzzSupport.AreEqual(list.Contains(item), model.Contains(item), $"Contains {item}"); + VerifyIndexes(list, model, item, hasLateIndex); + } + + VerifyAbsentKeys(list, hasLateIndex); + } + + /// Checks the index lookups for the key of one item. + /// The list under test. + /// The model list. + /// The item whose keys are queried. + /// Whether the late index exists. + private void VerifyIndexes(QuaternaryList list, List model, T item, bool hasLateIndex) + { + var first = _firstKey(item); + var second = _secondKey(item); + FuzzSupport.SameMultiset( + list.GetItemsBySecondaryIndex(FirstIndex, first), + model.Where(i => _firstKey(i) == first), + $"first index {first}"); + FuzzSupport.SameMultiset( + list.GetItemsBySecondaryIndex(SecondIndex, second), + model.Where(i => _secondKey(i) == second), + $"second index {second}"); + FuzzSupport.IsTrue(list.ItemMatchesSecondaryIndex(FirstIndex, item, first), "item matches its own first key"); + FuzzSupport.IsTrue(!list.ItemMatchesSecondaryIndex(FirstIndex, item, first + 1), "item does not match another first key"); + + if (!hasLateIndex) + { + return; + } + + var late = (first * LateMultiplier) + second; + FuzzSupport.SameMultiset( + list.GetItemsBySecondaryIndex(LateIndex, late), + model.Where(i => (_firstKey(i) * LateMultiplier) + _secondKey(i) == late), + $"late index {late}"); + } +} diff --git a/src/tests/ReactiveList.Tests/ListMultisetDifferenceTests.cs b/src/tests/ReactiveList.Tests/ListMultisetDifferenceTests.cs new file mode 100644 index 00000000..9190ff21 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ListMultisetDifferenceTests.cs @@ -0,0 +1,56 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks which items reports as added and removed. +public class ListMultisetDifferenceTests +{ + /// Equal contents report no difference. + /// A task representing the asynchronous test. + [Test] + public async Task Compute_EqualContents_ReportsNoDifference() + { + var differs = ListMultisetDifference.Compute(["a", "b"], ["a", "b"], out var added, out var removed); + + await Assert.That(differs).IsFalse(); + await Assert.That(added).IsEmpty(); + await Assert.That(removed).IsEmpty(); + } + + /// Items only on one side are reported without a table when the other window is empty. + /// A task representing the asynchronous test. + [Test] + public async Task Compute_OnlyAdditionsOrOnlyRemovals_ReportsThem() + { + var grew = ListMultisetDifference.Compute(["a"], ["a", "b"], out var added, out var removedWhenGrown); + var shrank = ListMultisetDifference.Compute(["a", "b"], ["a"], out var addedWhenShrunk, out var removed); + + using (Assert.Multiple()) + { + await Assert.That(grew).IsTrue(); + await Assert.That(added).IsEquivalentTo(["b"], CollectionOrdering.Matching); + await Assert.That(removedWhenGrown).IsEmpty(); + await Assert.That(shrank).IsTrue(); + await Assert.That(removed).IsEquivalentTo(["b"], CollectionOrdering.Matching); + await Assert.That(addedWhenShrunk).IsEmpty(); + } + } + + /// A reordered or replaced middle counts duplicates and nulls. + /// A task representing the asynchronous test. + [Test] + public async Task Compute_ReplacedMiddle_CountsDuplicatesAndNulls() + { + string[] before = ["a", null!, "b", "c"]; + List after = ["b", null!, null!, "c"]; + + var differs = ListMultisetDifference.Compute(before, after, out var added, out var removed); + + await Assert.That(differs).IsTrue(); + await Assert.That(added.Length).IsEqualTo(1); + await Assert.That(added[0]).IsNull(); + await Assert.That(removed).IsEquivalentTo(["a"], CollectionOrdering.Matching); + } +} diff --git a/src/tests/ReactiveList.Tests/ListReplica.cs b/src/tests/ReactiveList.Tests/ListReplica.cs new file mode 100644 index 00000000..9cc3838d --- /dev/null +++ b/src/tests/ReactiveList.Tests/ListReplica.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. + +namespace ReactiveList.Tests; + +/// Replays list notifications into a counting multiset so tests can compare it with the list. +internal sealed class ListReplica +{ + /// The guard for the counts. + private readonly Lock _gate = new(); + + /// The replayed item counts. + private readonly Dictionary _counts = []; + + /// Gets a value indicating whether any count ever dropped below zero. + internal bool WentNegative { get; private set; } + + /// Applies a notification to the counts. + /// The notification to replay. + internal void Apply(CacheNotify notification) + { + lock (_gate) + { + switch (notification.Action) + { + case CacheAction.Added: + { + Change(notification.Item, 1); + break; + } + + case CacheAction.Removed: + { + Change(notification.Item, -1); + break; + } + + case CacheAction.Cleared: + { + _counts.Clear(); + break; + } + + case CacheAction.BatchAdded: + { + for (var i = 0; i < notification.Batch!.Count; i++) + { + Change(notification.Batch.Items[i], 1); + } + + break; + } + + case CacheAction.BatchRemoved: + { + for (var i = 0; i < notification.Batch!.Count; i++) + { + Change(notification.Batch.Items[i], -1); + } + + break; + } + + default: + break; + } + } + } + + /// Checks whether the replayed counts equal the given contents. + /// The contents to compare with. + /// when the multisets are equal. + internal bool Matches(int[] contents) + { + lock (_gate) + { + var expected = new Dictionary(); + foreach (var item in contents) + { + expected[item] = expected.TryGetValue(item, out var n) ? n + 1 : 1; + } + + return expected.Count == _counts.Count && Enumerable.All(expected, p => _counts.TryGetValue(p.Key, out var n) && n == p.Value); + } + } + + /// Adjusts one count, dropping it when it reaches zero. + /// The item to adjust. + /// The change to apply. + private void Change(int item, int delta) + { + var next = (_counts.TryGetValue(item, out var current) ? current : 0) + delta; + if (next < 0) + { + WentNegative = true; + return; + } + + if (next == 0) + { + _ = _counts.Remove(item); + } + else + { + _counts[item] = next; + } + } +} diff --git a/src/tests/ReactiveList.Tests/ListStressWorkload.cs b/src/tests/ReactiveList.Tests/ListStressWorkload.cs new file mode 100644 index 00000000..c33c121d --- /dev/null +++ b/src/tests/ReactiveList.Tests/ListStressWorkload.cs @@ -0,0 +1,204 @@ +// 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. + +namespace ReactiveList.Tests; + +/// A multi-threaded mixed workload against a list with indexes, streams, and enumeration. +internal sealed class ListStressWorkload +{ + /// The seed multiplier that separates the workers. + private const int SeedFactor = 31; + + /// The number of groups the item type uses. + private const int GroupCount = 3; + + /// The stride used when reading by indexer. + private const int IndexerStride = 7; + + /// The name of the group index. + private const string GroupIndex = "group"; + + /// The name of the identity index. + private const string IdIndex = "id"; + + /// The seed that makes each worker's operation sequence reproducible. + private readonly int _seed; + + /// The list under stress. + private readonly QuaternaryList _list = []; + + /// Initializes a new instance of the class. + /// The seed for the workers. + internal ListStressWorkload(int seed) => _seed = seed; + + /// Runs the workload and checks the list at quiescence. + /// A task that completes when the checks pass. + /// The workload did not finish in time. + internal async Task RunAsync() + { + _list.AddIndex(GroupIndex, static i => i.Group); + _list.AddIndex(IdIndex, static x => x.Id % StressSettings.Universe); + var workers = new Task[StressSettings.WorkerCount]; + for (var worker = 0; worker < workers.Length; worker++) + { + var random = new StressRandom(unchecked((_seed * SeedFactor) + worker)); + workers[worker] = Task.Run(() => Work(random)); + } + + try + { + await Task.WhenAll(workers).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + } + catch (TimeoutException) + { + throw new InvalidOperationException($"List workload did not finish in time (seed {_seed}): deadlock suspected."); + } + + Verify(); + _list.Dispose(); + } + + /// Creates an item from an identity. + /// The item identity. + /// A new item. + private static CollidingItem Make(int id) => new(id, id % GroupCount); + + /// Checks Count, contents, and every index at quiescence. + private void Verify() + { + var contents = _list.ToArray(); + FuzzSupport.AreEqual(_list.Count, contents.Length, "Count equals contents"); + FuzzSupport.SameMultiset(_list.Snapshot(), contents, "Snapshot"); + for (var group = 0; group < GroupCount; group++) + { + FuzzSupport.SameMultiset( + _list.GetItemsBySecondaryIndex(GroupIndex, group), + contents.Where(i => i.Group == group), + $"group index {group}"); + } + + for (var key = 0; key < StressSettings.Universe; key++) + { + FuzzSupport.SameMultiset( + _list.GetItemsBySecondaryIndex(IdIndex, key), + contents.Where(i => i.Id % StressSettings.Universe == key), + $"id index {key}"); + } + } + + /// Performs random operations until the budget is spent. + /// The random source for this worker. + private void Work(StressRandom random) + { + Action[] actions = + [ + id => _list.Add(Make(id)), + id => _list.Add(Make(id)), + id => _list.Add(Make(id)), + id => _ = _list.Remove(Make(id)), + id => _ = _list.Remove(Make(id)), + id => _list.AddRange([Make(id), Make(id + 1), Make(id)]), + id => _list.RemoveRange([Make(id), Make(id)]), + id => _ = _list.RemoveMany(x => x.Id % StressSettings.RemoveModulus == id % StressSettings.RemoveModulus), + id => _list.Edit(c => + { + c.Add(Make(id)); + _ = c.Remove(Make(id + 1)); + }), + id => + { + if (random.OneIn(StressSettings.RareOdds)) + { + _list.ReplaceAll([Make(id), Make(id + 1)]); + } + }, + _ => + { + if (random.OneIn(StressSettings.RareOdds)) + { + _list.Clear(); + } + }, + _ => + { + if (random.OneIn(StressSettings.RareOdds)) + { + _list.AddIndex(IdIndex, static x => x.Id % StressSettings.Universe); + } + }, + id => _ = _list.ToArray(), + _ => Enumerate(), + id => _ = _list.Snapshot(), + _ => ReadByIndexer(), + id => _ = _list.Contains(Make(id)) && _list.GetItemsBySecondaryIndex(GroupIndex, id % GroupCount).Any(), + SubscribeBriefly, + _ => ToggleHandler(), + _ => CopyWhileSized(), + ]; + + for (var i = 0; i < StressSettings.OperationsPerWorker; i++) + { + actions[random.Next(actions.Length)](random.Next(StressSettings.Universe)); + } + } + + /// Enumerates the list while it changes. + private void Enumerate() + { + foreach (var item in _list) + { + _ = item.Id; + } + } + + /// Subscribes to the stream, adds an item, and unsubscribes. + /// The identity of the item to add. + private void SubscribeBriefly(int id) + { + using (_list.Stream.Subscribe(static _ => { })) + { + _list.Add(Make(id)); + } + } + + /// Adds and removes a collection changed handler. + private void ToggleHandler() + { + NotifyCollectionChangedEventHandler handler = static (_, _) => { }; + _list.CollectionChanged += handler; + _list.CollectionChanged -= handler; + } + + /// Copies the list into an array sized from an earlier count. + private void CopyWhileSized() + { + var copy = new CollidingItem[_list.Count + StressSettings.CopySpare]; + try + { + _list.CopyTo(copy, 0); + } + catch (ArgumentException) + { + // The list grew after the array was sized. + } + } + + /// Reads items through the indexer while the list changes. + private void ReadByIndexer() + { + var count = _list.Count; + for (var i = 0; i < count; i += IndexerStride) + { + try + { + _ = _list[i]; + } + catch (ArgumentOutOfRangeException) + { + // The list shrank after the count was read. + return; + } + } + } +} diff --git a/src/tests/ReactiveList.Tests/LiveChangeSerializerTests.cs b/src/tests/ReactiveList.Tests/LiveChangeSerializerTests.cs new file mode 100644 index 00000000..cb577a55 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveChangeSerializerTests.cs @@ -0,0 +1,100 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks that the serializer never loses a change and rebuilds when one cannot be applied. +public class LiveChangeSerializerTests +{ + /// The change every test hands to the serializer. + private static readonly NotifyCollectionChangedEventArgs Change = new(NotifyCollectionChangedAction.Reset); + + /// A change that arrives while another is being applied is covered by one rebuild once the first finishes. + /// A task representing the asynchronous test. + [Test] + public async Task Handle_WhileAnotherChangeIsApplied_RebuildsOnceAfterwards() + { + var rebuilds = 0; + var applied = 0; + LiveChangeSerializer? serializer = null; + serializer = new( + _ => + { + applied++; + if (applied == 1) + { + serializer!.Handle(Change); + } + + return true; + }, + () => rebuilds++, + static () => false); + + serializer.Handle(Change); + + await Assert.That(applied).IsEqualTo(1); + await Assert.That(rebuilds).IsEqualTo(1); + } + + /// A rebuild that was requested but not run is run by the next change instead of applying that change. + /// A task representing the asynchronous test. + [Test] + public async Task Handle_AfterAnUnservedRebuildRequest_RebuildsInsteadOfApplying() + { + var rebuilds = 0; + var applied = 0; + var stopped = true; + var serializer = new LiveChangeSerializer( + _ => + { + applied++; + return true; + }, + () => rebuilds++, + () => stopped); + + // While stopped the request is recorded but no rebuild runs. + serializer.Rebuild(); + stopped = false; + serializer.Handle(Change); + + await Assert.That(rebuilds).IsEqualTo(1); + await Assert.That(applied).IsEqualTo(0); + } + + /// A change that cannot be applied exactly is replaced by a rebuild. + /// A task representing the asynchronous test. + [Test] + public async Task Handle_ChangeThatCannotBeApplied_Rebuilds() + { + var rebuilds = 0; + var serializer = new LiveChangeSerializer(static _ => false, () => rebuilds++, static () => false); + + serializer.Handle(Change); + + await Assert.That(rebuilds).IsEqualTo(1); + } + + /// Nothing is applied or rebuilt once the owner stopped. + /// A task representing the asynchronous test. + [Test] + public async Task Handle_Stopped_DoesNothing() + { + var calls = 0; + var serializer = new LiveChangeSerializer( + _ => + { + calls++; + return true; + }, + () => calls++, + static () => true); + + serializer.Handle(Change); + serializer.Rebuild(); + + await Assert.That(calls).IsEqualTo(0); + } +} diff --git a/src/tests/ReactiveList.Tests/LiveFusedGroupCoreTests.cs b/src/tests/ReactiveList.Tests/LiveFusedGroupCoreTests.cs new file mode 100644 index 00000000..953ee799 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveFusedGroupCoreTests.cs @@ -0,0 +1,99 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks the grouping and projection layers that sit on top of a fused live query. +public class LiveFusedGroupCoreTests +{ + /// An added item fits when its position is within the held items. + /// A task representing the asynchronous test. + [Test] + public async Task Fits_Add_RequiresAPositionWithinTheHeldItems() + { + var item = new LiveQueryRow(0, 0, 0); + + await Assert.That(LiveGroupChanges.Fits(new(NotifyCollectionChangedAction.Add, item, 1), 1)).IsTrue(); + await Assert.That(LiveGroupChanges.Fits(new(NotifyCollectionChangedAction.Add, item, TestData.TestValueTwo), 1)).IsFalse(); + await Assert.That(LiveGroupChanges.Fits(new(NotifyCollectionChangedAction.Add, item, -1), 1)).IsFalse(); + } + + /// A removed item fits when its position holds an item. + /// A task representing the asynchronous test. + [Test] + public async Task Fits_Remove_RequiresAHeldPosition() + { + var item = new LiveQueryRow(0, 0, 0); + + await Assert.That(LiveGroupChanges.Fits(new(NotifyCollectionChangedAction.Remove, item, 0), 1)).IsTrue(); + await Assert.That(LiveGroupChanges.Fits(new(NotifyCollectionChangedAction.Remove, item, 1), 1)).IsFalse(); + await Assert.That(LiveGroupChanges.Fits(new(NotifyCollectionChangedAction.Remove, item, -1), 1)).IsFalse(); + } + + /// A replacement fits when it names one new item at a held position. + /// A task representing the asynchronous test. + [Test] + public async Task Fits_Replace_RequiresOneItemAtAHeldPosition() + { + var item = new LiveQueryRow(0, 0, 0); + var other = new LiveQueryRow(1, 0, 0); + List two = [item, other]; + + await Assert.That(LiveGroupChanges.Fits(new(NotifyCollectionChangedAction.Replace, item, other, 0), 1)).IsTrue(); + await Assert.That(LiveGroupChanges.Fits(new(NotifyCollectionChangedAction.Replace, item, other, 1), 1)).IsFalse(); + await Assert.That(LiveGroupChanges.Fits(new(NotifyCollectionChangedAction.Replace, two, two, 0), TestData.TestValueFive)).IsFalse(); + } + + /// A move fits when both positions hold items. + /// A task representing the asynchronous test. + [Test] + public async Task Fits_Move_RequiresBothPositionsToBeHeld() + { + var item = new LiveQueryRow(0, 0, 0); + + await Assert.That(LiveGroupChanges.Fits(new(NotifyCollectionChangedAction.Move, item, 1, 0), TestData.TestValueTwo)).IsTrue(); + await Assert.That(LiveGroupChanges.Fits(new(NotifyCollectionChangedAction.Move, item, TestData.TestValueTwo, 0), TestData.TestValueTwo)).IsFalse(); + await Assert.That(LiveGroupChanges.Fits(new(NotifyCollectionChangedAction.Move, item, 0, TestData.TestValueTwo), TestData.TestValueTwo)).IsFalse(); + } + + /// Any other kind of change never fits, so the groups are rebuilt. + /// A task representing the asynchronous test. + [Test] + public async Task Fits_Reset_NeverFits() => + await Assert.That(LiveGroupChanges.Fits(new(NotifyCollectionChangedAction.Reset), TestData.TestValueFive)).IsFalse(); + + /// Rebuilding the groups of a disposed view changes nothing. + /// A task representing the asynchronous test. + [Test] + public async Task Regroup_AfterDispose_ChangesNothing() + { + using var list = new ReactiveList([new(0, 0, 0)]); + var core = (LiveFusedGroupCore)list.Live.Feed.CreateGroups( + static r => r.Tag, + static r => r, + null, + Sequencer.Immediate, + TimeSpan.Zero); + core.Dispose(); + + core.Regroup(); + + await Assert.That(core.Count).IsEqualTo(1); + } + + /// A projection over an unordered query follows moves of the source. + /// A task representing the asynchronous test. + [Test] + public async Task ProjectedView_OverAnUnorderedQuery_FollowsMoves() + { + using var list = new ReactiveList([new(1, 0, 0), new(TestData.TestValueTwo, 0, 0), new(TestData.TestValueThree, 0, 0)]); + LiveShape shape = new(null, LiveWindow.None); + using var core = list.Live.Feed.CreateProjectedView(in shape, static r => r.Id, Sequencer.Immediate, TimeSpan.Zero); + await TestWaitHelpers.WaitUntilAsync(() => core.Items.Count == TestData.TestValueThree); + + list.Move(0, TestData.TestValueTwo); + + await TestWaitHelpers.WaitUntilAsync(() => core.Items.SequenceEqual([TestData.TestValueTwo, TestData.TestValueThree, 1])); + } +} diff --git a/src/tests/ReactiveList.Tests/LiveListEngineTests.cs b/src/tests/ReactiveList.Tests/LiveListEngineTests.cs new file mode 100644 index 00000000..03cf84ef --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveListEngineTests.cs @@ -0,0 +1,99 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks how views over an ordered list handle large inserts and window changes. +public class LiveListEngineTests +{ + /// The number of items that is too many to insert one by one. + private const int Bulk = 40; + + /// The number of rows the window tests hold. + private const int WindowRows = 10; + + /// A very large insert rebuilds the view from the source in one step. + /// A task representing the asynchronous test. + [Test] + public async Task View_AfterAVeryLargeInsert_HoldsEveryItem() + { + using var list = new ReactiveList([new(0, 0, 0)]); + using var view = list.Live.OrderBy(static r => r.Rank).ThenBy(static r => r.Id).ToView(Sequencer.Immediate, 0); + await TestWaitHelpers.WaitUntilAsync(() => view.Count == 1); + + list.AddRange(Enumerable.Range(1, Bulk).Select(static i => new LiveQueryRow(i, 0, 0))); + + await TestWaitHelpers.WaitUntilAsync(() => view.Count == Bulk + 1); + await Assert.That(view.Select(static r => r.Id)).IsEquivalentTo(Enumerable.Range(0, Bulk + 1), CollectionOrdering.Matching); + } + + /// A window count that arrives while the view is being built is applied once the view starts. + /// A task representing the asynchronous test. + [Test] + public async Task View_WindowCountArrivingWhileBuilding_IsApplied() + { + using var list = new ReactiveList([new(0, 0, 0), new(1, 0, 0), new(TestData.TestValueTwo, 0, 0)]); + var take = new Signal(); + + // The condition runs while the view evaluates its items, which is after the window values were read. + using var view = list.Live.Where( + r => + { + take.OnNext(1); + return r.Id >= 0; + }).Take(take).ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => view.Count == 1); + } + + /// A refreshed item that changed in place moves to its new sorted position. + /// A task representing the asynchronous test. + [Test] + public async Task ItemRefreshed_ChangedInPlace_MovesToItsNewPosition() + { + var first = new LiveQueryRow(0, 0, 0); + var second = new LiveQueryRow(1, 0, 1); + using var list = new ReactiveList([first, second]); + LiveShape shape = new(LiveQueryPlans.Key(static r => r.Rank, null, descending: false), LiveWindow.None); + using var core = list.Live.Feed.CreateView(in shape, Sequencer.Immediate, TimeSpan.Zero); + var engine = (LiveListEngine)core; + await TestWaitHelpers.WaitUntilAsync(() => engine.Items.Select(static r => r.Id).SequenceEqual([0, 1])); + + second.Change(0, -1); + engine.ItemRefreshed(1, second); + + await Assert.That(engine.Items.Select(static r => r.Id)).IsEquivalentTo([1, 0], CollectionOrdering.Matching); + } + + /// A drain is requested only when a change is queued. + /// A task representing the asynchronous test. + [Test] + public async Task RequestIf_DrainsOnlyWhenAChangeIsQueued() + { + var requests = 0; + + LiveDrainRequests.RequestIf(false, () => requests++); + await Assert.That(requests).IsEqualTo(0); + + LiveDrainRequests.RequestIf(true, () => requests++); + await Assert.That(requests).IsEqualTo(1); + } + + /// A window that moves more items than the reset limit is rebuilt instead of slid. + /// A task representing the asynchronous test. + [Test] + public async Task View_WindowMovingPastTheResetLimit_IsRebuilt() + { + using var list = new ReactiveList(Enumerable.Range(0, WindowRows).Select(static i => new LiveQueryRow(i, 0, i))); + var skip = new Signal(); + using var view = list.Live.OrderBy(static r => r.Rank).Skip(skip).Take(TestData.TestValueFive).ToView(Sequencer.Immediate, 0); + skip.OnNext(0); + await TestWaitHelpers.WaitUntilAsync(() => view.Count == TestData.TestValueFive); + view.BatchResetLimit = 1; + + skip.OnNext(TestData.TestValueTwo); + + await TestWaitHelpers.WaitUntilAsync(() => view.Select(static r => r.Id).SequenceEqual(Enumerable.Range(TestData.TestValueTwo, TestData.TestValueFive))); + } +} diff --git a/src/tests/ReactiveList.Tests/LiveMergeSubscriptionTests.cs b/src/tests/ReactiveList.Tests/LiveMergeSubscriptionTests.cs new file mode 100644 index 00000000..e789d422 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveMergeSubscriptionTests.cs @@ -0,0 +1,100 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks how a merged sequence reacts to a source that is disposed, an observable factory that throws and changes that arrive during disposal. +public class LiveMergeSubscriptionTests +{ + /// A source that is already disposed completes the merged sequence at once. + /// A task representing the asynchronous test. + [Test] + public async Task SelectMany_SourceAlreadyDisposed_Completes() + { + var source = new LiveQueryScriptedSource([new(0, 0, 0)]); + source.Dispose(); + var counter = new LiveQuerySubscriptionCounter(); + var recorder = new LiveQueryRecorder(); + + using var subscription = source.Live.SelectMany(counter.Observe).Subscribe(recorder); + + await Assert.That(recorder.Completed).IsTrue(); + await Assert.That(counter.Subscribed).IsEqualTo(0); + } + + /// A source that is disposed while the merge subscribes completes the merged sequence. + /// A task representing the asynchronous test. + [Test] + public async Task SelectMany_SourceDisposedWhileSubscribing_Completes() + { + var source = new LiveQueryScriptedSource([new(0, 0, 0)]) { DisposeOnSubscribe = true }; + var counter = new LiveQuerySubscriptionCounter(); + var recorder = new LiveQueryRecorder(); + + using var subscription = source.Live.SelectMany(counter.Observe).Subscribe(recorder); + + await Assert.That(recorder.Completed).IsTrue(); + } + + /// An observable factory that throws ends the merged sequence with that failure. + /// A task representing the asynchronous test. + [Test] + public async Task SelectMany_FactoryThrows_ReportsTheFailure() + { + using var list = new ReactiveList([new(0, 0, 0)]); + var recorder = new LiveQueryRecorder(); + + using var subscription = list.Live.SelectMany(static _ => FailingFactory()).Subscribe(recorder); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Error is not null); + await Assert.That(recorder.Error).IsTypeOf(); + } + + /// A change that reaches the merge after it was disposed is ignored. + /// A task representing the asynchronous test. + [Test] + public async Task OnTargetChanged_AfterDispose_IsIgnored() + { + using var list = new ReactiveList([new(0, 0, 0)]); + var counter = new LiveQuerySubscriptionCounter(); + var subscription = (LiveMergeSubscription)list.Live.SelectMany(counter.Observe).Subscribe(new LiveQueryRecorder()); + await TestWaitHelpers.WaitUntilAsync(() => counter.Subscribed == 1); + subscription.Dispose(); + + subscription.OnTargetChanged(null, new(NotifyCollectionChangedAction.Reset)); + + await Assert.That(counter.Active).IsEqualTo(0); + await Assert.That(counter.Subscribed).IsEqualTo(1); + } + + /// A change that reaches the merge while another change is being applied is left to that change. + /// A task representing the asynchronous test. + [Test] + public async Task OnTargetChanged_WhileAnotherChangeIsApplied_IsIgnored() + { + using var list = new ReactiveList(); + var counter = new LiveQuerySubscriptionCounter(); + LiveMergeSubscription? subscription = null; + var nested = 0; + var observable = list.Live.SelectMany(row => counter.ObserveWith(row, _ => + { + // The selector runs while the outer change owns the mirror, so the nested change must be refused. + subscription!.OnTargetChanged(null, new(NotifyCollectionChangedAction.Reset)); + nested++; + })); + subscription = (LiveMergeSubscription)observable.Subscribe(new LiveQueryRecorder()); + + list.Add(new(1, 0, 0)); + + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref nested) == 1); + await Assert.That(counter.Active).IsEqualTo(1); + subscription.Dispose(); + await Assert.That(counter.Active).IsEqualTo(0); + } + + /// Creates an observable factory failure. + /// Never returns. + /// Always thrown. + private static IObservable FailingFactory() => throw new InvalidOperationException("The factory failed."); +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryActionObserver.cs b/src/tests/ReactiveList.Tests/LiveQueryActionObserver.cs new file mode 100644 index 00000000..1e2db7f7 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryActionObserver.cs @@ -0,0 +1,25 @@ +// 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. + +namespace ReactiveList.Tests; + +/// An observer that runs the actions a test hands it, so a test can act while a notification is being delivered. +/// The value type. +/// Runs for each value. +/// Runs on completion. +internal sealed class LiveQueryActionObserver(Action onNext, Action onCompleted) : IObserver +{ + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnNext(T value) => onNext(value); + + /// + public void OnError(Exception error) + { + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted() => onCompleted(); +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryCase.cs b/src/tests/ReactiveList.Tests/LiveQueryCase.cs new file mode 100644 index 00000000..4e566e25 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryCase.cs @@ -0,0 +1,24 @@ +// 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. + +namespace ReactiveList.Tests; + +/// A query paired with the LINQ expression it must agree with. +/// The item type. +/// The name shown when the query disagrees. +/// Builds the view from a live query. +/// Computes the expected items from the source items. +/// The sort key of the query, or when the query is unordered. +/// Whether the query skips or takes items. +/// The identity of an item. +/// Whether the ordering ends in the identity, so the result has one possible sequence even over an unordered source. +internal sealed record LiveQueryCase( + string Name, + Func, LiveView> Build, + Func> Expect, + Func? Key, + bool Windowed, + Func Id, + bool TotalOrder = false) + where T : notnull; diff --git a/src/tests/ReactiveList.Tests/LiveQueryCases.cs b/src/tests/ReactiveList.Tests/LiveQueryCases.cs new file mode 100644 index 00000000..4cc8d89c --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryCases.cs @@ -0,0 +1,143 @@ +// 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. + +namespace ReactiveList.Tests; + +/// The operator combinations the model tests run, each with its LINQ equivalent. +internal static class LiveQueryCases +{ + /// Weights a primary sort key above a secondary one. + internal const long Weight = 10; + + /// Separates the rank from the identity in a combined key. + internal const long IdSpan = 1_000_000; + + /// The number of items a window skips. + internal const int SkipCount = 1; + + /// The number of items a window takes. + internal const int TakeCount = 3; + + /// The number of items a window with no ordering takes. + internal const int ShortTakeCount = TestData.TestValueTwo; + + /// The tag some queries exclude. + internal const int ExcludedTag = TestData.TestValueTwo; + + /// The queries over item sources. + internal static readonly IReadOnlyList> Rows = + [ + new("where", static q => q.Where(static r => r.Tag != 0).ToView(Sequencer.Immediate, 0), static s => s.Where(static r => r.Tag != 0), null, false, static r => r.Id), + new("orderBy", static q => q.OrderBy(static r => r.Rank).ToView(Sequencer.Immediate, 0), static s => s.OrderBy(static r => r.Rank), static r => r.Rank, false, static r => r.Id), + new( + "where orderByDescending thenBy", + static q => q.Where(static r => r.Tag != 1).OrderByDescending(static r => r.Rank).ThenBy(static r => r.Tag).ToView(Sequencer.Immediate, 0), + static s => s.Where(static r => r.Tag != 1).OrderByDescending(static r => r.Rank).ThenBy(static r => r.Tag), + static r => (-r.Rank * Weight) + r.Tag, + false, + static r => r.Id), + new( + "orderBy thenByDescending", + static q => q.OrderBy(static r => r.Tag).ThenByDescending(static r => r.Rank).ToView(Sequencer.Immediate, 0), + static s => s.OrderBy(static r => r.Tag).ThenByDescending(static r => r.Rank), + static r => (r.Tag * Weight) - r.Rank, + false, + static r => r.Id), + new( + "orderBy skip take", + static q => q.OrderBy(static r => r.Rank).Skip(SkipCount).Take(TakeCount).ToView(Sequencer.Immediate, 0), + static s => s.OrderBy(static r => r.Rank).Skip(SkipCount).Take(TakeCount), + static r => r.Rank, + true, + static r => r.Id), + new( + "orderBy thenBy id skip take", + static q => q.OrderBy(static r => r.Rank).ThenBy(static r => r.Id).Skip(SkipCount).Take(TakeCount).ToView(Sequencer.Immediate, 0), + static s => s.OrderBy(static r => r.Rank).ThenBy(static r => r.Id).Skip(SkipCount).Take(TakeCount), + static r => (r.Rank * IdSpan) + r.Id, + true, + static r => r.Id, + true), + new( + "where orderBy thenBy id skip take select", + static q => q.Where(static r => r.Tag != ExcludedTag).OrderBy(static r => r.Rank).ThenBy(static r => r.Id).Skip(SkipCount).Take(TakeCount) + .Select(static r => r with { Tag = r.Tag + 1 }).ToView(Sequencer.Immediate, 0), + static s => s.Where(static r => r.Tag != ExcludedTag).OrderBy(static r => r.Rank).ThenBy(static r => r.Id).Skip(SkipCount).Take(TakeCount) + .Select(static r => r with { Tag = r.Tag + 1 }), + null, + true, + static r => r.Id, + true), + new( + "orderBy take skip", + static q => q.OrderBy(static r => r.Rank).ThenBy(static r => r.Id).Take(TakeCount + 1).Skip(SkipCount).ToView(Sequencer.Immediate, 0), + static s => s.OrderBy(static r => r.Rank).ThenBy(static r => r.Id).Take(TakeCount + 1).Skip(SkipCount), + null, + true, + static r => r.Id, + true), + new( + "skip take", + static q => q.Skip(SkipCount).Take(ShortTakeCount).ToView(Sequencer.Immediate, 0), + static s => s.Skip(SkipCount).Take(ShortTakeCount), + null, + true, + static r => r.Id), + new("take", static q => q.Take(TakeCount).ToView(Sequencer.Immediate, 0), static s => s.Take(TakeCount), null, true, static r => r.Id), + new( + "where select", + static q => q.Where(static r => r.Tag != ExcludedTag).Select(static r => r with { Rank = r.Rank + 1 }).ToView(Sequencer.Immediate, 0), + static s => s.Where(static r => r.Tag != ExcludedTag).Select(static r => r with { Rank = r.Rank + 1 }), + null, + false, + static r => r.Id), + ]; + + /// The queries over dictionary entries. + internal static readonly IReadOnlyList>> Entries = + [ + new( + "where", + static q => q.Where(static kv => kv.Value.Tag != 0).ToView(Sequencer.Immediate, 0), + static s => s.Where(static kv => kv.Value.Tag != 0), + null, + false, + static kv => kv.Key), + new( + "orderBy", + static q => q.OrderBy(static kv => kv.Value.Rank).ToView(Sequencer.Immediate, 0), + static s => s.OrderBy(static kv => kv.Value.Rank), + static kv => kv.Value.Rank, + false, + static kv => kv.Key), + new( + "orderByDescending skip take", + static q => q.OrderByDescending(static kv => kv.Value.Rank).Skip(SkipCount).Take(TakeCount).ToView(Sequencer.Immediate, 0), + static s => s.OrderByDescending(static kv => kv.Value.Rank).Skip(SkipCount).Take(TakeCount), + static kv => -kv.Value.Rank, + true, + static kv => kv.Key), + new( + "orderBy thenBy key skip take", + static q => q.OrderBy(static kv => kv.Value.Rank).ThenBy(static kv => kv.Key).Skip(SkipCount).Take(TakeCount).ToView(Sequencer.Immediate, 0), + static s => s.OrderBy(static kv => kv.Value.Rank).ThenBy(static kv => kv.Key).Skip(SkipCount).Take(TakeCount), + null, + true, + static kv => kv.Key, + true), + new( + "where select", + static q => q.Where(static kv => kv.Value.Tag != ExcludedTag).Select(Bump).ToView(Sequencer.Immediate, 0), + static s => s.Where(static kv => kv.Value.Tag != ExcludedTag).Select(Bump), + null, + false, + static kv => kv.Key), + ]; + + /// Raises the rank of an entry by one. + /// The entry. + /// The entry with the raised rank. + private static KeyValuePair Bump(KeyValuePair entry) => + new(entry.Key, entry.Value with { Rank = entry.Value.Rank + 1 }); +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryComposeTests.cs b/src/tests/ReactiveList.Tests/LiveQueryComposeTests.cs new file mode 100644 index 00000000..1c65cc08 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryComposeTests.cs @@ -0,0 +1,262 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks that skips, takes, filters, projections and orderings compose like LINQ and still run as one view over one subscription. +public class LiveQueryComposeTests +{ + /// The number of rows the sources hold. + private const int RowCount = 12; + + /// The number of rows the throttled view test removes. + private const int RowRemovals = TestData.TestValueFour; + + /// The number of distinct tags. + private const int Tags = TestData.TestValueThree; + + /// The number of distinct ranks. + private const int Ranks = TestData.TestValueFive; + + /// The factor a projection multiplies an identity by. + private const int Scale = TestData.TestValueTen; + + /// Rows with repeated tags and ranks, so orderings have ties and every window cuts through them. + private static readonly LiveQueryRow[] Rows = CreateRows(); + + /// The windows to compare with LINQ: a name, the way each is built, and the LINQ result over the totally ordered rows. + private static readonly WindowCase[] Windows = + [ + new("take then skip", static q => q.Take(TestData.TestValueTen).Skip(TestData.TestValueTwo), static s => s.Take(TestData.TestValueTen).Skip(TestData.TestValueTwo)), + new("skip then take", static q => q.Skip(TestData.TestValueTwo).Take(TestData.TestValueThree), static s => s.Skip(TestData.TestValueTwo).Take(TestData.TestValueThree)), + new("skip then skip", static q => q.Skip(1).Skip(TestData.TestValueTwo), static s => s.Skip(1).Skip(TestData.TestValueTwo)), + new("take then take", static q => q.Take(TestData.TestValueFive).Take(TestData.TestValueThree), static s => s.Take(TestData.TestValueFive).Take(TestData.TestValueThree)), + new("take then bigger skip", static q => q.Take(TestData.TestValueThree).Skip(TestData.TestValueFive), static s => s.Take(TestData.TestValueThree).Skip(TestData.TestValueFive)), + new("skip take skip", static q => q.Skip(1).Take(TestData.TestValueTen).Skip(TestData.TestValueTwo), static s => s.Skip(1).Take(TestData.TestValueTen).Skip(TestData.TestValueTwo)), + ]; + + /// Skips and takes recorded one after the other give what LINQ gives, over every kind of source. + /// A task representing the asynchronous test. + [Test] + public async Task Windows_ComposeLikeLinq() + { + foreach (var window in Windows) + { + var expected = window.Expect(TotalOrder(Rows)).Select(static r => r.Id).ToArray(); + using var list = new ReactiveList(Rows); + using var sharded = new QuaternaryList(); + sharded.AddRange(Rows); + + using var fromList = window.Build(TotalOrder(list.Live)).ToView(Sequencer.Immediate, 0); + using var fromSharded = window.Build(TotalOrder(sharded.Live)).ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => Ids(fromList).SequenceEqual(expected) && Ids(fromSharded).SequenceEqual(expected)); + await Assert.That(Ids(fromList)).IsEquivalentTo(expected, CollectionOrdering.Matching).Because(window.Name); + await Assert.That(Ids(fromSharded)).IsEquivalentTo(expected, CollectionOrdering.Matching).Because(window.Name); + } + } + + /// A skip that follows a take, with either supplied over time, composes like LINQ as the values change. + /// A task representing the asynchronous test. + [Test] + public async Task ObservableWindows_ComposeLikeLinq() + { + using var list = new ReactiveList(Rows); + var take = new Signal(); + var skip = new Signal(); + using var view = TotalOrder(list.Live).Take(take).Skip(skip).ToView(Sequencer.Immediate, 0); + var ordered = TotalOrder(Rows).Select(static r => r.Id).ToArray(); + + await Assert.That(view.Count).IsEqualTo(0); + take.OnNext(TestData.TestValueSeven); + skip.OnNext(TestData.TestValueTwo); + await TestWaitHelpers.WaitUntilAsync(() => Ids(view).SequenceEqual(ordered.Take(TestData.TestValueSeven).Skip(TestData.TestValueTwo))); + + skip.OnNext(TestData.TestValueTen); + await TestWaitHelpers.WaitUntilAsync(() => view.Count == 0); + + skip.OnNext(1); + take.OnNext(TestData.TestValueFive); + await TestWaitHelpers.WaitUntilAsync(() => Ids(view).SequenceEqual(ordered.Take(TestData.TestValueFive).Skip(1))); + } + + /// Where, OrderBy, Skip, Take and Select chained in method syntax give the LINQ result over every kind of source. + /// A task representing the asynchronous test. + [Test] + public async Task Chain_MethodSyntax_MatchesLinq() + { + var expected = TotalOrder(Rows.Where(static r => r.Tag != 0)).Skip(1).Take(TestData.TestValueFive).Select(static r => r.Id * Scale).ToArray(); + using var list = new ReactiveList(Rows); + using var sharded = new QuaternaryList(); + sharded.AddRange(Rows); + using var dictionary = new QuaternaryDictionary(); + dictionary.AddRange(Rows.Select(static r => new KeyValuePair(r.Id, r))); + + using var fromList = TotalOrder(list.Live.Where(static r => r.Tag != 0)).Skip(1).Take(TestData.TestValueFive).Select(static r => r.Id * Scale).ToView(Sequencer.Immediate, 0); + using var fromSharded = TotalOrder(sharded.Live.Where(static r => r.Tag != 0)).Skip(1).Take(TestData.TestValueFive).Select(static r => r.Id * Scale).ToView(Sequencer.Immediate, 0); + using var fromDictionary = dictionary.Live + .Where(static kv => kv.Value.Tag != 0) + .OrderBy(static kv => kv.Value.Rank) + .ThenBy(static kv => kv.Key) + .Skip(1) + .Take(TestData.TestValueFive) + .Select(static kv => kv.Key * Scale) + .ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => fromList.SequenceEqual(expected) && fromSharded.SequenceEqual(expected) && fromDictionary.SequenceEqual(expected)); + } + + /// The same chain written in query syntax compiles and gives the LINQ result. + /// A task representing the asynchronous test. + [Test] + public async Task Chain_QuerySyntax_MatchesLinq() + { + var expected = (from r in Rows where r.Tag != 0 orderby r.Rank, r.Id select r.Id * Scale).ToArray(); + using var list = new ReactiveList(Rows); + + var query = from r in list.Live + where r.Tag != 0 + orderby r.Rank, r.Id + select r.Id * Scale; + using var view = query.ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => view.SequenceEqual(expected)); + } + + /// A projection after a window keeps the window, and a skip or take after it applies to the same sequence. + /// A task representing the asynchronous test. + [Test] + public async Task SelectAfterWindow_KeepsTheWindow() + { + var expected = TotalOrder(Rows).Skip(1).Take(TestData.TestValueSix).Select(static r => r.Id).Skip(1).Take(TestData.TestValueTwo).ToArray(); + using var list = new ReactiveList(Rows); + + using var view = TotalOrder(list.Live).Skip(1).Take(TestData.TestValueSix).Select(static r => r.Id).Skip(1).Take(TestData.TestValueTwo).ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => view.SequenceEqual(expected)); + } + + /// A projection after an ordering can be ordered again, with the earlier order breaking ties, as LINQ's stable ordering does. + /// A task representing the asynchronous test. + [Test] + public async Task OrderByAfterSelect_BreaksTiesWithTheEarlierOrder() + { + var expected = Rows.OrderBy(static r => r.Id % TestData.TestValueFour).ThenBy(static r => r.Id).Select(static r => r.Tag).Order().ToArray(); + using var list = new ReactiveList(Rows); + using var sharded = new QuaternaryList(); + sharded.AddRange(Rows); + + using var fromList = ByIdModulo(list.Live).Select(static r => r.Tag).OrderBy(static tag => tag).ToView(Sequencer.Immediate, 0); + using var fromSharded = ByIdModulo(sharded.Live).Select(static r => r.Tag).OrderBy(static tag => tag).ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => fromList.SequenceEqual(expected) && fromSharded.SequenceEqual(expected)); + } + + /// A filter, count, containment test and grouping after a projection that follows an ordering see the projected items. + /// A task representing the asynchronous test. + [Test] + public async Task OperatorsAfterAnOrderedSelect_SeeTheProjectedItems() + { + using var list = new ReactiveList(Rows); + var projected = TotalOrder(list.Live).Select(static r => r.Id); + var count = new LiveQueryRecorder(); + var contains = new LiveQueryRecorder(); + using var subscriptions = new MultipleDisposable + { + projected.Where(static id => id > TestData.TestValueFive).Count().Subscribe(count), + projected.Contains(TestData.TestValueThree).Subscribe(contains), + }; + using var filtered = projected.Where(static id => id > TestData.TestValueFive).ToView(Sequencer.Immediate, 0); + using var grouped = projected.OrderBy(static id => id).GroupBy(static id => id % Tags).ToView(Sequencer.Immediate, 0); + + var ordered = TotalOrder(Rows).Select(static r => r.Id).ToArray(); + await TestWaitHelpers.WaitUntilAsync(() => filtered.SequenceEqual(ordered.Where(static id => id > TestData.TestValueFive))); + await TestWaitHelpers.WaitUntilAsync(() => count.Last == ordered.Count(static id => id > TestData.TestValueFive) && contains.Last); + await TestWaitHelpers.WaitUntilAsync(() => grouped.Count == Tags && grouped[0].SequenceEqual(ordered.Order().Where(static id => id % Tags == 0))); + } + + /// A projected query over live data follows changes to the source. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedSelect_FollowsSourceChanges() + { + using var list = new ReactiveList(Rows); + using var view = TotalOrder(list.Live).Select(static r => r.Id).ToView(Sequencer.Immediate, 0); + + list.Add(new(RowCount, 0, 0)); + list.RemoveAt(0); + list[1] = new(RowCount + 1, Tags - 1, Ranks - 1); + + await TestWaitHelpers.WaitUntilAsync(() => view.SequenceEqual(TotalOrder(list.ToArray()).Select(static r => r.Id))); + } + + /// A view created with the default scheduler and throttle catches up with the source and settles on the final state. + /// A task representing the asynchronous test. + [Test] + public async Task DefaultThrottledView_SettlesOnTheFinalState() + { + using var list = new ReactiveList(Rows); + using var sharded = new QuaternaryList(); + sharded.AddRange(Rows); + using var fromList = TotalOrder(list.Live).Take(TestData.TestValueFive).ToView(); + using var fromSharded = TotalOrder(sharded.Live).Take(TestData.TestValueFive).ToView(); + + for (var i = 0; i < RowRemovals; i++) + { + list.RemoveAt(0); + _ = sharded.Remove(Rows[i]); + } + + var expected = TotalOrder(list.ToArray()).Take(TestData.TestValueFive).Select(static r => r.Id).ToArray(); + await TestWaitHelpers.WaitUntilAsync(() => Ids(fromList).SequenceEqual(expected) && Ids(fromSharded).SequenceEqual(expected)); + } + + /// Orders rows by rank and then by identity, which is a total order. + /// The query to order. + /// The ordered query. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static OrderedLiveQuery TotalOrder(LiveQuery query) => + query.OrderBy(static r => r.Rank).ThenBy(static r => r.Id); + + /// Orders rows by rank and then by identity, which is a total order. + /// The rows to order. + /// The ordered rows. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static IOrderedEnumerable TotalOrder(IEnumerable rows) => + rows.OrderBy(static r => r.Rank).ThenBy(static r => r.Id); + + /// Orders rows by the remainder of their identity, then by identity. + /// The query to order. + /// The ordered query. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static OrderedLiveQuery ByIdModulo(LiveQuery query) => + query.OrderBy(static r => r.Id % TestData.TestValueFour).ThenBy(static r => r.Id); + + /// Reads the identities of the rows of a view. + /// The view. + /// The identities in view order. + private static int[] Ids(LiveView view) => [.. view.Select(static r => r.Id)]; + + /// Creates rows with repeated tags and ranks. + /// The rows. + private static LiveQueryRow[] CreateRows() + { + var rows = new LiveQueryRow[RowCount]; + for (var i = 0; i < rows.Length; i++) + { + rows[i] = new(i, i % Tags, i * TestData.TestValueSeven % Ranks); + } + + return rows; + } + + /// A way of windowing an ordered query and the LINQ result it must give. + /// The name of the case. + /// Applies the skips and takes to a live query. + /// Applies the same skips and takes to the ordered rows. + private sealed record WindowCase( + string Name, + Func, WindowedLiveQuery> Build, + Func, IEnumerable> Expect); +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryConcurrencyTests.cs b/src/tests/ReactiveList.Tests/LiveQueryConcurrencyTests.cs new file mode 100644 index 00000000..8ca88264 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryConcurrencyTests.cs @@ -0,0 +1,307 @@ +// 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. + +using System.Security.Cryptography; + +namespace ReactiveList.Tests; + +/// Checks that queries stay correct while writers mutate the source, and that disposal is safe at any moment. +public class LiveQueryConcurrencyTests +{ + /// The number of writer tasks. + private const int Writers = 3; + + /// The number of mutations each writer makes. + private const int Rounds = 600; + + /// The number of writes that must have completed before a dispose, so the writers are provably running. + private const int MinimumWritesBeforeDispose = 50; + + /// The number of identities each writer owns. + private const int IdSpace = 10_000; + + /// Enumeration keeps a stable snapshot even when the view applies another write. + /// A task representing the asynchronous test. + [Test] + public async Task Enumerate_WhileItemsAreAdded_KeepsTheCapturedContents() + { + using ReactiveList list = [1]; + using var view = list.Live.OrderBy(static item => item).ToView(Sequencer.Immediate); + using var snapshot = view.GetEnumerator(); + list.Add(TestData.TestValueTwo); + await TestWaitHelpers.WaitUntilAsync(() => view.Count == TestData.TestValueTwo); + + await Assert.That(snapshot.MoveNext()).IsTrue(); + await Assert.That(snapshot.Current).IsEqualTo(1); + await Assert.That(snapshot.MoveNext()).IsFalse(); + } + + /// A view created during delivery never reapplies the mutation its initial snapshot already contains. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedViewCreatedDuringDelivery_DoesNotReplayItsSnapshot() + { + using var list = new ReactiveList(); + LiveView? view = null; + + list.CollectionChanged += (_, _) => + { + if (view is not null) + { + return; + } + + view = list.Live.OrderBy(static item => item).ToView(Sequencer.Immediate, 0); + list.Add(TestData.TestValueTwo); + }; + + list.Add(1); + + using var result = view!; + await Assert.That(result.ToArray()).IsEquivalentTo([1, TestData.TestValueTwo]); + } + + /// Queries created while writers run on an ordered list converge to the LINQ result. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedList_QueriesCreatedDuringWritesConverge() + { + using var list = new ReactiveList(); + List> views = []; + var writers = StartWriters(list.Add, item => list.Remove(item)); + + foreach (var query in LiveQueryCases.Rows) + { + views.Add(query.Build(list.Live)); + await Task.Yield(); + } + + await Task.WhenAll(writers); + for (var i = 0; i < views.Count; i++) + { + await LiveQueryModelCheck.AssertConvergedAsync(views[i], LiveQueryCases.Rows[i], list.ToArray, true, []); + views[i].Dispose(); + } + } + + /// Queries created while writers run on a sharded list converge to the LINQ result. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryList_QueriesCreatedDuringWritesConverge() + { + using var list = new QuaternaryList(); + List> views = []; + var writers = StartWriters(list.Add, item => list.Remove(item)); + + foreach (var query in LiveQueryCases.Rows) + { + views.Add(query.Build(list.Live)); + await Task.Yield(); + } + + await Task.WhenAll(writers); + for (var i = 0; i < views.Count; i++) + { + await LiveQueryModelCheck.AssertConvergedAsync(views[i], LiveQueryCases.Rows[i], list.ToArray, false, []); + views[i].Dispose(); + } + } + + /// State streams created while writers run end on the LINQ answer. + /// A task representing the asynchronous test. + [Test] + public async Task StateStreamsCreatedDuringWritesConverge() + { + using var list = new ReactiveList(); + using var quaternary = new QuaternaryList(); + var writers = StartWriters( + item => + { + list.Add(item); + quaternary.Add(item); + }, + item => + { + _ = list.Remove(item); + _ = quaternary.Remove(item); + }); + var listCount = new LiveQueryRecorder(); + var quaternaryCount = new LiveQueryRecorder(); + var quaternaryAny = new LiveQueryRecorder(); + await Task.Yield(); + using var first = list.Live.Where(static r => r.Tag != 0).Count().Subscribe(listCount); + using var second = quaternary.Live.Where(static r => r.Tag != 0).Count().Subscribe(quaternaryCount); + using var third = quaternary.Live.Any().Subscribe(quaternaryAny); + + await Task.WhenAll(writers); + + AssertSequenceIsValid(listCount.Values, Writers * Rounds); + AssertSequenceIsValid(quaternaryCount.Values, Writers * Rounds); + await TestWaitHelpers.WaitUntilAsync(() => listCount.Last == list.ToArray().Count(static r => r.Tag != 0)); + await TestWaitHelpers.WaitUntilAsync(() => quaternaryCount.Last == quaternary.ToArray().Count(static r => r.Tag != 0)); + await TestWaitHelpers.WaitUntilAsync(() => quaternaryAny.Last == (quaternary.Count > 0)); + } + + /// Disposing views and subscriptions while writers run is safe and leaves no active item subscriptions. + /// A task representing the asynchronous test. + [Test] + public async Task DisposeDuringMutationStorm_IsSafe() + { + using var list = new ReactiveList(); + using var quaternary = new QuaternaryList(); + var listCounter = new LiveQuerySubscriptionCounter(); + var quaternaryCounter = new LiveQuerySubscriptionCounter(); + List disposables = []; + foreach (var query in LiveQueryCases.Rows) + { + disposables.Add(query.Build(list.Live)); + disposables.Add(query.Build(quaternary.Live)); + } + + disposables.Add(list.Live.SelectMany(listCounter.Observe).Subscribe(new LiveQueryRecorder())); + disposables.Add(quaternary.Live.SelectMany(quaternaryCounter.Observe).Subscribe(new LiveQueryRecorder())); + disposables.Add(list.Live.Count().Subscribe(new LiveQueryRecorder())); + disposables.Add(quaternary.Live.Count().Subscribe(new LiveQueryRecorder())); + var writes = new int[1]; + var writers = StartWriters( + item => + { + list.Add(item); + quaternary.Add(item); + _ = Interlocked.Increment(ref writes[0]); + }, + item => + { + _ = list.Remove(item); + _ = quaternary.Remove(item); + }); + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref writes[0]) >= MinimumWritesBeforeDispose); + + var disposer = Task.Run(() => + { + foreach (var disposable in disposables) + { + disposable.Dispose(); + disposable.Dispose(); + } + }); + + await Task.WhenAll([.. writers, disposer]); + + await TestWaitHelpers.WaitUntilAsync(() => listCounter.Active == 0 && quaternaryCounter.Active == 0); + } + + /// Disposing the source while writers still run completes every stream and does not throw. + /// A task representing the asynchronous test. + [Test] + public async Task SourceDisposedDuringWrites_CompletesStreams() + { + var list = new ReactiveList(); + var count = new LiveQueryRecorder(); + using var subscription = list.Live.Count().Subscribe(count); + using var view = list.Live.OrderBy(static r => r.Rank).ToView(Sequencer.Immediate, 0); + var writes = 0; + var writer = Task.Run(() => + { + for (var i = 0; i < Rounds; i++) + { + try + { + list.Add(new(i, 0, 0)); + _ = Interlocked.Increment(ref writes); + } + catch (ObjectDisposedException) + { + return; + } + } + }); + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref writes) >= MinimumWritesBeforeDispose); + + list.Dispose(); + await writer; + + await TestWaitHelpers.WaitUntilAsync(() => count.Completed); + } + + /// Disposing a view, a state stream subscription and a merge twice is safe. + /// A task representing the asynchronous test. + [Test] + public async Task DoubleDispose_IsSafe() + { + using var list = new ReactiveList([new(0, 0, 0)]); + var view = list.Live.OrderBy(static r => r.Rank).ToView(Sequencer.Immediate, 0); + var plain = list.Live.ToView(Sequencer.Immediate, 0); + var groups = list.Live.GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0); + var count = list.Live.Count().Subscribe(new LiveQueryRecorder()); + var merge = list.Live.SelectMany(static r => new Signal()).Subscribe(new LiveQueryRecorder()); + + var act = () => + { + for (var i = 0; i < TestData.TestValueTwo; i++) + { + view.Dispose(); + plain.Dispose(); + groups.Dispose(); + count.Dispose(); + merge.Dispose(); + } + }; + + await Assert.That(act).ThrowsNothing(); + } + + /// Checks that every count a state stream published is a possible count and that no value repeats the one before it. + /// The published counts, in order. + /// The most items that can ever match. + /// Thrown when a count is out of range or repeats. + private static void AssertSequenceIsValid(int[] values, int maximum) + { + for (var i = 0; i < values.Length; i++) + { + if (values[i] < 0 || values[i] > maximum) + { + throw new InvalidOperationException($"The count {values[i]} at position {i} is outside 0..{maximum}."); + } + + if (i > 0 && values[i] == values[i - 1]) + { + throw new InvalidOperationException($"The count {values[i]} repeats at position {i}."); + } + } + } + + /// Starts writers that add and remove items they own. + /// Adds an item to the source. + /// Removes an item from the source. + /// The writer tasks. + private static Task[] StartWriters(Action add, Action remove) + { + var tasks = new Task[Writers]; + for (var writer = 0; writer < Writers; writer++) + { + var offset = writer * IdSpace; + tasks[writer] = Task.Run(() => + { + List owned = []; + for (var i = 0; i < Rounds; i++) + { + if (owned.Count > 0 && RandomNumberGenerator.GetInt32(TestData.TestValueThree) == 0) + { + var index = RandomNumberGenerator.GetInt32(owned.Count); + remove(owned[index]); + owned.RemoveAt(index); + continue; + } + + var row = new LiveQueryRow(offset + i, RandomNumberGenerator.GetInt32(TestData.TestValueFour), RandomNumberGenerator.GetInt32(TestData.TestValueThree)); + owned.Add(row); + add(row); + } + }); + } + + return tasks; + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryCountingList.cs b/src/tests/ReactiveList.Tests/LiveQueryCountingList.cs new file mode 100644 index 00000000..a11d8497 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryCountingList.cs @@ -0,0 +1,232 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Wraps an ordered list and counts how often its stream is subscribed. +/// The item type. +internal sealed class LiveQueryCountingList : IReactiveList + where T : notnull +{ + /// The wrapped list. + private readonly ReactiveList _inner; + + /// The number of subscriptions to the stream so far. + private int _subscriptions; + + /// The number of stream subscriptions that were disposed. + private int _disposedSubscriptions; + + /// Initializes a new instance of the class. + /// The list to wrap. + internal LiveQueryCountingList(ReactiveList inner) + { + _inner = inner; + Stream = Signal.Create>(Subscribe); + } + + /// + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add => ((INotifyCollectionChanged)_inner).CollectionChanged += value; + remove => ((INotifyCollectionChanged)_inner).CollectionChanged -= value; + } + + /// + public event PropertyChangedEventHandler? PropertyChanged + { + add => ((INotifyPropertyChanged)_inner).PropertyChanged += value; + remove => ((INotifyPropertyChanged)_inner).PropertyChanged -= value; + } + + /// + public int Count => _inner.Count; + + /// + public bool IsReadOnly => _inner.IsReadOnly; + + /// + public bool IsDisposed => _inner.IsDisposed; + + /// + public long Version => _inner.Version; + + /// + public IObservable> Stream { get; } + + /// + public IObservable> Added => _inner.Added; + + /// + public IObservable> Changed => _inner.Changed; + + /// + public IObservable> CurrentItems => _inner.CurrentItems; + + /// + public ReadOnlyObservableCollection Items => _inner.Items; + + /// + public ReadOnlyObservableCollection ItemsAdded => _inner.ItemsAdded; + + /// + public ReadOnlyObservableCollection ItemsChanged => _inner.ItemsChanged; + + /// + public ReadOnlyObservableCollection ItemsRemoved => _inner.ItemsRemoved; + + /// + public IObservable> Removed => _inner.Removed; + + /// + bool IList.IsFixedSize => ((IList)_inner).IsFixedSize; + + /// + bool ICollection.IsSynchronized => ((ICollection)_inner).IsSynchronized; + + /// + object ICollection.SyncRoot => ((ICollection)_inner).SyncRoot; + + /// Gets the number of subscriptions to the stream so far. + internal int Subscriptions => Volatile.Read(ref _subscriptions); + + /// Gets the number of stream subscriptions that are still active. + internal int ActiveSubscriptions => Volatile.Read(ref _subscriptions) - Volatile.Read(ref _disposedSubscriptions); + + /// + public T this[int index] + { + get => _inner[index]; + set => _inner[index] = value; + } + + /// + object? IList.this[int index] + { + get => ((IList)_inner)[index]; + set => ((IList)_inner)[index] = value; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T[] ToArray() => _inner.ToArray(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _inner.Dispose(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator GetEnumerator() => _inner.GetEnumerator(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(T item) => _inner.Add(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddRange(IEnumerable items) => _inner.AddRange(items); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() => _inner.Clear(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(T item) => _inner.Contains(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void CopyTo(T[] array, int arrayIndex) => _inner.CopyTo(array, arrayIndex); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Edit(Action> editAction) => _inner.Edit(editAction); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int IndexOf(T item) => _inner.IndexOf(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Insert(int index, T item) => _inner.Insert(index, item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, IEnumerable items) => _inner.InsertRange(index, items); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) => _inner.Move(oldIndex, newIndex); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(T item) => _inner.Remove(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Remove(IEnumerable items) => _inner.Remove(items); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) => _inner.RemoveAt(index); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int RemoveMany(Func predicate) => _inner.RemoveMany(predicate); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) => _inner.RemoveRange(index, count); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(IEnumerable items) => _inner.ReplaceAll(items); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Update(T item, T newValue) => _inner.Update(item, newValue); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + int IList.Add(object? value) => ((IList)_inner).Add(value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + bool IList.Contains(object? value) => ((IList)_inner).Contains(value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + int IList.IndexOf(object? value) => ((IList)_inner).IndexOf(value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void IList.Insert(int index, object? value) => ((IList)_inner).Insert(index, value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void IList.Remove(object? value) => ((IList)_inner).Remove(value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void ICollection.CopyTo(Array array, int index) => ((ICollection)_inner).CopyTo(array, index); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// Subscribes to the wrapped stream and counts the subscription. + /// The observer. + /// The subscription. + private IDisposable Subscribe(IObserver> observer) + { + _ = Interlocked.Increment(ref _subscriptions); + var inner = _inner.Stream.Subscribe(observer); + return Scope.Create((inner, this), static state => + { + state.inner.Dispose(); + _ = Interlocked.Increment(ref state.Item2._disposedSubscriptions); + }); + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryCountingSource.cs b/src/tests/ReactiveList.Tests/LiveQueryCountingSource.cs new file mode 100644 index 00000000..bc2901b7 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryCountingSource.cs @@ -0,0 +1,86 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Wraps a sharded list as an unordered source and counts how often its stream is subscribed. +/// The item type. +internal sealed class LiveQueryCountingSource : IReactiveSource + where T : notnull +{ + /// The wrapped list. + private readonly QuaternaryList _inner; + + /// The number of subscriptions to the stream so far. + private int _subscriptions; + + /// The number of stream subscriptions that were disposed. + private int _disposedSubscriptions; + + /// Initializes a new instance of the class. + /// The list to wrap. + internal LiveQueryCountingSource(QuaternaryList inner) + { + _inner = inner; + Stream = Signal.Create>(Subscribe); + } + + /// + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add => ((INotifyCollectionChanged)_inner).CollectionChanged += value; + remove => ((INotifyCollectionChanged)_inner).CollectionChanged -= value; + } + + /// + public int Count => _inner.Count; + + /// + public bool IsReadOnly => _inner.IsReadOnly; + + /// + public bool IsDisposed => _inner.IsDisposed; + + /// + public long Version => _inner.Version; + + /// + public IObservable> Stream { get; } + + /// Gets the number of subscriptions to the stream so far. + internal int Subscriptions => Volatile.Read(ref _subscriptions); + + /// Gets the number of stream subscriptions that are still active. + internal int ActiveSubscriptions => Volatile.Read(ref _subscriptions) - Volatile.Read(ref _disposedSubscriptions); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T[] ToArray() => _inner.ToArray(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _inner.Dispose(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator GetEnumerator() => _inner.GetEnumerator(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// Subscribes to the wrapped stream and counts the subscription. + /// The observer. + /// The subscription. + private IDisposable Subscribe(IObserver> observer) + { + _ = Interlocked.Increment(ref _subscriptions); + var inner = _inner.Stream.Subscribe(observer); + return Scope.Create((inner, this), static state => + { + state.inner.Dispose(); + _ = Interlocked.Increment(ref state.Item2._disposedSubscriptions); + }); + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryGroupViewTests.cs b/src/tests/ReactiveList.Tests/LiveQueryGroupViewTests.cs new file mode 100644 index 00000000..f5008522 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryGroupViewTests.cs @@ -0,0 +1,172 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks the order of the groups of a live group view and that its dictionary members can be read while the source changes. +public class LiveQueryGroupViewTests +{ + /// The number of writers that change the source while readers run. + private const int Writers = 2; + + /// The number of changes each writer makes. + private const int ChangesPerWriter = 400; + + /// The number of distinct group keys the writers use. + private const int KeyCount = 12; + + /// Inserting an item whose key sorts first puts its group first, as LINQ orders groups by the first occurrence of the key. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedList_InsertingAtTheFront_PutsThatGroupFirst() + { + using var list = new ReactiveList([new(0, 1, 0)]); + using var view = list.Live.GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0); + + list.Insert(0, new(1, 0, 0)); + + await TestWaitHelpers.WaitUntilAsync(() => view.Groups.Select(static g => g.Key).SequenceEqual([0, 1])); + await Assert.That(view.Keys.ToArray()).IsEquivalentTo([0, 1], CollectionOrdering.Matching); + await Assert.That(view.Select(static pair => pair.Key).ToArray()).IsEquivalentTo([0, 1], CollectionOrdering.Matching); + } + + /// Removing the first member of a group moves the group behind groups that now occur earlier. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedList_RemovingTheFirstMember_MovesTheGroupBack() + { + using var list = new ReactiveList([new(0, 1, 0), new(1, 0, 0), new(TestData.TestValueTwo, 1, 0)]); + using var view = list.Live.GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0); + await TestWaitHelpers.WaitUntilAsync(() => view.Groups.Select(static g => g.Key).SequenceEqual([1, 0])); + + list.RemoveAt(0); + + await TestWaitHelpers.WaitUntilAsync(() => view.Groups.Select(static g => g.Key).SequenceEqual([0, 1])); + await Assert.That(view[1].Select(static r => r.Id).ToArray()).IsEquivalentTo([TestData.TestValueTwo], CollectionOrdering.Matching); + } + + /// Grouping with an element selector holds the selected elements, keyed by the item, in the order of the query. + /// A task representing the asynchronous test. + [Test] + public async Task ElementSelector_GroupsTheProjectedElements() + { + using var list = new ReactiveList([new(0, 1, TestData.TestValueTwo), new(1, 0, 1), new(TestData.TestValueTwo, 1, 0)]); + using var view = list.Live.OrderBy(static r => r.Rank).GroupBy(static r => r.Tag, static r => r.Id).ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => view.Groups.Select(static g => g.Key).SequenceEqual([1, 0])); + await Assert.That(view[1].ToArray()).IsEquivalentTo([TestData.TestValueTwo, 0], CollectionOrdering.Matching); + await Assert.That(view[0].ToArray()).IsEquivalentTo([1], CollectionOrdering.Matching); + } + + /// Reading every dictionary member of a group view from other threads while the source changes never throws and never shows a torn group. + /// Whether to use a sharded source. + /// A task representing the asynchronous test. + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task ConcurrentReads_DuringWrites_NeverThrow(bool sharded) + { + using var source = sharded ? (IReactiveSource)new QuaternaryList() : new ReactiveList(); + using var view = source.Live.GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0); + using var start = new Barrier(Writers + 1); + var writing = Writers; + var failure = default(Exception); + var reads = 0; + + var writers = new Task[Writers]; + for (var w = 0; w < writers.Length; w++) + { + var offset = w * ChangesPerWriter; + writers[w] = Task.Run(() => + { + _ = start.SignalAndWait(TimeSpan.FromSeconds(TestData.TestValueTen)); + for (var i = 0; i < ChangesPerWriter; i++) + { + Change(source, new(offset + i, i % KeyCount, 0), i); + } + + _ = Interlocked.Decrement(ref writing); + }); + } + + var reader = Task.Run(() => + { + _ = start.SignalAndWait(TimeSpan.FromSeconds(TestData.TestValueTen)); + try + { + while (Volatile.Read(ref writing) > 0 || Volatile.Read(ref reads) < 1) + { + ReadEverything(view); + _ = Interlocked.Increment(ref reads); + } + } + catch (Exception ex) + { + Volatile.Write(ref failure, ex); + } + }); + + await Task.WhenAll(writers); + await reader; + + await Assert.That(Volatile.Read(ref failure)).IsNull(); + await Assert.That(Volatile.Read(ref reads)).IsGreaterThan(0); + } + + /// Adds an item, and removes an earlier one every other change so groups come and go. + /// The source. + /// The item to add. + /// The step of the writer. + private static void Change(IReactiveSource source, LiveQueryRow row, int step) + { + if (source is QuaternaryList quaternary) + { + quaternary.Add(row); + if (step % TestData.TestValueTwo != 0) + { + _ = quaternary.RemoveMany(r => r.Tag == step % KeyCount); + } + + return; + } + + var list = (ReactiveList)source; + list.Add(row); + if (step % TestData.TestValueTwo != 0) + { + _ = list.RemoveMany(r => r.Tag == step % KeyCount); + } + } + + /// Calls every dictionary member of a view and checks each result is consistent with itself. + /// The view. + /// Thrown when a result contradicts itself. + private static void ReadEverything(LiveGroupView view) + { + var keys = view.Keys.ToArray(); + _ = view.Values.ToArray(); + var pairs = view.ToArray(); + _ = view.Count; + for (var key = 0; key < KeyCount; key++) + { + if (view.TryGetValue(key, out var members)) + { + foreach (var member in members) + { + if (member.Tag != key) + { + throw new InvalidOperationException($"A group of {key} held an item of {member.Tag}."); + } + } + } + + _ = view.ContainsKey(key); + } + + if (keys.Length != new HashSet(keys).Count || pairs.Length != new HashSet(pairs.Select(static p => p.Key)).Count) + { + throw new InvalidOperationException("A snapshot repeated a group."); + } + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryHeavy.cs b/src/tests/ReactiveList.Tests/LiveQueryHeavy.cs new file mode 100644 index 00000000..70242306 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryHeavy.cs @@ -0,0 +1,9 @@ +// 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. + +namespace ReactiveList.Tests; + +/// A reference-type item whose collection can be observed through a weak reference. +/// The identity. +internal sealed record LiveQueryHeavy(int Id); diff --git a/src/tests/ReactiveList.Tests/LiveQueryModelCheck.cs b/src/tests/ReactiveList.Tests/LiveQueryModelCheck.cs new file mode 100644 index 00000000..4390912c --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryModelCheck.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. + +namespace ReactiveList.Tests; + +/// Compares live views with the LINQ result computed from the source items. +internal static class LiveQueryModelCheck +{ + /// The number of random scripts each model test runs. + internal const int Scripts = 30; + + /// The longest generated script. + internal const int MaxScriptLength = 24; + + /// Generates mutation scripts. + internal static readonly Gen ScriptGen = + Gen.Select(Gen.Int[0, LiveQueryOps.KindCount - 1], Gen.Int[0, 9], Gen.Int[0, 9], static (kind, a, b) => new LiveQueryOp(kind, a, b)).Array[0, MaxScriptLength]; + + /// Takes random scripts from the generator. + /// The scripts. + internal static List SampleScripts() + { + List scripts = []; + ScriptGen.Sample(scripts.Add, iter: Scripts, threads: 1); + return scripts; + } + + /// Tells whether a view holds what the query should produce for the source items. + /// The item type. + /// The view contents. + /// The query. + /// The source items. + /// Whether ties must follow source order, as they do for an ordered source. + /// when the view agrees with the model. + internal static bool Matches(IReadOnlyList actual, LiveQueryCase query, T[] source, bool strict) + where T : notnull + { + var expected = query.Expect(source).ToArray(); + if (strict || query.TotalOrder) + { + return actual.SequenceEqual(expected); + } + + if (actual.Count != expected.Length) + { + return false; + } + + if (query.Key is { } key && !actual.Select(key).SequenceEqual(expected.Select(key))) + { + return false; + } + + return query.Windowed + ? IsSubMultiset(actual.Select(query.Id), source.Select(query.Id)) + : actual.Select(query.Id).Order().SequenceEqual(expected.Select(query.Id).Order()); + } + + /// Waits until a view agrees with the model, then asserts it. + /// The item type. + /// The view. + /// The query. + /// Reads the current source items. + /// Whether ties must follow source order. + /// The script, for the failure message. + /// A task that completes when the view agrees. + /// Thrown when the view does not converge in time. + internal static async Task AssertConvergedAsync(LiveView view, LiveQueryCase query, Func read, bool strict, LiveQueryOp[] script) + where T : notnull + { + try + { + await TestWaitHelpers.WaitUntilAsync(() => Matches(view, query, read(), strict)).ConfigureAwait(false); + } + catch (TimeoutException) + { + var expected = string.Join(", ", query.Expect(read())); + var actual = string.Join(", ", view); + throw new InvalidOperationException($"{query.Name} did not converge. Script: {string.Join(' ', script)}. Expected: [{expected}]. Actual: [{actual}]."); + } + } + + /// Tells whether every identity occurs in the whole at least as often as in the part. + /// The identities of the part. + /// The identities of the whole. + /// when the part is a sub-multiset of the whole. + private static bool IsSubMultiset(IEnumerable part, IEnumerable whole) + { + Dictionary available = []; + foreach (var id in whole) + { + available[id] = available.GetValueOrDefault(id) + 1; + } + + foreach (var id in part) + { + var remaining = available.GetValueOrDefault(id) - 1; + if (remaining < 0) + { + return false; + } + + available[id] = remaining; + } + + return true; + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryModelTests.cs b/src/tests/ReactiveList.Tests/LiveQueryModelTests.cs new file mode 100644 index 00000000..3cf34f20 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryModelTests.cs @@ -0,0 +1,295 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Model-based tests that check every operator combination converges to the LINQ result for each source type. +public class LiveQueryModelTests +{ + /// Views over an ordered list keep order and break ties in source order, whether created before or during the mutations. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedList_QueriesMatchLinqIncludingTieOrder() + { + foreach (var script in LiveQueryModelCheck.SampleScripts()) + { + foreach (var query in LiveQueryCases.Rows) + { + using var list = new ReactiveList(); + var nextId = 0; + using var early = query.Build(list.Live); + var half = script.Length / TestData.TestValueTwo; + for (var i = 0; i < half; i++) + { + LiveQueryOps.Apply(list, script[i], ref nextId); + } + + using var late = query.Build(list.Live); + for (var i = half; i < script.Length; i++) + { + LiveQueryOps.Apply(list, script[i], ref nextId); + } + + await LiveQueryModelCheck.AssertConvergedAsync(early, query, list.ToArray, true, script); + await LiveQueryModelCheck.AssertConvergedAsync(late, query, list.ToArray, true, script); + } + } + } + + /// Views over a sharded list agree with LINQ on content and on the sort key sequence. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryList_QueriesMatchLinq() + { + foreach (var script in LiveQueryModelCheck.SampleScripts()) + { + foreach (var query in LiveQueryCases.Rows) + { + using var list = new QuaternaryList(); + var nextId = 0; + using var early = query.Build(list.Live); + var half = script.Length / TestData.TestValueTwo; + for (var i = 0; i < half; i++) + { + LiveQueryOps.Apply(list, script[i], ref nextId); + } + + using var late = query.Build(list.Live); + for (var i = half; i < script.Length; i++) + { + LiveQueryOps.Apply(list, script[i], ref nextId); + } + + await LiveQueryModelCheck.AssertConvergedAsync(early, query, list.ToArray, false, script); + await LiveQueryModelCheck.AssertConvergedAsync(late, query, list.ToArray, false, script); + } + } + } + + /// Views over a sharded dictionary agree with LINQ on content and on the sort key sequence. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryDictionary_QueriesMatchLinq() + { + foreach (var script in LiveQueryModelCheck.SampleScripts()) + { + foreach (var query in LiveQueryCases.Entries) + { + using var dictionary = new QuaternaryDictionary(); + var nextId = 0; + using var early = query.Build(dictionary.Live); + var half = script.Length / TestData.TestValueTwo; + for (var i = 0; i < half; i++) + { + LiveQueryOps.Apply(dictionary, script[i], ref nextId); + } + + using var late = query.Build(dictionary.Live); + for (var i = half; i < script.Length; i++) + { + LiveQueryOps.Apply(dictionary, script[i], ref nextId); + } + + await LiveQueryModelCheck.AssertConvergedAsync(early, query, dictionary.ToArray, false, script); + await LiveQueryModelCheck.AssertConvergedAsync(late, query, dictionary.ToArray, false, script); + } + } + } + + /// Replacing a key in an add range updates a live view and count without adding a second entry. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryDictionary_AddRangeReplacingKey_UpdatesViewAndCount() + { + using var dictionary = new QuaternaryDictionary { { 1, TestData.TestValueTwo } }; + var query = dictionary.Live.Where(static entry => entry.Value == TestData.TestValueTwo); + using var view = query.ToView(Sequencer.Immediate); + var count = new LiveQueryRecorder(); + using var subscription = query.Count().Subscribe(count); + + dictionary.AddRange([new(1, TestData.TestValueThree), new(1, TestData.TestValueFour)]); + + await TestWaitHelpers.WaitUntilAsync(() => view.Count == 0 && count.Values.LastOrDefault() == 0); + await Assert.That(count.Values).IsEquivalentTo([1, 0], CollectionOrdering.Matching); + } + + /// Grouped views over an ordered list hold the LINQ groups with members in query order. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedList_GroupsMatchLinq() + { + foreach (var script in LiveQueryModelCheck.SampleScripts()) + { + using var list = new ReactiveList(); + var nextId = 0; + using var plain = list.Live.GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0); + using var ordered = list.Live.Where(static r => r.Tag != TestData.TestValueThree).OrderBy(static r => r.Rank).GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0); + foreach (var op in script) + { + LiveQueryOps.Apply(list, op, ref nextId); + } + + await AssertGroupsAsync(plain, () => Expected(list.ToArray().GroupBy(static r => r.Tag))); + await AssertGroupsAsync( + ordered, + () => Expected(list.ToArray() + .Where(static r => r.Tag != TestData.TestValueThree) + .OrderBy(static r => r.Rank) + .GroupBy(static r => r.Tag))); + } + } + + /// Grouped views over a sharded list hold the LINQ groups, with members compared as sets. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryList_GroupsMatchLinq() + { + foreach (var script in LiveQueryModelCheck.SampleScripts()) + { + using var list = new QuaternaryList(); + var nextId = 0; + using var grouped = list.Live.GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0); + foreach (var op in script) + { + LiveQueryOps.Apply(list, op, ref nextId); + } + + await TestWaitHelpers.WaitUntilAsync(() => GroupsMatch(grouped, Expected(list.ToArray().GroupBy(static r => r.Tag)), false)); + } + } + + /// A take count that arrives later opens the window as it changes, and the view follows the LINQ slice. + /// A task representing the asynchronous test. + [Test] + public async Task DynamicWindow_FollowsTheObservableCounts() + { + LiveQueryRow[] rows = [new(1, 0, 0), new(TestData.TestValueTwo, 0, 1), new(TestData.TestValueThree, 0, TestData.TestValueTwo), new(TestData.TestValueFour, 0, TestData.TestValueThree)]; + using var list = new ReactiveList(rows); + using var quaternary = new QuaternaryList(); + quaternary.AddRange(rows); + var take = new Signal(); + var skip = new Signal(); + using var fromList = list.Live.OrderBy(static r => r.Rank).Skip(skip).Take(take).ToView(Sequencer.Immediate, 0); + using var fromQuaternary = quaternary.Live.OrderBy(static r => r.Rank).Skip(skip).Take(take).ToView(Sequencer.Immediate, 0); + + await Assert.That(fromList.Count).IsEqualTo(0); + take.OnNext(TestData.TestValueTwo); + skip.OnNext(1); + await WaitForIdsAsync(fromList, fromQuaternary, [TestData.TestValueTwo, TestData.TestValueThree]); + take.OnNext(TestData.TestValueThree); + await WaitForIdsAsync(fromList, fromQuaternary, [TestData.TestValueTwo, TestData.TestValueThree, TestData.TestValueFour]); + skip.OnNext(0); + await WaitForIdsAsync(fromList, fromQuaternary, [1, TestData.TestValueTwo, TestData.TestValueThree]); + } + + /// Windows whose skip and take change between mutations follow the LINQ slice of the totally ordered rows. + /// A task representing the asynchronous test. + [Test] + public async Task ObservableWindows_ChangingBetweenMutations_FollowLinq() + { + foreach (var script in LiveQueryModelCheck.SampleScripts()) + { + using var list = new ReactiveList(); + using var sharded = new QuaternaryList(); + var skip = new Signal(); + var take = new Signal(); + using var fromList = list.Live.OrderBy(static r => r.Rank).ThenBy(static r => r.Id).Skip(skip).Take(take).ToView(Sequencer.Immediate, 0); + using var fromSharded = sharded.Live.OrderBy(static r => r.Rank).ThenBy(static r => r.Id).Skip(skip).Take(take).ToView(Sequencer.Immediate, 0); + var skipped = 0; + var taken = TestData.TestValueThree; + skip.OnNext(skipped); + take.OnNext(taken); + var listId = 0; + var shardedId = 0; + for (var i = 0; i < script.Length; i++) + { + LiveQueryOps.Apply(list, script[i], ref listId); + LiveQueryOps.Apply(sharded, script[i], ref shardedId); + if (script[i].B % TestData.TestValueThree == 0) + { + skipped = script[i].A % TestData.TestValueFive; + skip.OnNext(skipped); + } + else if (script[i].B % TestData.TestValueFour == 0) + { + taken = script[i].A % TestData.TestValueFive; + take.OnNext(taken); + } + } + + await TestWaitHelpers.WaitUntilAsync(() => SameWindow(fromList, list.ToArray(), skipped, taken)); + await TestWaitHelpers.WaitUntilAsync(() => SameWindow(fromSharded, sharded.ToArray(), skipped, taken)); + } + } + + /// Tells whether a windowed view holds the LINQ window of the totally ordered rows. + /// The view. + /// The source rows. + /// The number of rows skipped. + /// The most rows taken. + /// when the view agrees. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool SameWindow(LiveView view, LiveQueryRow[] rows, int skip, int take) => + view.SequenceEqual(rows.OrderBy(static r => r.Rank).ThenBy(static r => r.Id).Skip(skip).Take(take)); + + /// Waits until both views hold the expected identities in order. + /// The first view. + /// The second view. + /// The expected identities. + /// A task that completes when both agree. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Task WaitForIdsAsync(LiveView first, LiveView second, int[] ids) => + TestWaitHelpers.WaitUntilAsync(() => first.Select(static r => r.Id).SequenceEqual(ids) && second.Select(static r => r.Id).SequenceEqual(ids)); + + /// Waits until a grouped view holds the expected groups in order. + /// The grouped view. + /// Computes the expected groups. + /// A task that completes when the view agrees. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Task AssertGroupsAsync(LiveGroupView view, Func[]> expected) => + TestWaitHelpers.WaitUntilAsync(() => GroupsMatch(view, expected(), true)); + + /// Captures LINQ groups in their order. + /// The groups. + /// The key and members of each group, in the order LINQ produced them. + private static KeyValuePair[] Expected(IEnumerable> groups) => + [.. groups.Select(static g => new KeyValuePair(g.Key, [.. g]))]; + + /// Tells whether a grouped view holds the expected groups. + /// The grouped view. + /// The expected groups, in the expected order. + /// Whether the groups and their members must be in the expected order, as they are for an ordered source. + /// when the groups agree. + private static bool GroupsMatch(LiveGroupView view, KeyValuePair[] expected, bool strict) + { + var actualKeys = view.Groups.Select(static g => g.Key).ToArray(); + if (view.Count != expected.Length || actualKeys.Length != expected.Length) + { + return false; + } + + if (strict && (!actualKeys.SequenceEqual(expected.Select(static pair => pair.Key)) || !view.Keys.SequenceEqual(actualKeys) || !view.Select(static pair => pair.Key).SequenceEqual(actualKeys))) + { + return false; + } + + foreach (var (key, members) in expected) + { + if (!view.TryGetValue(key, out var actual)) + { + return false; + } + + var agrees = strict + ? actual.SequenceEqual(members) + : actual.Select(static r => r.Id).Order().SequenceEqual(members.Select(static r => r.Id).Order()); + if (!agrees) + { + return false; + } + } + + return true; + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryOp.cs b/src/tests/ReactiveList.Tests/LiveQueryOp.cs new file mode 100644 index 00000000..e37c333b --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryOp.cs @@ -0,0 +1,11 @@ +// 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. + +namespace ReactiveList.Tests; + +/// One generated mutation of a source. +/// Selects the mutation. +/// The first operand. +/// The second operand. +internal readonly record struct LiveQueryOp(int Kind, int A, int B); diff --git a/src/tests/ReactiveList.Tests/LiveQueryOps.cs b/src/tests/ReactiveList.Tests/LiveQueryOps.cs new file mode 100644 index 00000000..67a0c31e --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryOps.cs @@ -0,0 +1,399 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Applies generated mutations to each kind of source. +internal static class LiveQueryOps +{ + /// The number of distinct mutation kinds. + internal const int KindCount = RefreshKind + 1; + + /// The number of distinct tags. + private const int Tags = TestData.TestValueFour; + + /// The number of distinct ranks. + private const int Ranks = TestData.TestValueThree; + + /// Inserts an item at an index. + private const int Insert = 1; + + /// Removes the item at an index. + private const int RemoveAt = TestData.TestValueTwo; + + /// Clears the source, or adds an item. + private const int ClearOrAdd = TestData.TestValueThree; + + /// Moves an item. + private const int Move = TestData.TestValueFour; + + /// Adds two items at once. + private const int AddPair = TestData.TestValueFive; + + /// Replaces the item at an index. + private const int Replace = TestData.TestValueSix; + + /// Removes an existing item by value. + private const int RemoveItem = TestData.TestValueSeven; + + /// Adds an equal copy of an item that is already present. + private const int Duplicate = 8; + + /// Changes the source in one edit. + private const int EditKind = 9; + + /// Replaces every item at once. + private const int ReplaceAllKind = 10; + + /// Removes the items with one tag in one call. + private const int RemoveManyKind = 11; + + /// Adds items while notifications are deferred. + private const int Deferred = 12; + + /// Changes the tag and rank of an item in place, then assigns the item back to its own position so the list announces the change. + private const int RefreshKind = 13; + + /// Applies a mutation to an ordered list. + /// The list. + /// The mutation. + /// The next unused identity. + internal static void Apply(ReactiveList list, LiveQueryOp op, ref int nextId) + { + var count = list.Count; + switch (op.Kind) + { + case Insert: + { + list.Insert(op.A % (count + 1), Row(ref nextId, op)); + break; + } + + case RemoveAt: + { + if (count > 0) + { + list.RemoveAt(op.A % count); + } + + break; + } + + case ClearOrAdd: + { + if (op.A == 0) + { + list.Clear(); + } + else + { + list.Add(Row(ref nextId, op)); + } + + break; + } + + default: + { + if (!ApplyBulk(list, op, ref nextId)) + { + ApplyOther(list, op, ref nextId); + } + + break; + } + } + } + + /// Applies a mutation to a sharded list. + /// The list. + /// The mutation. + /// The next unused identity. + internal static void Apply(QuaternaryList list, LiveQueryOp op, ref int nextId) + { + switch (op.Kind) + { + case ClearOrAdd or RemoveManyKind: + { + _ = list.RemoveMany(r => r.Tag == op.A % Tags); + break; + } + + case AddPair: + { + list.AddRange([Row(ref nextId, op), Row(ref nextId, op)]); + break; + } + + case RemoveAt or RemoveItem: + { + var snapshot = list.ToArray(); + if (snapshot.Length > 0) + { + _ = list.Remove(snapshot[op.A % snapshot.Length]); + } + + break; + } + + default: + { + ApplyShardedBulk(list, op, ref nextId); + break; + } + } + } + + /// Applies a mutation to a sharded dictionary. + /// The dictionary. + /// The mutation. + /// The next unused identity. + internal static void Apply(QuaternaryDictionary dictionary, LiveQueryOp op, ref int nextId) + { + switch (op.Kind) + { + case RemoveAt or RemoveItem: + { + _ = dictionary.Remove(op.A); + break; + } + + case ClearOrAdd: + { + _ = dictionary.RemoveMany(kv => kv.Value.Tag == op.A % Tags); + break; + } + + case AddPair: + { + dictionary.AddRange([new(op.A, Row(ref nextId, op)), new(op.B, Row(ref nextId, op))]); + break; + } + + case Duplicate: + { + var snapshot = dictionary.ToArray(); + if (snapshot.Length > 0) + { + var entry = snapshot[op.A % snapshot.Length]; + dictionary.AddOrUpdate(entry.Key, entry.Value); + } + + break; + } + + case EditKind: + { + var first = Row(ref nextId, op); + var second = Row(ref nextId, op); + dictionary.Edit(d => + { + d[op.A] = first; + d[op.B] = second; + }); + break; + } + + case Deferred: + { + using (dictionary.DeferNotifications()) + { + dictionary.AddOrUpdate(op.A, Row(ref nextId, op)); + dictionary.AddOrUpdate(op.B, Row(ref nextId, op)); + } + + break; + } + + default: + { + dictionary.AddOrUpdate(op.A, Row(ref nextId, op)); + break; + } + } + } + + /// Applies a duplicate, edit, replace-all, bulk removal or deferred mutation to an ordered list. + /// The list. + /// The mutation. + /// The next unused identity. + /// when the mutation was one of those kinds. + private static bool ApplyBulk(ReactiveList list, LiveQueryOp op, ref int nextId) + { + switch (op.Kind) + { + case Duplicate: + { + list.Add(list.Count > 0 ? list[op.A % list.Count] with { } : Row(ref nextId, op)); + return true; + } + + case EditKind: + { + var first = Row(ref nextId, op); + var second = Row(ref nextId, op); + list.Edit(e => + { + e.Add(first); + e.AddRange([second]); + if (e.Count > TestData.TestValueThree) + { + e.Move(0, e.Count - 1); + } + }); + return true; + } + + case ReplaceAllKind: + { + list.ReplaceAll([Row(ref nextId, op), Row(ref nextId, op), Row(ref nextId, op)]); + return true; + } + + case RemoveManyKind: + { + _ = list.RemoveMany(r => r.Tag == op.A % Tags); + return true; + } + + case Deferred: + { + using (list.DeferNotifications()) + { + list.Add(Row(ref nextId, op)); + list.Add(Row(ref nextId, op)); + if (list.Count > 0) + { + list.RemoveAt(op.A % list.Count); + } + } + + return true; + } + + case RefreshKind: + { + RefreshInPlace(list, op, ref nextId); + return true; + } + + default: + { + return false; + } + } + } + + /// Changes an item of an ordered list in place and announces the change, or adds an item when the list is empty. + /// The list. + /// The mutation. + /// The next unused identity. + private static void RefreshInPlace(ReactiveList list, LiveQueryOp op, ref int nextId) + { + if (list.Count == 0) + { + list.Add(Row(ref nextId, op)); + return; + } + + var index = op.A % list.Count; + var row = list[index]; + row.Change(op.B % Tags, (op.A + op.B) % Ranks); + + // Assigning an item to its own position is how a list reports that the item changed in place. + list[index] = row; + } + + /// Applies a duplicate, edit, replace-all or deferred mutation to a sharded list, or adds an item. + /// The list. + /// The mutation. + /// The next unused identity. + private static void ApplyShardedBulk(QuaternaryList list, LiveQueryOp op, ref int nextId) + { + switch (op.Kind) + { + case Duplicate: + { + var snapshot = list.ToArray(); + list.Add(snapshot.Length > 0 ? snapshot[op.A % snapshot.Length] : Row(ref nextId, op)); + break; + } + + case EditKind: + { + var first = Row(ref nextId, op); + var second = Row(ref nextId, op); + list.Edit(c => + { + c.Add(first); + c.Add(second); + }); + break; + } + + case ReplaceAllKind: + { + list.ReplaceAll([Row(ref nextId, op), Row(ref nextId, op), Row(ref nextId, op)]); + break; + } + + case Deferred: + { + using (list.DeferNotifications()) + { + list.Add(Row(ref nextId, op)); + list.Add(Row(ref nextId, op)); + } + + break; + } + + default: + { + list.Add(Row(ref nextId, op)); + break; + } + } + } + + /// Applies a move, bulk add, replacement or removal by value to an ordered list. + /// The list. + /// The mutation. + /// The next unused identity. + private static void ApplyOther(ReactiveList list, LiveQueryOp op, ref int nextId) + { + var count = list.Count; + if (op.Kind == AddPair) + { + list.AddRange([Row(ref nextId, op), Row(ref nextId, op)]); + } + else if (count == 0 || op.Kind is not (Move or Replace or RemoveItem)) + { + list.Add(Row(ref nextId, op)); + } + else if (op.Kind == Move) + { + list.Move(op.A % count, op.B % count); + } + else if (op.Kind == Replace) + { + list[op.A % count] = Row(ref nextId, op); + } + else + { + _ = list.Remove(list[op.A % count]); + } + } + + /// Creates an item from a mutation. + /// The next unused identity. + /// The mutation. + /// The item. + private static LiveQueryRow Row(ref int nextId, LiveQueryOp op) + { + var id = nextId; + nextId = id + 1; + return new(id, op.A % Tags, op.B % Ranks); + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryPlanningTests.cs b/src/tests/ReactiveList.Tests/LiveQueryPlanningTests.cs new file mode 100644 index 00000000..7c502dc7 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryPlanningTests.cs @@ -0,0 +1,209 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks that a terminal plans a recorded query onto exactly one subscription to the source stream. +public class LiveQueryPlanningTests +{ + /// The number of items given to each source. + private const int ItemCount = TestData.TestValueFive; + + /// The terminals, each starting a query and returning what disposes it. + private static readonly IReadOnlyList, IDisposable>>> Plans = + [ + new("where view", static s => s.Live.Where(static r => r.Tag != 0).ToView(Sequencer.Immediate, 0)), + new("orderBy view", static s => s.Live.OrderBy(static r => r.Rank).ToView(Sequencer.Immediate, 0)), + new("where orderBy view", static s => s.Live.Where(static r => r.Tag != 0).OrderBy(static r => r.Rank).ToView(Sequencer.Immediate, 0)), + new("skip take view", static s => s.Live.Skip(1).Take(ItemCount).ToView(Sequencer.Immediate, 0)), + new("orderBy skip take view", static s => s.Live.OrderBy(static r => r.Rank).Skip(1).Take(ItemCount).ToView(Sequencer.Immediate, 0)), + new("select view", static s => s.Live.Select(static r => r.Id).ToView(Sequencer.Immediate, 0)), + new("select orderBy view", static s => s.Live.Select(static r => r.Id).OrderByDescending(static id => id).ToView(Sequencer.Immediate, 0)), + new( + "where orderBy skip take select view", + static s => s.Live.Where(static r => r.Tag != 0).OrderBy(static r => r.Rank).Skip(1).Take(ItemCount).Select(static r => r.Id).ToView(Sequencer.Immediate, 0)), + new("orderBy select view", static s => s.Live.OrderBy(static r => r.Rank).Select(static r => r.Id).ToView(Sequencer.Immediate, 0)), + new("orderBy select group view", static s => s.Live.OrderBy(static r => r.Rank).Select(static r => r.Id).GroupBy(static id => id % TestData.TestValueTwo).ToView(Sequencer.Immediate, 0)), + new("orderBy select count", static s => s.Live.OrderBy(static r => r.Rank).Select(static r => r.Id).Where(static id => id > 0).Count().Subscribe(new LiveQueryRecorder())), + new("group element view", static s => s.Live.GroupBy(static r => r.Tag, static r => r.Id).ToView(Sequencer.Immediate, 0)), + new("group view", static s => s.Live.GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0)), + new("where orderBy group view", static s => s.Live.Where(static r => r.Tag != 0).OrderBy(static r => r.Rank).GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0)), + new("count", static s => s.Live.Count().Subscribe(new LiveQueryRecorder())), + new("count where", static s => s.Live.Where(static r => r.Tag != 0).Count().Subscribe(new LiveQueryRecorder())), + new("any", static s => s.Live.Any().Subscribe(new LiveQueryRecorder())), + new("contains", static s => s.Live.Contains(new(0, 0, 0)).Subscribe(new LiveQueryRecorder())), + new("selectMany", static s => s.Live.SelectMany(static r => new Signal()).Subscribe(new LiveQueryRecorder())), + new("where selectMany", static s => s.Live.Where(static r => r.Tag != 0).SelectMany(static r => new Signal()).Subscribe(new LiveQueryRecorder())), + ]; + + /// Every terminal over an ordered list subscribes to its stream exactly once and releases it on dispose. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedList_EveryTerminalSubscribesOnce() + { + foreach (var plan in Plans) + { + using var inner = new ReactiveList(); + var source = new LiveQueryCountingList(inner); + var terminal = plan.Value(source); + + await Assert.That(source.Subscriptions).IsEqualTo(1).Because(plan.Key); + Populate(inner); + await Task.Yield(); + await Assert.That(source.Subscriptions).IsEqualTo(1).Because(plan.Key); + + terminal.Dispose(); + await Assert.That(source.ActiveSubscriptions).IsEqualTo(0).Because(plan.Key); + } + } + + /// Every terminal over an ordered list that publishes versioned snapshots subscribes to its stream exactly once and releases it on dispose. + /// A task representing the asynchronous test. + [Test] + public async Task VersionedOrderedList_EveryTerminalSubscribesOnce() + { + foreach (var plan in Plans) + { + using var inner = new ReactiveList(); + var source = new LiveQueryVersionedList(inner); + var terminal = plan.Value(source); + + await Assert.That(source.Subscriptions).IsEqualTo(1).Because(plan.Key); + Populate(inner); + await Task.Yield(); + await Assert.That(source.Subscriptions).IsEqualTo(1).Because(plan.Key); + + terminal.Dispose(); + await Assert.That(source.ActiveSubscriptions).IsEqualTo(0).Because(plan.Key); + } + } + + /// Every terminal over an unordered source subscribes to its stream exactly once and releases it on dispose. + /// A task representing the asynchronous test. + [Test] + public async Task UnorderedSource_EveryTerminalSubscribesOnce() + { + foreach (var plan in Plans) + { + using var inner = new QuaternaryList(); + var source = new LiveQueryCountingSource(inner); + var terminal = plan.Value(source); + + await Assert.That(source.Subscriptions).IsEqualTo(1).Because(plan.Key); + Populate(inner); + await Task.Yield(); + await Assert.That(source.Subscriptions).IsEqualTo(1).Because(plan.Key); + + terminal.Dispose(); + await Assert.That(source.ActiveSubscriptions).IsEqualTo(0).Because(plan.Key); + } + } + + /// Every terminal over the versioned sharded list subscribes to a stream exactly once and releases it on dispose. + /// A task representing the asynchronous test. + [Test] + public async Task VersionedSource_EveryTerminalSubscribesOnce() + { + foreach (var plan in Plans) + { + using var inner = new QuaternaryList(); + var source = new LiveQueryVersionedSource(inner); + var terminal = plan.Value(source); + + await Assert.That(source.Subscriptions).IsEqualTo(1).Because(plan.Key); + Populate(inner); + await Task.Yield(); + await Assert.That(source.Subscriptions).IsEqualTo(1).Because(plan.Key); + + terminal.Dispose(); + await Assert.That(source.ActiveSubscriptions).IsEqualTo(0).Because(plan.Key); + } + } + + /// Every dictionary terminal over the versioned sharded dictionary subscribes to a stream exactly once and releases it on dispose. + /// A task representing the asynchronous test. + [Test] + public async Task VersionedDictionary_EveryTerminalSubscribesOnce() + { + IReadOnlyList>, IDisposable>>> plans = + [ + new("where view", static s => s.Live.Where(static kv => kv.Value.Tag != 0).ToView(Sequencer.Immediate, 0)), + new("orderBy skip take select view", static s => s.Live.OrderBy(static kv => kv.Value.Rank).Skip(1).Take(ItemCount).Select(static kv => kv.Key).ToView(Sequencer.Immediate, 0)), + new("group view", static s => s.Live.GroupBy(static kv => kv.Value.Tag).ToView(Sequencer.Immediate, 0)), + new("count", static s => s.Live.Where(static kv => kv.Value.Tag != 0).Count().Subscribe(new LiveQueryRecorder())), + new("selectMany", static s => s.Live.SelectMany(static kv => new Signal()).Subscribe(new LiveQueryRecorder())), + ]; + foreach (var plan in plans) + { + using var inner = new QuaternaryDictionary(); + var source = new LiveQueryVersionedSource>(inner); + var terminal = plan.Value(source); + + await Assert.That(source.Subscriptions).IsEqualTo(1).Because(plan.Key); + for (var i = 0; i < ItemCount; i++) + { + inner.AddOrUpdate(i, new(i, i % TestData.TestValueTwo, i % TestData.TestValueThree)); + } + + await Task.Yield(); + await Assert.That(source.Subscriptions).IsEqualTo(1).Because(plan.Key); + + terminal.Dispose(); + await Assert.That(source.ActiveSubscriptions).IsEqualTo(0).Because(plan.Key); + } + } + + /// Recording a long chain of operators subscribes to nothing until a terminal runs. + /// A task representing the asynchronous test. + [Test] + public async Task Recording_SubscribesToNothingUntilATerminalRuns() + { + using var inner = new ReactiveList(); + var source = new LiveQueryCountingList(inner); + + var query = source.Live.Where(static r => r.Tag != 0).Select(static r => r with { Rank = r.Rank + 1 }).OrderBy(static r => r.Rank).ThenBy(static r => r.Id).Skip(1).Take(ItemCount); + + await Assert.That(source.Subscriptions).IsEqualTo(0); + using var view = query.ToView(Sequencer.Immediate, 0); + await Assert.That(source.Subscriptions).IsEqualTo(1); + } + + /// An ordered window publishes changes for the completed batch rather than every intermediate slice. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedWindow_AddRange_ReconcilesOnce() + { + const int FirstAdded = 5; + const int LastAdded = 6; + using ReactiveList list = [1, 2, 3, 4]; + using var view = list.Live.OrderByDescending(static value => value).Take(TestData.TestValueTwo).ToView(Sequencer.Immediate, 0); + var events = 0; + view.CollectionChanged += (_, _) => events++; + + list.AddRange([FirstAdded, LastAdded]); + + await Assert.That(view.ToArray()).IsEquivalentTo([LastAdded, FirstAdded], CollectionOrdering.Matching); + await Assert.That(events).IsEqualTo(TestData.TestValueTwo); + } + + /// Adds a few items to a list. + /// The list. + private static void Populate(ReactiveList list) + { + for (var i = 0; i < ItemCount; i++) + { + list.Add(new(i, i % TestData.TestValueTwo, i % TestData.TestValueThree)); + } + } + + /// Adds a few items to a sharded list. + /// The list. + private static void Populate(QuaternaryList list) + { + for (var i = 0; i < ItemCount; i++) + { + list.Add(new(i, i % TestData.TestValueTwo, i % TestData.TestValueThree)); + } + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryRecorder.cs b/src/tests/ReactiveList.Tests/LiveQueryRecorder.cs new file mode 100644 index 00000000..6bf26c57 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryRecorder.cs @@ -0,0 +1,113 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Records everything an observable delivers, safely across threads. +/// The value type. +internal sealed class LiveQueryRecorder : IObserver +{ + /// Guards the recorded state. + private readonly Lock _gate = new(); + + /// The delivered values. + private readonly List _values = []; + + /// Whether completion was delivered. + private bool _completed; + + /// The delivered error, if any. + private Exception? _error; + + /// Gets a copy of the delivered values. + internal T[] Values + { + get + { + lock (_gate) + { + return [.. _values]; + } + } + } + + /// Gets a value indicating whether completion was delivered. + internal bool Completed + { + get + { + lock (_gate) + { + return _completed; + } + } + } + + /// Gets the delivered error, if any. + internal Exception? Error + { + get + { + lock (_gate) + { + return _error; + } + } + } + + /// Gets the most recent value, or the default when nothing was delivered. + internal T? Last + { + get + { + lock (_gate) + { + return _values.Count == 0 ? default : _values[^1]; + } + } + } + + /// + public void OnNext(T value) + { + lock (_gate) + { + _values.Add(value); + } + } + + /// + public void OnError(Exception error) + { + lock (_gate) + { + _error = error; + } + } + + /// + public void OnCompleted() + { + lock (_gate) + { + _completed = true; + } + } + + /// Tells whether any two consecutive delivered values are equal. + /// when a value repeats the one before it. + internal bool HasConsecutiveDuplicates() + { + var values = Values; + for (var i = 1; i < values.Length; i++) + { + if (EqualityComparer.Default.Equals(values[i], values[i - 1])) + { + return true; + } + } + + return false; + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryResetLimitTests.cs b/src/tests/ReactiveList.Tests/LiveQueryResetLimitTests.cs new file mode 100644 index 00000000..1a6eaa62 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryResetLimitTests.cs @@ -0,0 +1,186 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks that live views honour their reset limit on both sides of it. +public class LiveQueryResetLimitTests +{ + /// The reset limit the tests set. + private const int Limit = TestData.TestValueFive; + + /// The number of items a batch under the limit adds. + private const int SmallBatch = TestData.TestValueThree; + + /// The number of items a batch over the limit adds. + private const int LargeBatch = TestData.TestValueTen; + + /// The size of a window page. + private const int Page = TestData.TestValueFour; + + /// A view starts with no reset limit. + /// A task representing the asynchronous test. + [Test] + public async Task Default_IsUnlimited() + { + using var list = new ReactiveList(); + using var view = list.Live.ToView(Sequencer.Immediate, 0); + using var grouped = list.Live.GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0); + + await Assert.That(view.BatchResetLimit).IsEqualTo(int.MaxValue); + await Assert.That(grouped.BatchResetLimit).IsEqualTo(int.MaxValue); + } + + /// A negative limit is rejected. + /// A task representing the asynchronous test. + [Test] + public async Task Negative_IsRejected() + { + using var list = new ReactiveList(); + using var view = list.Live.ToView(Sequencer.Immediate, 0); + using var grouped = list.Live.GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0); + + await Assert.That(() => view.BatchResetLimit = -1).Throws(); + await Assert.That(() => grouped.BatchResetLimit = -1).Throws(); + } + + /// A batch over the limit raises one reset and a batch within it raises a notification per item, on every kind of source. + /// Whether the source is a sharded list. + /// A task representing the asynchronous test. + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Batch_RaisesOneResetOnlyAboveTheLimit(bool sharded) + { + using var source = new SourcePair(sharded); + using var view = source.Source.Live.Where(static r => r.Tag == 0).ToView(Sequencer.Immediate, 0); + view.BatchResetLimit = Limit; + var actions = new List(); + view.CollectionChanged += (_, e) => + { + lock (actions) + { + actions.Add(e.Action); + } + }; + + source.AddRange(0, SmallBatch); + await TestWaitHelpers.WaitUntilAsync(() => view.Count == SmallBatch); + await Assert.That(Snapshot(actions)).DoesNotContain(NotifyCollectionChangedAction.Reset); + + source.AddRange(SmallBatch, LargeBatch); + + // A sharded source delivers on its own thread, and the view holds its new items before it raises the event. + await TestWaitHelpers.WaitUntilAsync(() => + view.Count == SmallBatch + LargeBatch && Snapshot(actions).Contains(NotifyCollectionChangedAction.Reset)); + await Assert.That(Snapshot(actions).Count(static a => a == NotifyCollectionChangedAction.Reset)).IsEqualTo(1); + } + + /// Sliding a window past the limit raises one reset, and sliding within it changes only the items that move. + /// A task representing the asynchronous test. + [Test] + public async Task WindowSlide_RaisesOneResetOnlyAboveTheLimit() + { + using var list = new ReactiveList(Enumerable.Range(0, LargeBatch * TestData.TestValueTwo).Select(static i => new LiveQueryRow(i, 0, i))); + var skip = new Signal(); + using var view = list.Live.OrderBy(static r => r.Rank).Skip(skip).Take(Page).ToView(Sequencer.Immediate, 0); + view.BatchResetLimit = Page - 1; + skip.OnNext(0); + await TestWaitHelpers.WaitUntilAsync(() => view.Count == Page); + var actions = new List(); + view.CollectionChanged += (_, e) => actions.Add(e.Action); + + skip.OnNext(1); + await TestWaitHelpers.WaitUntilAsync(() => view[0].Id == 1); + await Assert.That(actions).DoesNotContain(NotifyCollectionChangedAction.Reset); + + actions.Clear(); + skip.OnNext(LargeBatch); + await TestWaitHelpers.WaitUntilAsync(() => view[0].Id == LargeBatch); + await Assert.That(actions.Count(static a => a == NotifyCollectionChangedAction.Reset)).IsEqualTo(1); + int[] expected = [LargeBatch, LargeBatch + 1, LargeBatch + TestData.TestValueTwo, LargeBatch + TestData.TestValueThree]; + await Assert.That(view.Select(static r => r.Id).ToArray()).IsEquivalentTo(expected, CollectionOrdering.Matching); + } + + /// A projected view over an ordered query honours the limit it is given. + /// A task representing the asynchronous test. + [Test] + public async Task ProjectedView_RaisesOneResetOnlyAboveTheLimit() + { + using var list = new ReactiveList(); + using var view = list.Live.OrderBy(static r => r.Rank).Select(static r => r.Id).ToView(Sequencer.Immediate, 0); + view.BatchResetLimit = Limit; + var actions = new List(); + view.CollectionChanged += (_, e) => actions.Add(e.Action); + + list.AddRange(Enumerable.Range(0, SmallBatch).Select(static i => new LiveQueryRow(i, 0, i))); + await TestWaitHelpers.WaitUntilAsync(() => view.Count == SmallBatch); + await Assert.That(actions).DoesNotContain(NotifyCollectionChangedAction.Reset); + + list.AddRange(Enumerable.Range(SmallBatch, LargeBatch).Select(static i => new LiveQueryRow(i, 0, i))); + await TestWaitHelpers.WaitUntilAsync(() => view.Count == SmallBatch + LargeBatch); + await Assert.That(actions.Count(static a => a == NotifyCollectionChangedAction.Reset)).IsGreaterThanOrEqualTo(1); + } + + /// Copies the recorded actions. + /// The recorded actions. + /// The copy. + private static NotifyCollectionChangedAction[] Snapshot(List actions) + { + lock (actions) + { + return [.. actions]; + } + } + + /// An ordered list or a sharded list that tests fill the same way. + private sealed class SourcePair : IDisposable + { + /// The list when the source is ordered. + private readonly ReactiveList? _list; + + /// The list when the source is sharded. + private readonly QuaternaryList? _sharded; + + /// Initializes a new instance of the class. + /// Whether the source is a sharded list. + internal SourcePair(bool sharded) + { + if (sharded) + { + _sharded = new(); + } + else + { + _list = new(); + } + } + + /// Gets the source. + internal IReactiveSource Source => _list is not null ? _list : _sharded!; + + /// + public void Dispose() + { + _list?.Dispose(); + _sharded?.Dispose(); + } + + /// Adds rows with consecutive identities in one batch. + /// The identity of the first row. + /// The number of rows. + internal void AddRange(int first, int count) + { + var rows = Enumerable.Range(first, count).Select(static i => new LiveQueryRow(i, 0, i)).ToArray(); + if (_list is not null) + { + _list.AddRange(rows); + } + else + { + _sharded!.AddRange(rows); + } + } + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryRow.cs b/src/tests/ReactiveList.Tests/LiveQueryRow.cs new file mode 100644 index 00000000..2bc559b5 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryRow.cs @@ -0,0 +1,41 @@ +// 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. + +namespace ReactiveList.Tests; + +/// An item with a unique identity, a small grouping tag and a small rank that is often tied. alters the tag and rank in place. +/// The unique identity. +/// The grouping tag. +/// The rank used for ordering. +internal sealed record LiveQueryRow(int Id, int Tag, int Rank) +{ + /// The grouping tag. + private int _tag = Tag; + + /// The rank used for ordering. + private int _rank = Rank; + + /// Gets the grouping tag. + public int Tag + { + get => _tag; + init => _tag = value; + } + + /// Gets the rank used for ordering. + public int Rank + { + get => _rank; + init => _rank = value; + } + + /// Alters the tag and rank of this instance in place. + /// The new tag. + /// The new rank. + internal void Change(int tag, int rank) + { + _tag = tag; + _rank = rank; + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryScriptedSource.cs b/src/tests/ReactiveList.Tests/LiveQueryScriptedSource.cs new file mode 100644 index 00000000..59bf55f7 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryScriptedSource.cs @@ -0,0 +1,107 @@ +// 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. + +namespace ReactiveList.Tests; + +/// An unordered source whose notifications, failure, completion and disposal are all driven by the test. +/// The item type. +internal sealed class LiveQueryScriptedSource : IReactiveSource + where T : notnull +{ + /// The items the source holds. + private readonly List _items; + + /// The stream the test publishes to. + private readonly Signal> _stream = new(); + + /// Initializes a new instance of the class. + /// The initial items. + internal LiveQueryScriptedSource(IEnumerable items) => _items = new(items); + + /// + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add { } + remove { } + } + + /// + public int Count => _items.Count; + + /// + public bool IsReadOnly => false; + + /// + public bool IsDisposed { get; private set; } + + /// + /// The version never changes, so every notification a test publishes counts as newer than any copy of the source. + public long Version => 0; + + /// + public IObservable> Stream => Signal.Create>(Subscribe); + + /// Gets or sets a value indicating whether subscribing to the stream marks the source disposed and throws. + internal bool DisposeOnSubscribe { get; set; } + + /// + public T[] ToArray() => [.. _items]; + + /// + public void Dispose() + { + IsDisposed = true; + _stream.OnCompleted(); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator GetEnumerator() => _items.GetEnumerator(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// Adds an item and publishes the matching notification. + /// The item. + internal void Add(T item) + { + _items.Add(item); + _stream.OnNext(new(CacheAction.Added, item)); + } + + /// Adds an item without announcing it, so a test can make the source differ from what its notifications imply. + /// The item. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void AddWithoutNotification(T item) => _items.Add(item); + + /// Publishes a notification without changing the items. + /// The notification. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void Emit(CacheNotify notification) => _stream.OnNext(notification); + + /// Fails the stream. + /// The failure. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void Fail(Exception error) => _stream.OnError(error); + + /// Completes the stream. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void Complete() => _stream.OnCompleted(); + + /// Subscribes an observer to the stream, or fails the way a source that was disposed meanwhile does. + /// The observer. + /// The subscription. + /// Thrown when is set. + private IDisposable Subscribe(IObserver> observer) + { + if (DisposeOnSubscribe) + { + IsDisposed = true; + throw new ObjectDisposedException(nameof(LiveQueryScriptedSource<>)); + } + + return _stream.Subscribe(observer); + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQuerySelectManyTests.cs b/src/tests/ReactiveList.Tests/LiveQuerySelectManyTests.cs new file mode 100644 index 00000000..531fc852 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQuerySelectManyTests.cs @@ -0,0 +1,466 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks that SelectMany subscribes to an item's observable once when the item enters and unsubscribes exactly once when it leaves. +public class LiveQuerySelectManyTests +{ + /// The tag the filtered queries keep. + private const int KeptTag = TestData.TestValueTwo; + + /// The tag of an item whose observable fails. + private const int FailingTag = TestData.TestValueNine; + + /// The number of items that makes a rebuild replace the whole collection in one notification. + private const int ResetItems = 40; + + /// Subscriptions balance the included items after any mutation sequence on an ordered list, and reach zero on dispose. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedList_SubscriptionsBalanceAfterAnyMutations() + { + foreach (var script in LiveQueryModelCheck.SampleScripts()) + { + using var list = new ReactiveList(); + var nextId = 0; + var counter = new LiveQuerySubscriptionCounter(); + var all = new LiveQuerySubscriptionCounter(); + var recorder = new LiveQueryRecorder(); + var subscription = list.Live.Where(static r => r.Tag != KeptTag).SelectMany(counter.Observe).Subscribe(recorder); + var allSubscription = list.Live.SelectMany(all.Observe).Subscribe(new LiveQueryRecorder()); + foreach (var op in script) + { + LiveQueryOps.Apply(list, op, ref nextId); + } + + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == list.Count(static r => r.Tag != KeptTag) && all.Active == list.Count); + + subscription.Dispose(); + subscription.Dispose(); + allSubscription.Dispose(); + await Assert.That(counter.Active).IsEqualTo(0); + await Assert.That(all.Active).IsEqualTo(0); + await Assert.That(counter.Subscribed).IsEqualTo(counter.Unsubscribed); + } + } + + /// Subscriptions balance the included items after any mutation sequence on a sharded list, and reach zero on dispose. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryList_SubscriptionsBalanceAfterAnyMutations() + { + foreach (var script in LiveQueryModelCheck.SampleScripts()) + { + using var list = new QuaternaryList(); + var nextId = 0; + var counter = new LiveQuerySubscriptionCounter(); + var subscription = list.Live.Where(static r => r.Tag != KeptTag).SelectMany(counter.Observe).Subscribe(new LiveQueryRecorder()); + foreach (var op in script) + { + LiveQueryOps.Apply(list, op, ref nextId); + } + + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == list.ToArray().Count(static r => r.Tag != KeptTag)); + + subscription.Dispose(); + await Assert.That(counter.Active).IsEqualTo(0); + await Assert.That(counter.Subscribed).IsEqualTo(counter.Unsubscribed); + } + } + + /// Subscriptions balance when the source is disposed while items are still included. + /// Whether to exercise the versioned sharded source. + /// A task representing the asynchronous test. + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task SourceDisposed_ReleasesEveryItemSubscription(bool sharded) + { + LiveQueryRow[] rows = [new(0, 0, 0), new(1, 0, 0), new(TestData.TestValueTwo, 0, 0)]; + IReactiveSource list = sharded ? new QuaternaryList() : new ReactiveList(rows); + if (list is QuaternaryList quaternary) + { + quaternary.AddRange(rows); + } + + var counter = new LiveQuerySubscriptionCounter(); + var recorder = new LiveQueryRecorder(); + using var subscription = list.Live.SelectMany(counter.Observe).Subscribe(recorder); + using (list) + { + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == TestData.TestValueThree); + } + + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == 0 && recorder.Completed); + await Assert.That(counter.Subscribed).IsEqualTo(TestData.TestValueThree); + } + + /// Setting an item to the instance it already holds keeps its subscription. + /// A task representing the asynchronous test. + [Test] + public async Task Replace_WithTheSameInstance_KeepsTheSubscription() + { + var row = new LiveQueryRow(0, 0, 0); + using var list = new ReactiveList([row]); + var counter = new LiveQuerySubscriptionCounter(); + using var subscription = list.Live.SelectMany(counter.Observe).Subscribe(new LiveQueryRecorder()); + await TestWaitHelpers.WaitUntilAsync(() => counter.Subscribed == 1); + + list[0] = row; + + // The sentinel is applied after the replacement, so once it is subscribed the replacement was handled. + list.Add(new(1, 0, 0)); + await TestWaitHelpers.WaitUntilAsync(() => counter.Subscribed == TestData.TestValueTwo); + await Assert.That(counter.Unsubscribed).IsEqualTo(0); + } + + /// Replacing an item with an equal copy that is a different instance swaps the subscription. + /// A task representing the asynchronous test. + [Test] + public async Task Replace_WithAnEqualCopy_SwapsTheSubscription() + { + using var list = new ReactiveList([new(0, 0, 0)]); + var counter = new LiveQuerySubscriptionCounter(); + using var subscription = list.Live.SelectMany(counter.Observe).Subscribe(new LiveQueryRecorder()); + await TestWaitHelpers.WaitUntilAsync(() => counter.Subscribed == 1); + + list[0] = new(0, 0, 0); + + await TestWaitHelpers.WaitUntilAsync(() => counter.Subscribed == TestData.TestValueTwo && counter.Unsubscribed == 1); + await Assert.That(counter.Active).IsEqualTo(1); + } + + /// An item whose observable fails synchronously while the query is rebuilt ends the merge and releases every subscription. + /// A task representing the asynchronous test. + [Test] + public async Task InnerError_DuringReset_ReleasesEverySubscription() + { + var rows = new LiveQueryRow[ResetItems]; + for (var i = 0; i < rows.Length; i++) + { + rows[i] = new(i, 0, 0); + } + + using var list = new ReactiveList(rows); + var counter = new LiveQuerySubscriptionCounter(); + var recorder = new LiveQueryRecorder(); + using var subscription = list.Live.SelectMany(r => r.Tag == FailingTag ? counter.ObserveFailing(r) : counter.Observe(r)).Subscribe(recorder); + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == ResetItems); + + var replacement = (LiveQueryRow[])rows.Clone(); + replacement[ResetItems / TestData.TestValueTwo] = new(ResetItems, FailingTag, 0); + list.ReplaceAll(replacement); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Error is not null); + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == 0); + await Assert.That(counter.Subscribed).IsEqualTo(counter.Unsubscribed); + } + + /// An item whose observable fails when it enters the query ends the merge and releases every subscription. + /// Whether to use a sharded source. + /// A task representing the asynchronous test. + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task InnerError_OnSubscribe_ReleasesEverySubscription(bool sharded) + { + using var source = CreateSource(sharded, [new(0, 0, 0), new(1, 0, 0)]); + var counter = new LiveQuerySubscriptionCounter(); + var recorder = new LiveQueryRecorder(); + using var subscription = source.Live.SelectMany(r => r.Tag == FailingTag ? counter.ObserveFailing(r) : counter.Observe(r)).Subscribe(recorder); + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == TestData.TestValueTwo); + + Add(source, new(TestData.TestValueTwo, FailingTag, 0)); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Error is not null && counter.Active == 0); + await Assert.That(counter.Subscribed).IsEqualTo(counter.Unsubscribed); + } + + /// An item whose observable fails later ends the merge and releases every subscription. + /// Whether to use a sharded source. + /// A task representing the asynchronous test. + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task InnerError_AfterSubscribe_ReleasesEverySubscription(bool sharded) + { + using var source = CreateSource(sharded, [new(0, 0, 0), new(1, 0, 0), new(TestData.TestValueTwo, 0, 0)]); + var counter = new LiveQuerySubscriptionCounter(); + var recorder = new LiveQueryRecorder(); + using var subscription = source.Live.SelectMany(counter.ObserveControlled).Subscribe(recorder); + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == TestData.TestValueThree); + + counter.ControlFor(1).OnError(new InvalidOperationException("late failure")); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Error is not null && counter.Active == 0); + await Assert.That(counter.Subscribed).IsEqualTo(counter.Unsubscribed); + } + + /// An item's observable that completes does not end the merge, and its subscription is still released exactly once. + /// A task representing the asynchronous test. + [Test] + public async Task InnerCompletion_KeepsTheMergeAndReleasesOnce() + { + LiveQueryRow[] rows = [new(0, 0, 0), new(1, 0, 0), new(TestData.TestValueTwo, 0, 0)]; + using var list = new ReactiveList(rows); + var counter = new LiveQuerySubscriptionCounter(); + var recorder = new LiveQueryRecorder(); + var subscription = list.Live.SelectMany(counter.ObserveCompleting).Subscribe(recorder); + await TestWaitHelpers.WaitUntilAsync(() => counter.Subscribed == TestData.TestValueThree); + + list.RemoveAt(0); + list.Add(new(TestData.TestValueThree, 0, 0)); + + await TestWaitHelpers.WaitUntilAsync(() => counter.Subscribed == TestData.TestValueFour); + await Assert.That(recorder.Completed).IsFalse(); + await Assert.That(recorder.Error).IsNull(); + await Assert.That(counter.Unsubscribed).IsLessThanOrEqualTo(counter.Subscribed); + + subscription.Dispose(); + await Assert.That(counter.Subscribed).IsEqualTo(TestData.TestValueFour); + await Assert.That(counter.Unsubscribed).IsEqualTo(TestData.TestValueFour); + } + + /// Source writes made from an item's observable while it is subscribed are applied in order and keep the subscriptions balanced. + /// A task representing the asynchronous test. + [Test] + public async Task ReentrantSourceWrites_KeepSubscriptionsBalanced() + { + const int LastId = 3; + using var list = new ReactiveList(); + var counter = new LiveQuerySubscriptionCounter(); + var recorder = new LiveQueryRecorder(); + var subscription = list.Live.SelectMany(r => counter.ObserveWith(r, row => + { + if (row.Id < LastId) + { + list.Add(new(row.Id + 1, 0, 0)); + } + })).Subscribe(recorder); + + list.Add(new(0, 0, 0)); + + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == LastId + 1 && list.Count == LastId + 1); + await Assert.That(recorder.Values.Order()).IsEquivalentTo([0, 1, TestData.TestValueTwo, LastId], CollectionOrdering.Matching); + + subscription.Dispose(); + await Assert.That(counter.Active).IsEqualTo(0); + } + + /// Disposing the subscription from inside an item's observable releases that item and every other one. + /// A task representing the asynchronous test. + [Test] + public async Task DisposeInsideACallback_ReleasesEverySubscription() + { + using var list = new ReactiveList([new(0, 0, 0), new(1, 0, 0)]); + var counter = new LiveQuerySubscriptionCounter(); + IDisposable? subscription = null; + subscription = list.Live.SelectMany(r => counter.ObserveWith(r, row => + { + if (row.Id == TestData.TestValueTwo) + { + subscription?.Dispose(); + } + })).Subscribe(new LiveQueryRecorder()); + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == TestData.TestValueTwo); + + list.Add(new(TestData.TestValueTwo, 0, 0)); + list.Add(new(TestData.TestValueThree, 0, 0)); + + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == 0); + await Assert.That(counter.Subscribed).IsEqualTo(counter.Unsubscribed); + } + + /// Disposing on another thread while a drain is still subscribing an item releases every subscription once the drain ends. + /// A task representing the asynchronous test. + [Test] + public async Task DisposeOnAnotherThread_DuringADrain_ReleasesEverySubscription() + { + using var list = new ReactiveList([new(0, 0, 0), new(1, 0, 0)]); + var counter = new LiveQuerySubscriptionCounter(); + using var entered = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var subscription = list.Live.SelectMany(r => counter.ObserveWith(r, row => + { + if (row.Id != TestData.TestValueTwo) + { + return; + } + + entered.Set(); + + // A bounded wait, so the drain finishes even when disposal waits for it. + _ = release.Wait(TimeSpan.FromSeconds(TestData.TestValueTwo)); + })).Subscribe(new LiveQueryRecorder()); + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == TestData.TestValueTwo); + + var writer = Task.Run(() => list.AddRange([new(TestData.TestValueTwo, 0, 0), new(TestData.TestValueThree, 0, 0)])); + await TestWaitHelpers.WaitUntilAsync(() => entered.IsSet); + await Task.Run(subscription.Dispose); + release.Set(); + await writer; + + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == 0); + await Assert.That(counter.Subscribed).IsEqualTo(counter.Unsubscribed); + } + + /// Once disposal returns, a drain that was subscribing on another thread has finished and every subscription is released. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_WhileADrainIsSubscribing_ReturnsOnlyWhenBalanced() + { + using var list = new QuaternaryList(); + list.AddRange([new(0, 0, 0), new(1, 0, 0)]); + var counter = new LiveQuerySubscriptionCounter(); + using var entered = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var subscription = list.Live.SelectMany(r => counter.ObserveWith(r, row => + { + if (row.Id != TestData.TestValueTwo) + { + return; + } + + entered.Set(); + + // A bounded wait, so the drain finishes even if disposal never waits for it. + _ = release.Wait(TimeSpan.FromSeconds(TestData.TestValueTwo)); + })).Subscribe(new LiveQueryRecorder()); + await TestWaitHelpers.WaitUntilAsync(() => counter.Active == TestData.TestValueTwo); + + list.Add(new(TestData.TestValueTwo, 0, 0)); + await TestWaitHelpers.WaitUntilAsync(() => entered.IsSet); + var balancedAtReturn = false; + var disposal = Task.Run(() => + { + subscription.Dispose(); + balancedAtReturn = counter.Subscribed == counter.Unsubscribed; + }); + + // Disposal waits for the drain, so it is still running until the drain is released. A short bounded wait covers the case where it does not. + _ = SpinWait.SpinUntil(() => disposal.IsCompleted, TimeSpan.FromMilliseconds(TestData.TestValueTen * TestData.TestValueTen)); + release.Set(); + await disposal; + + await Assert.That(balancedAtReturn).IsTrue(); + } + + /// The result selector form combines each value with its item. + /// A task representing the asynchronous test. + [Test] + public async Task ResultSelector_CombinesValuesWithItems() + { + using var list = new ReactiveList([new(TestData.TestValueFive, 0, 0)]); + var counter = new LiveQuerySubscriptionCounter(); + var recorder = new LiveQueryRecorder(); + + using var subscription = list.Live.SelectMany(counter.Observe, static (row, id) => row.Id + id).Subscribe(recorder); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Values.SequenceEqual([TestData.TestValueTen])); + } + + /// A removed item and a disposed subscription do not keep items or the source alive. + /// A task representing the asynchronous test. + [Test] + public async Task RemovedItems_AreNotRetainedByTheSubscription() + { + using var list = new ReactiveList(); + var references = Populate(list); + using var subscription = list.Live.SelectMany(static h => new Signal()).Subscribe(new LiveQueryRecorder()); + + list.Clear(); + + // A new mutation replaces the source list's own removal history. + list.Add(new(0)); + + await TestWaitHelpers.WaitUntilAsync(() => AllCollected(references)); + } + + /// A disposed subscription does not keep the source alive. + /// A task representing the asynchronous test. + [Test] + public async Task DisposedSubscription_DoesNotRetainTheSource() + { + var reference = CreateAndDispose(); + + await TestWaitHelpers.WaitUntilAsync(() => !CollectAndCheck(reference)); + } + + /// Creates a source holding items. + /// Whether to create a sharded list. + /// The items. + /// The source. + private static IReactiveSource CreateSource(bool sharded, LiveQueryRow[] rows) + { + if (!sharded) + { + return new ReactiveList(rows); + } + + var list = new QuaternaryList(); + list.AddRange(rows); + return list; + } + + /// Adds an item to a source made by . + /// The source. + /// The item. + private static void Add(IReactiveSource source, LiveQueryRow row) + { + if (source is QuaternaryList quaternary) + { + quaternary.Add(row); + return; + } + + ((ReactiveList)source).Add(row); + } + + /// Creates items held only by a list and returns weak references to them. + /// The list to fill. + /// Weak references to the items. + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference[] Populate(ReactiveList list) + { + var references = new WeakReference[TestData.TestValueFive]; + for (var i = 0; i < references.Length; i++) + { + var item = new LiveQueryHeavy(i); + references[i] = new(item); + list.Add(item); + } + + return references; + } + + /// Subscribes to a list, disposes the subscription and returns a weak reference to the list. + /// A weak reference to the list. + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference CreateAndDispose() + { + var list = new ReactiveList([new(0)]); + var subscription = list.Live.SelectMany(static h => new Signal()).Subscribe(new LiveQueryRecorder()); + subscription.Dispose(); + return new(list); + } + + /// Collects garbage and tells whether every referenced item is gone. + /// The weak references. + /// when all items were collected. + private static bool AllCollected(WeakReference[] references) + { + _ = GC.GetTotalMemory(forceFullCollection: true); + return Array.TrueForAll(references, static r => !r.IsAlive); + } + + /// Collects garbage and tells whether the referenced object is still alive. + /// The weak reference. + /// when the object is still alive. + private static bool CollectAndCheck(WeakReference reference) + { + _ = GC.GetTotalMemory(forceFullCollection: true); + return reference.IsAlive; + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQuerySourceFailureTests.cs b/src/tests/ReactiveList.Tests/LiveQuerySourceFailureTests.cs new file mode 100644 index 00000000..6728a3e7 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQuerySourceFailureTests.cs @@ -0,0 +1,103 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks that live queries follow a source that clears silently or whose user code throws during a change. +public class LiveQuerySourceFailureTests +{ + /// The first item name. + private const string Alpha = "alpha"; + + /// The second item name. + private const string Beta = "beta"; + + /// The third item name. + private const string Gamma = "gamma"; + + /// The name of the item that replaces the second one. + private const string Replacement = "replacement"; + + /// Every kind of live query still follows a list that is cleared without announcing the change to legacy observers. + /// A task representing the asynchronous test. + [Test] + public async Task SilentClear_EmptiesEveryKindOfLiveQuery() + { + using var list = new ReactiveList([new(0, 0, 0), new(1, 1, 1), new(TestData.TestValueTwo, 0, TestData.TestValueTwo)]); + using var plain = list.Live.Where(static r => r.Tag == 0).ToView(Sequencer.Immediate, 0); + using var ordered = list.Live.OrderBy(static r => r.Rank).Take(TestData.TestValueTwo).ToView(Sequencer.Immediate, 0); + using var projected = list.Live.OrderBy(static r => r.Rank).Select(static r => r.Id).ToView(Sequencer.Immediate, 0); + using var grouped = list.Live.GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0); + var count = new LiveQueryRecorder(); + var any = new LiveQueryRecorder(); + using var subscriptions = new MultipleDisposable { list.Live.Count().Subscribe(count), list.Live.Any().Subscribe(any) }; + await TestWaitHelpers.WaitUntilAsync(() => plain.Count == TestData.TestValueTwo && ordered.Count == TestData.TestValueTwo && grouped.Count == TestData.TestValueTwo); + + list.ClearWithoutDeallocation(notifyChange: false); + + await TestWaitHelpers.WaitUntilAsync(() => plain.Count == 0 && ordered.Count == 0 && projected.Count == 0 && grouped.Count == 0); + await TestWaitHelpers.WaitUntilAsync(() => count.Last == 0 && !any.Last); + } + + /// A silent clear on a source that still holds items is followed by later writes. + /// A task representing the asynchronous test. + [Test] + public async Task SilentClear_ThenWrites_ViewsFollowTheNewContents() + { + using var list = new ReactiveList([new(0, 0, 0), new(1, 0, 1)]); + using var view = list.Live.OrderBy(static r => r.Rank).ToView(Sequencer.Immediate, 0); + await TestWaitHelpers.WaitUntilAsync(() => view.Count == TestData.TestValueTwo); + + list.ClearWithoutDeallocation(notifyChange: false); + list.Add(new(TestData.TestValueFive, 0, 0)); + + await TestWaitHelpers.WaitUntilAsync(() => view.Select(static r => r.Id).SequenceEqual([TestData.TestValueFive])); + } + + /// An edit whose equality throws is still committed, and live views and counts match the list. + /// A task representing the asynchronous test. + [Test] + public async Task EditWhoseEqualityThrows_ViewsMatchTheCommittedList() + { + var first = new ThrowingEqualityItem(Alpha); + var second = new ThrowingEqualityItem(Beta); + var third = new ThrowingEqualityItem(Gamma); + var other = new ThrowingEqualityItem(Replacement); + using var list = new ReactiveList([first, second, third]); + using var view = list.Live.OrderBy(static i => i.Name, StringComparer.Ordinal).ToView(Sequencer.Immediate, 0); + var count = new LiveQueryRecorder(); + using var subscription = list.Live.Count().Subscribe(count); + await TestWaitHelpers.WaitUntilAsync(() => view.Count == TestData.TestValueThree); + other.Failure.OnHash = true; + + Action edit = () => list.Edit(editor => editor[1] = other); + + await Assert.That(edit).Throws(); + string[] expected = [Alpha, Gamma, Replacement]; + await TestWaitHelpers.WaitUntilAsync(() => view.Select(static i => i.Name).SequenceEqual(expected)); + await TestWaitHelpers.WaitUntilAsync(() => count.Last == TestData.TestValueThree); + } + + /// A deferral whose release throws still announces the scope, and live views match the list. + /// A task representing the asynchronous test. + [Test] + public async Task DeferralReleaseThatThrows_ViewsMatchTheCommittedList() + { + var first = new ThrowingEqualityItem(Alpha); + var second = new ThrowingEqualityItem(Beta); + var other = new ThrowingEqualityItem(Replacement); + using var list = new ReactiveList([first, second]); + using var view = list.Live.ToView(Sequencer.Immediate, 0); + await TestWaitHelpers.WaitUntilAsync(() => view.Count == TestData.TestValueTwo); + var deferral = list.DeferNotifications(); + list[1] = other; + other.Failure.OnHash = true; + + Action release = deferral.Dispose; + + await Assert.That(release).Throws(); + string[] expected = [Alpha, Replacement]; + await TestWaitHelpers.WaitUntilAsync(() => view.Select(static i => i.Name).SequenceEqual(expected)); + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryStateTests.cs b/src/tests/ReactiveList.Tests/LiveQueryStateTests.cs new file mode 100644 index 00000000..99c293f1 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryStateTests.cs @@ -0,0 +1,317 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks the state streams: a first value on subscribe, no repeated values, the LINQ answer at quiescence and completion on dispose. +public class LiveQueryStateTests +{ + /// The tag the filtered streams keep. + private const int KeptTag = TestData.TestValueTwo; + + /// The item the contains streams look for. + private static readonly LiveQueryRow Probe = new(0, 0, 0); + + /// Count, Any and Contains over an ordered list agree with LINQ and behave like state streams. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedList_StateStreamsFollowLinq() + { + foreach (var script in LiveQueryModelCheck.SampleScripts()) + { + var list = new ReactiveList(); + var nextId = 0; + var count = new LiveQueryRecorder(); + var countWhere = new LiveQueryRecorder(); + var any = new LiveQueryRecorder(); + var anyWhere = new LiveQueryRecorder(); + var contains = new LiveQueryRecorder(); + var windowCount = new LiveQueryRecorder(); + using MultipleDisposable subscriptions = + [ + list.Live.Count().Subscribe(count), + list.Live.Count(static r => r.Tag == KeptTag).Subscribe(countWhere), + list.Live.Any().Subscribe(any), + list.Live.Any(static r => r.Tag == KeptTag).Subscribe(anyWhere), + list.Live.Contains(Probe).Subscribe(contains), + list.Live.Where(static r => r.Tag != 0).OrderBy(static r => r.Rank).Count().Subscribe(windowCount), + ]; + + await Assert.That(count.Values.Length).IsGreaterThan(0); + await Assert.That(count.Values[0]).IsEqualTo(0); + foreach (var op in script) + { + LiveQueryOps.Apply(list, op, ref nextId); + } + + await TestWaitHelpers.WaitUntilAsync(() => Agrees(list.ToArray(), count, countWhere, any, anyWhere, contains, windowCount)); + AssertNoRepeats(count, countWhere, any, anyWhere, contains, windowCount); + + list.Dispose(); + await TestWaitHelpers.WaitUntilAsync(() => count.Completed && contains.Completed && windowCount.Completed); + } + } + + /// Count, Any and Contains over a sharded list agree with LINQ and behave like state streams. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryList_StateStreamsFollowLinq() + { + foreach (var script in LiveQueryModelCheck.SampleScripts()) + { + var list = new QuaternaryList(); + var nextId = 0; + var count = new LiveQueryRecorder(); + var countWhere = new LiveQueryRecorder(); + var any = new LiveQueryRecorder(); + var anyWhere = new LiveQueryRecorder(); + var contains = new LiveQueryRecorder(); + var windowCount = new LiveQueryRecorder(); + using MultipleDisposable subscriptions = + [ + list.Live.Count().Subscribe(count), + list.Live.Count(static r => r.Tag == KeptTag).Subscribe(countWhere), + list.Live.Any().Subscribe(any), + list.Live.Any(static r => r.Tag == KeptTag).Subscribe(anyWhere), + list.Live.Contains(Probe).Subscribe(contains), + list.Live.Where(static r => r.Tag != 0).OrderBy(static r => r.Rank).Count().Subscribe(windowCount), + ]; + + await Assert.That(count.Values.Length).IsGreaterThan(0); + await Assert.That(count.Values[0]).IsEqualTo(0); + foreach (var op in script) + { + LiveQueryOps.Apply(list, op, ref nextId); + } + + await TestWaitHelpers.WaitUntilAsync(() => Agrees(list.ToArray(), count, countWhere, any, anyWhere, contains, windowCount)); + AssertNoRepeats(count, countWhere, any, anyWhere, contains, windowCount); + + list.Dispose(); + await TestWaitHelpers.WaitUntilAsync(() => count.Completed && contains.Completed && windowCount.Completed); + } + } + + /// Count, Any, Contains and ObserveValue over a dictionary agree with the dictionary and complete on dispose. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryDictionary_StateStreamsFollowTheDictionary() + { + foreach (var script in LiveQueryModelCheck.SampleScripts()) + { + var dictionary = new QuaternaryDictionary(); + var nextId = 0; + var count = new LiveQueryRecorder(); + var any = new LiveQueryRecorder(); + var tagged = new LiveQueryRecorder(); + var value = new LiveQueryRecorder>(); + var filtered = new LiveQueryRecorder>(); + using MultipleDisposable subscriptions = + [ + dictionary.Live.Count().Subscribe(count), + dictionary.Live.Any().Subscribe(any), + dictionary.Live.Count(static kv => kv.Value.Tag == KeptTag).Subscribe(tagged), + dictionary.Live.ObserveValue(1).Subscribe(value), + dictionary.Live.Where(static kv => kv.Value.Tag == KeptTag).ObserveValue(1).Subscribe(filtered), + ]; + + await Assert.That(value.Values.Length).IsGreaterThan(0); + await Assert.That(value.Values[0].Found).IsFalse(); + foreach (var op in script) + { + LiveQueryOps.Apply(dictionary, op, ref nextId); + } + + await TestWaitHelpers.WaitUntilAsync(() => DictionaryAgrees(dictionary, count, any, tagged, value, filtered)); + AssertNoRepeats(count, tagged); + await Assert.That(any.HasConsecutiveDuplicates()).IsFalse(); + await Assert.That(value.HasConsecutiveDuplicates()).IsFalse(); + await Assert.That(filtered.HasConsecutiveDuplicates()).IsFalse(); + + dictionary.Dispose(); + await TestWaitHelpers.WaitUntilAsync(() => (count.Completed && value.Completed && filtered.Completed) + || (count.Error ?? value.Error ?? filtered.Error) is not null); + await Assert.That(count.Error ?? value.Error ?? filtered.Error).IsNull(); + } + } + + /// A write that lands between subscribing to the source and the first count never makes a count negative or wrong. + /// A task representing the asynchronous test. + [Test] + public async Task Count_WriteDuringStart_FirstValueIsARealState() + { + using var inner = new QuaternaryList(); + LiveQueryRow[] rows = [new(0, KeptTag, 0), new(1, KeptTag, 0), new(TestData.TestValueTwo, KeptTag, 0), new(TestData.TestValueThree, KeptTag, 0), new(TestData.TestValueFour, KeptTag, 0)]; + inner.AddRange(rows); + var source = new LiveQueryVersionedSource(inner); + source.AfterNextSubscribe(() => inner.Remove(rows[0])); + var recorder = new LiveQueryRecorder(); + + using var subscription = source.Live.Count(static r => r.Tag == KeptTag).Subscribe(recorder); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Last == rows.Length - 1); + await Assert.That(Array.TrueForAll(recorder.Values, static count => count is >= TestData.TestValueFour and <= TestData.TestValueFive)).IsTrue(); + await Assert.That(recorder.Values[0]).IsGreaterThanOrEqualTo(TestData.TestValueFour); + } + + /// A write that lands between subscribing to the source and the first answer never makes Any report a false negative. + /// A task representing the asynchronous test. + [Test] + public async Task Any_WriteDuringStart_NeverReportsFalseWhileMatchesExist() + { + using var inner = new QuaternaryList(); + LiveQueryRow[] rows = [new(0, KeptTag, 0), new(1, KeptTag, 0)]; + inner.AddRange(rows); + var source = new LiveQueryVersionedSource(inner); + source.AfterNextSubscribe(() => inner.Remove(rows[0])); + var recorder = new LiveQueryRecorder(); + + using var subscription = source.Live.Any(static r => r.Tag == KeptTag).Subscribe(recorder); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Values.Length > 0); + await Assert.That(Array.TrueForAll(recorder.Values, static value => value)).IsTrue(); + } + + /// ObserveValue rejects a query that is not a plain filtered dictionary. + /// A task representing the asynchronous test. + [Test] + public async Task ObserveValue_AfterProjection_Throws() + { + using var dictionary = new QuaternaryDictionary(); + var projected = dictionary.Live.Select(static kv => new KeyValuePair(kv.Key, kv.Value)); + + var act = () => projected.ObserveValue(1); + + await Assert.That(act).Throws(); + } + + /// A state stream that subscribes to a source that is already disposed completes straight away. + /// A task representing the asynchronous test. + [Test] + public async Task DisposedSource_StateStreamCompletes() + { + var list = new ReactiveList(); + list.Dispose(); + var recorder = new LiveQueryRecorder(); + + using var subscription = list.Live.Count().Subscribe(recorder); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Completed); + } + + /// A source disposed during a keyed read completes the state stream without an error. + /// A task representing the asynchronous test. + [Test] + public async Task DictionaryDisposedDuringLookup_StateStreamCompletes() + { + using var dictionary = new QuaternaryDictionary(); + var recorder = new LiveQueryRecorder>(); + using var subscription = dictionary.Live.ObserveValue(new(dictionary.Dispose)).Subscribe(recorder); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Completed || recorder.Error is not null); + await Assert.That(recorder.Error).IsNull(); + await Assert.That(recorder.Values).IsEmpty(); + } + + /// Tells whether every list state stream shows the LINQ answer. + /// The source items. + /// The count recorder. + /// The filtered count recorder. + /// The any recorder. + /// The filtered any recorder. + /// The contains recorder. + /// The recorder of the count of a filtered, ordered query. + /// when all agree. + private static bool Agrees( + LiveQueryRow[] items, + LiveQueryRecorder count, + LiveQueryRecorder countWhere, + LiveQueryRecorder any, + LiveQueryRecorder anyWhere, + LiveQueryRecorder contains, + LiveQueryRecorder windowCount) => + count.Last == items.Length + && countWhere.Last == items.Count(static r => r.Tag == KeptTag) + && any.Last == (items.Length > 0) + && anyWhere.Last == Array.Exists(items, static r => r.Tag == KeptTag) + && contains.Last == items.Contains(Probe) + && windowCount.Last == items.Count(static r => r.Tag != 0); + + /// Tells whether the dictionary state streams show what the dictionary holds. + /// The dictionary. + /// The count recorder. + /// The any recorder. + /// The filtered count recorder. + /// The value recorder. + /// The filtered value recorder. + /// when all agree. + private static bool DictionaryAgrees( + QuaternaryDictionary dictionary, + LiveQueryRecorder count, + LiveQueryRecorder any, + LiveQueryRecorder tagged, + LiveQueryRecorder> value, + LiveQueryRecorder> filtered) + { + var entries = dictionary.ToArray(); + var found = dictionary.TryGetValue(1, out var current); + var expectedFiltered = found && current!.Tag == KeptTag; + return count.Last == entries.Length + && any.Last == (entries.Length > 0) + && tagged.Last == entries.Count(static kv => kv.Value.Tag == KeptTag) + && value.Last.Found == found + && (!found || value.Last.Value == current) + && filtered.Last.Found == expectedFiltered + && (!expectedFiltered || filtered.Last.Value == current); + } + + /// Asserts that no integer stream repeated a value. + /// The recorders. + /// Thrown when a stream repeated a value. + private static void AssertNoRepeats(params LiveQueryRecorder[] recorders) + { + foreach (var recorder in recorders) + { + if (recorder.HasConsecutiveDuplicates()) + { + throw new InvalidOperationException($"A stream repeated a value: {string.Join(", ", recorder.Values)}"); + } + } + } + + /// Asserts that no stream repeated a value. + /// The count recorder. + /// The filtered count recorder. + /// The any recorder. + /// The filtered any recorder. + /// The contains recorder. + /// The recorder of the count of a filtered, ordered query. + /// Thrown when a stream repeated a value. + private static void AssertNoRepeats( + LiveQueryRecorder count, + LiveQueryRecorder countWhere, + LiveQueryRecorder any, + LiveQueryRecorder anyWhere, + LiveQueryRecorder contains, + LiveQueryRecorder windowCount) + { + AssertNoRepeats(count, countWhere, windowCount); + if (any.HasConsecutiveDuplicates() || anyWhere.HasConsecutiveDuplicates() || contains.HasConsecutiveDuplicates()) + { + throw new InvalidOperationException("A boolean stream repeated a value."); + } + } + + /// Disposes the source after the query's disposal check and before the lookup takes a shard lock. + /// Disposes the dictionary being read. + private sealed record DisposingLookupKey(Action DisposeSource) + { + /// + public override int GetHashCode() + { + DisposeSource(); + return 0; + } + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQuerySubscriptionCounter.cs b/src/tests/ReactiveList.Tests/LiveQuerySubscriptionCounter.cs new file mode 100644 index 00000000..af67cb53 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQuerySubscriptionCounter.cs @@ -0,0 +1,105 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Builds observables that count how often they are subscribed and unsubscribed, with several ways to end or interrupt a subscription. +internal sealed class LiveQuerySubscriptionCounter +{ + /// The signals tests use to drive an item's observable. + private readonly System.Collections.Concurrent.ConcurrentDictionary> _controls = new(); + + /// The number of subscriptions made. + private int _subscribed; + + /// The number of subscriptions disposed. + private int _unsubscribed; + + /// Gets the number of subscriptions made. + internal int Subscribed => Volatile.Read(ref _subscribed); + + /// Gets the number of subscriptions disposed. + internal int Unsubscribed => Volatile.Read(ref _unsubscribed); + + /// Gets the number of subscriptions still active. + internal int Active => Subscribed - Unsubscribed; + + /// Creates the counted observable of an item. + /// The item. + /// An observable that emits the item's id when subscribed and counts its subscription. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal IObservable Observe(LiveQueryRow row) => + Signal.Create(observer => + { + _ = Interlocked.Increment(ref _subscribed); + observer.OnNext(row.Id); + return CountedScope(); + }); + + /// Creates the counted observable of an item that fails as soon as it is subscribed. + /// The item. + /// An observable that fails when subscribed and counts its subscription. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal IObservable ObserveFailing(LiveQueryRow row) => + Signal.Create(observer => + { + _ = Interlocked.Increment(ref _subscribed); + observer.OnError(new InvalidOperationException($"Item {row.Id} failed.")); + return CountedScope(); + }); + + /// Creates the counted observable of an item that emits and completes as soon as it is subscribed. + /// The item. + /// An observable that completes when subscribed and counts its subscription. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal IObservable ObserveCompleting(LiveQueryRow row) => + Signal.Create(observer => + { + _ = Interlocked.Increment(ref _subscribed); + observer.OnNext(row.Id); + observer.OnCompleted(); + return CountedScope(); + }); + + /// Creates the counted observable of an item that runs a callback while it is being subscribed. + /// The item. + /// The callback, which runs after the subscription was counted and the item's id was emitted. + /// An observable that runs the callback when subscribed and counts its subscription. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal IObservable ObserveWith(LiveQueryRow row, Action whileSubscribing) => + Signal.Create(observer => + { + _ = Interlocked.Increment(ref _subscribed); + observer.OnNext(row.Id); + whileSubscribing(row); + return CountedScope(); + }); + + /// Creates the counted observable of an item that emits, fails or completes when a test drives its signal. + /// The item. + /// An observable that follows and counts its subscription. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal IObservable ObserveControlled(LiveQueryRow row) => + Signal.Create(observer => + { + _ = Interlocked.Increment(ref _subscribed); + var inner = ControlFor(row.Id).Subscribe(observer); + return Scope.Create((inner, this), static state => + { + state.inner.Dispose(); + _ = Interlocked.Increment(ref state.Item2._unsubscribed); + }); + }); + + /// Gets the signal that drives the controlled observable of an item. + /// The identity of the item. + /// The signal. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal Signal ControlFor(int id) => _controls.GetOrAdd(id, static _ => new()); + + /// Creates the disposable that counts the disposal of a subscription. + /// The disposable. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private IDisposable CountedScope() => Scope.Create(this, static counter => Interlocked.Increment(ref counter._unsubscribed)); +} diff --git a/src/tests/ReactiveList.Tests/LiveQuerySurfaceTests.cs b/src/tests/ReactiveList.Tests/LiveQuerySurfaceTests.cs new file mode 100644 index 00000000..f3c180bb --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQuerySurfaceTests.cs @@ -0,0 +1,217 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks every overload a live query offers. +public class LiveQuerySurfaceTests +{ + /// The scale that lets one value carry an item identity and a value of its observable. + private const int Scale = 10; + + /// The values the combining overload produces for the three rows, in ascending order. + private static readonly int[] CombinedValues = [11, 22, 33]; + + /// Every view creation overload produces a view with the expected items. + /// A task representing the asynchronous test. + [Test] + public async Task ToView_EveryOverload_FollowsTheSource() + { + using var list = new ReactiveList(Rows()); + var plain = list.Live; + var ordered = plain.OrderBy(static r => r.Rank); + var windowed = ordered.Take(TestData.TestValueTwo); + var grouped = plain.GroupBy(static r => r.Tag); + using var plainDefault = plain.ToView(); + using var plainThrottled = plain.ToView(0); + using var orderedDefault = ordered.ToView(); + using var orderedThrottled = ordered.ToView(0); + using var orderedScheduled = ordered.ToView(Sequencer.Immediate); + using var windowedDefault = windowed.ToView(); + using var windowedScheduled = windowed.ToView(Sequencer.Immediate); + using var windowedThrottled = windowed.ToView(0); + using var groupedDefault = grouped.ToView(); + using var groupedScheduled = grouped.ToView(Sequencer.Immediate); + using var groupedThrottled = grouped.ToView(0); + + await TestWaitHelpers.WaitUntilAsync(() => + plainDefault.Count == TestData.TestValueThree + && plainThrottled.Count == TestData.TestValueThree + && orderedDefault.Count == TestData.TestValueThree + && orderedThrottled.Count == TestData.TestValueThree + && orderedScheduled.Count == TestData.TestValueThree + && windowedDefault.Count == TestData.TestValueTwo + && windowedScheduled.Count == TestData.TestValueTwo + && windowedThrottled.Count == TestData.TestValueTwo + && groupedDefault.Count == TestData.TestValueTwo + && groupedScheduled.Count == TestData.TestValueTwo + && groupedThrottled.Count == TestData.TestValueTwo); + await Assert.That(orderedScheduled.Select(static r => r.Id)).IsEquivalentTo([TestData.TestValueThree, TestData.TestValueTwo, 1], CollectionOrdering.Matching); + } + + /// Descending orders and tie breakers accept a comparer for their key. + /// A task representing the asynchronous test. + [Test] + public async Task Orderings_WithComparers_FollowTheComparers() + { + using var list = new ReactiveList(Rows()); + using var descending = list.Live.OrderByDescending(static r => r.Rank, Comparer.Default).ToView(Sequencer.Immediate, 0); + using var ascendingThenDescending = list.Live.OrderBy(static r => r.Tag).ThenByDescending(static r => r.Rank, Comparer.Default).ToView(Sequencer.Immediate, 0); + using var ascendingThenAscending = list.Live.OrderBy(static r => r.Tag).ThenBy(static r => r.Rank, Comparer.Default).ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => + descending.Count == TestData.TestValueThree + && ascendingThenDescending.Count == TestData.TestValueThree + && ascendingThenAscending.Count == TestData.TestValueThree); + await Assert.That(descending.Select(static r => r.Id)).IsEquivalentTo([1, TestData.TestValueTwo, TestData.TestValueThree], CollectionOrdering.Matching); + await Assert.That(ascendingThenDescending.Select(static r => r.Id)).IsEquivalentTo([1, TestData.TestValueThree, TestData.TestValueTwo], CollectionOrdering.Matching); + await Assert.That(ascendingThenAscending.Select(static r => r.Id)).IsEquivalentTo([TestData.TestValueThree, 1, TestData.TestValueTwo], CollectionOrdering.Matching); + } + + /// Skip and take counts that arrive over time open the window of an unordered query. + /// A task representing the asynchronous test. + [Test] + public async Task UnorderedWindow_FollowsObservableCounts() + { + using var list = new ReactiveList(Rows()); + var take = new Signal(); + var skip = new Signal(); + using var taken = list.Live.Take(take).ToView(Sequencer.Immediate, 0); + using var skipped = list.Live.Skip(skip).ToView(Sequencer.Immediate, 0); + + take.OnNext(TestData.TestValueTwo); + skip.OnNext(1); + + await TestWaitHelpers.WaitUntilAsync(() => taken.Count == TestData.TestValueTwo && skipped.Count == TestData.TestValueTwo); + } + + /// A window whose count source fails or completes keeps the last count. + /// A task representing the asynchronous test. + [Test] + public async Task WindowCounts_EndingOrFailing_KeepTheLastCount() + { + using var list = new ReactiveList(Rows()); + var completing = new Signal(); + var failing = new Signal(); + using var completed = list.Live.Take(completing).ToView(Sequencer.Immediate, 0); + using var failed = list.Live.Take(failing).ToView(Sequencer.Immediate, 0); + using var everything = list.Live.ToView(Sequencer.Immediate, 0); + completing.OnNext(1); + failing.OnNext(1); + await TestWaitHelpers.WaitUntilAsync(() => completed.Count == 1 && failed.Count == 1); + + completing.OnCompleted(); + failing.OnError(new InvalidOperationException("The count failed.")); + list.Add(new(TestData.TestValueFour, 0, 0)); + + await TestWaitHelpers.WaitUntilAsync(() => everything.Count == TestData.TestValueFour); + await Assert.That(completed.Count).IsEqualTo(1); + await Assert.That(failed.Count).IsEqualTo(1); + } + + /// An ordered query merges the observables of its items, alone or combined with the item. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedQuery_SelectMany_MergesItemObservables() + { + using var list = new ReactiveList(Rows()); + var counter = new LiveQuerySubscriptionCounter(); + var plain = new LiveQueryRecorder(); + var combined = new LiveQueryRecorder(); + using var plainSubscription = list.Live.OrderBy(static r => r.Rank).SelectMany(counter.Observe).Subscribe(plain); + using var combinedSubscription = list.Live.OrderBy(static r => r.Rank) + .SelectMany(counter.Observe, static (row, id) => (row.Id * Scale) + id) + .Subscribe(combined); + + await TestWaitHelpers.WaitUntilAsync(() => plain.Values.Length == TestData.TestValueThree && combined.Values.Length == TestData.TestValueThree); + await Assert.That(plain.Values.Order()).IsEquivalentTo([1, TestData.TestValueTwo, TestData.TestValueThree], CollectionOrdering.Matching); + await Assert.That(combined.Values.Order()).IsEquivalentTo(CombinedValues, CollectionOrdering.Matching); + } + + /// A query merges item observables with and without an ordering through the combining overload. + /// A task representing the asynchronous test. + [Test] + public async Task Query_SelectMany_CombinesItemsWithTheirValues() + { + using var list = new ReactiveList(Rows()); + var counter = new LiveQuerySubscriptionCounter(); + var combined = new LiveQueryRecorder(); + using var subscription = list.Live.SelectMany(counter.Observe, static (row, id) => (row.Id * Scale) + id).Subscribe(combined); + + await TestWaitHelpers.WaitUntilAsync(() => combined.Values.Length == TestData.TestValueThree); + await Assert.That(combined.Values.Order()).IsEquivalentTo(CombinedValues, CollectionOrdering.Matching); + } + + /// An ordered query reports whether it holds any item and whether it holds a given item. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedQuery_AnyAndContains_ReportMembership() + { + var first = new LiveQueryRow(1, 0, 0); + using var list = new ReactiveList(); + var any = new LiveQueryRecorder(); + var contains = new LiveQueryRecorder(); + using var anySubscription = list.Live.OrderBy(static r => r.Rank).Any().Subscribe(any); + using var containsSubscription = list.Live.OrderBy(static r => r.Rank).Contains(first).Subscribe(contains); + await TestWaitHelpers.WaitUntilAsync(() => any.Values.Length > 0 && !any.Last && !contains.Last); + + list.Add(first); + + await TestWaitHelpers.WaitUntilAsync(() => any.Last && contains.Last); + } + + /// A projection that follows an ordering can be ordered again, filtered, merged and tallied. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedProjection_SupportsFurtherOperators() + { + using var list = new ReactiveList(Rows()); + var merged = new LiveQueryRecorder(); + var any = new LiveQueryRecorder(); + var count = new LiveQueryRecorder(); + var projection = list.Live.OrderBy(static r => r.Rank).Select(static r => r.Id); + using var view = projection.Select(static id => id * Scale).Where(static id => id > Scale).ToView(Sequencer.Immediate, 0); + using var reordered = projection.OrderByDescending(static id => id).Select(static id => id + 1).ToView(Sequencer.Immediate, 0); + using var mergedSubscription = projection.SelectMany(EmitOnce).Subscribe(merged); + using var anySubscription = projection.Any(static id => id > TestData.TestValueTwo).Subscribe(any); + using var countSubscription = projection.Count(static id => id > 1).Subscribe(count); + + await TestWaitHelpers.WaitUntilAsync(() => + view.Count == TestData.TestValueTwo + && reordered.Count == TestData.TestValueThree + && merged.Values.Length == TestData.TestValueThree + && any.Last + && count.Last == TestData.TestValueTwo); + await Assert.That(reordered.Select(static id => id)).IsEquivalentTo([TestData.TestValueFour, TestData.TestValueThree, TestData.TestValueTwo], CollectionOrdering.Matching); + } + + /// The value of a key can only be observed on a query made straight from a dictionary. + /// A task representing the asynchronous test. + [Test] + public async Task ObserveValue_OnAnOrderedProjection_Throws() + { + using var dictionary = new QuaternaryDictionary(); + + Func>> projected = () => dictionary.Live.OrderBy(static e => e.Key).Select(static e => e).ObserveValue(1); + Func>> empty = static () => default(LiveQuery>).ObserveValue(1); + + await Assert.That(projected).Throws(); + await Assert.That(empty).Throws(); + } + + /// Creates an observable that emits one value when subscribed. + /// The value. + /// The observable. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static IObservable EmitOnce(int value) => + Signal.Create(observer => + { + observer.OnNext(value); + return Scope.Empty; + }); + + /// Creates the rows the surface tests use. + /// Three rows with distinct ranks and two tags. + private static LiveQueryRow[] Rows() => [new(1, 0, TestData.TestValueTwo), new(TestData.TestValueTwo, 1, 1), new(TestData.TestValueThree, 0, 0)]; +} diff --git a/src/tests/ReactiveList.Tests/LiveQuerySyntaxTests.cs b/src/tests/ReactiveList.Tests/LiveQuerySyntaxTests.cs new file mode 100644 index 00000000..a0b9558a --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQuerySyntaxTests.cs @@ -0,0 +1,183 @@ +// 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. + +using System.Linq; + +namespace ReactiveList.Tests; + +/// Checks that C# query syntax binds to the live query by pattern and never to LINQ, even with System.Linq in scope. +public class LiveQuerySyntaxTests +{ + /// The tag some queries keep. + private const int KeptTag = TestData.TestValueTwo; + + /// A where clause and an ordering compile and run against the live query. + /// A task representing the asynchronous test. + [Test] + public async Task WhereOrderBy_QuerySyntaxBindsToTheLiveQuery() + { + using var list = new ReactiveList([new(0, KeptTag, TestData.TestValueTwo), new(1, 0, 0), new(TestData.TestValueTwo, KeptTag, 1)]); + + var query = from row in list.Live + where row.Tag == KeptTag + orderby row.Rank + select row; + using var view = query.ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => view.Select(static r => r.Id).SequenceEqual([TestData.TestValueTwo, 0])); + } + + /// A secondary ordering clause binds to the ThenBy members. + /// A task representing the asynchronous test. + [Test] + public async Task OrderByThenByDescending_QuerySyntaxBindsToTheLiveQuery() + { + using var list = new ReactiveList([new(0, 1, 0), new(1, 0, 0), new(TestData.TestValueTwo, 0, 1)]); + + var query = from row in list.Live + orderby row.Rank, row.Tag descending + select row; + using var view = query.ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => view.Select(static r => r.Id).SequenceEqual([0, 1, TestData.TestValueTwo])); + } + + /// A projection binds to the Select member. + /// A task representing the asynchronous test. + [Test] + public async Task Select_QuerySyntaxBindsToTheLiveQuery() + { + using var list = new ReactiveList([new(1, 0, 0), new(TestData.TestValueTwo, 0, 0)]); + + var query = from row in list.Live + where row.Id > 1 + select row.Id * TestData.TestValueTen; + using var view = query.ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => view.SequenceEqual([TestData.TestValueTwenty])); + } + + /// A grouping clause binds to the GroupBy member. + /// A task representing the asynchronous test. + [Test] + public async Task GroupBy_QuerySyntaxBindsToTheLiveQuery() + { + using var list = new ReactiveList([new(0, 1, 0), new(1, 0, 0), new(TestData.TestValueTwo, 1, 0)]); + + var query = from row in list.Live + group row by row.Tag; + using var view = query.ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => view.Count == TestData.TestValueTwo && view[1].Count == TestData.TestValueTwo); + } + + /// A second from clause binds to the SelectMany member and merges the inner observables. + /// A task representing the asynchronous test. + [Test] + public async Task SelectMany_QuerySyntaxBindsToTheLiveQuery() + { + using var list = new ReactiveList([new(1, 0, 0)]); + var inner = new Signal(); + var recorder = new LiveQueryRecorder(); + + var query = from row in list.Live + from value in inner + select value + row.Id; + using var subscription = query.Subscribe(recorder); + inner.OnNext(TestData.TestValueTen); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Values.SequenceEqual([TestData.TestValueTen + 1])); + } + + /// A projection after an ordering clause compiles and projects the ordered items. + /// A task representing the asynchronous test. + [Test] + public async Task OrderBySelect_QuerySyntaxProjectsTheOrderedItems() + { + using var list = new ReactiveList([new(0, 0, TestData.TestValueTwo), new(1, 0, 0), new(TestData.TestValueTwo, 0, 1)]); + + var query = from row in list.Live + orderby row.Rank + select row.Id; + using var view = query.ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => view.SequenceEqual([1, TestData.TestValueTwo, 0])); + } + + /// A where clause after an ordering clause filters and keeps the order. + /// A task representing the asynchronous test. + [Test] + public async Task OrderByWhere_QuerySyntaxFiltersAndKeepsTheOrder() + { + using var list = new ReactiveList([new(0, KeptTag, TestData.TestValueTwo), new(1, 0, 0), new(TestData.TestValueTwo, KeptTag, 1)]); + + var query = from row in list.Live + orderby row.Rank + where row.Tag == KeptTag + select row; + using var view = query.ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => view.Select(static r => r.Id).SequenceEqual([TestData.TestValueTwo, 0])); + } + + /// A grouping clause with an element projects the elements into the groups. + /// A task representing the asynchronous test. + [Test] + public async Task GroupByElement_QuerySyntaxHoldsTheElements() + { + using var list = new ReactiveList([new(0, 1, 0), new(1, 0, 0), new(TestData.TestValueTwo, 1, 0)]); + + var query = from row in list.Live + orderby row.Id descending + group row.Id by row.Tag; + using var view = query.ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => view.Groups.Select(static g => g.Key).SequenceEqual([1, 0]) && view[1].SequenceEqual([TestData.TestValueTwo, 0])); + } + + /// A projection after a window written with method syntax continues in query syntax. + /// A task representing the asynchronous test. + [Test] + public async Task SelectAfterWindow_QuerySyntaxBindsToTheWindowedQuery() + { + using var list = new ReactiveList([new(0, 0, TestData.TestValueTwo), new(1, 0, 0), new(TestData.TestValueTwo, 0, 1)]); + + var query = from row in list.Live.OrderBy(static r => r.Rank).Skip(1).Take(TestData.TestValueTwo) + select row.Id * TestData.TestValueTen; + using var view = query.ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => view.SequenceEqual([TestData.TestValueTwenty, 0])); + } + + /// The live query of a dictionary resolves to the dictionary overload and its clauses bind in query syntax. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_LiveResolvesWithoutAmbiguity() + { + using var dictionary = new QuaternaryDictionary(); + dictionary.AddRange([new(1, new(1, 0, TestData.TestValueTwo)), new(TestData.TestValueTwo, new(TestData.TestValueTwo, 0, 0))]); + + var query = from entry in dictionary.Live + orderby entry.Value.Rank + select entry.Key; + using var view = query.ToView(Sequencer.Immediate, 0); + var observed = dictionary.Live.ObserveValue(1); + var recorder = new LiveQueryRecorder>(); + using var subscription = observed.Subscribe(recorder); + + await TestWaitHelpers.WaitUntilAsync(() => view.SequenceEqual([TestData.TestValueTwo, 1]) && recorder.Last.Found); + } + + /// LINQ operators still bind to plain enumerables in the same file, so the live query adds no ambiguity. + /// A task representing the asynchronous test. + [Test] + public async Task LinqOverEnumerables_StillBindsToEnumerable() + { + int[] numbers = [TestData.TestValueThree, 1, TestData.TestValueTwo]; + + var sorted = numbers.Where(static n => n > 0).Order().ToArray(); + + await Assert.That(sorted).IsEquivalentTo([1, TestData.TestValueTwo, TestData.TestValueThree]); + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryVersionedList.cs b/src/tests/ReactiveList.Tests/LiveQueryVersionedList.cs new file mode 100644 index 00000000..b4ebabf0 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryVersionedList.cs @@ -0,0 +1,254 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Wraps an ordered list and counts how often either of its streams is subscribed, forwarding its versioned snapshots as the list does. +/// The item type. +internal sealed class LiveQueryVersionedList : IReactiveList, IVersionedSnapshotSource + where T : notnull +{ + /// The wrapped list. + private readonly ReactiveList _inner; + + /// The number of subscriptions to the stream so far. + private int _subscriptions; + + /// The number of stream subscriptions that were disposed. + private int _disposedSubscriptions; + + /// Initializes a new instance of the class. + /// The list to wrap. + internal LiveQueryVersionedList(ReactiveList inner) + { + _inner = inner; + Stream = Signal.Create>(Subscribe); + VersionedStream = Signal.Create>(SubscribeVersioned); + } + + /// + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add => ((INotifyCollectionChanged)_inner).CollectionChanged += value; + remove => ((INotifyCollectionChanged)_inner).CollectionChanged -= value; + } + + /// + public event PropertyChangedEventHandler? PropertyChanged + { + add => ((INotifyPropertyChanged)_inner).PropertyChanged += value; + remove => ((INotifyPropertyChanged)_inner).PropertyChanged -= value; + } + + /// + public int Count => _inner.Count; + + /// + public bool IsReadOnly => _inner.IsReadOnly; + + /// + public bool IsDisposed => _inner.IsDisposed; + + /// + public long Version => _inner.Version; + + /// + public IObservable> Stream { get; } + + /// + public IObservable> VersionedStream { get; } + + /// + public IObservable> Added => _inner.Added; + + /// + public IObservable> Changed => _inner.Changed; + + /// + public IObservable> CurrentItems => _inner.CurrentItems; + + /// + public ReadOnlyObservableCollection Items => _inner.Items; + + /// + public ReadOnlyObservableCollection ItemsAdded => _inner.ItemsAdded; + + /// + public ReadOnlyObservableCollection ItemsChanged => _inner.ItemsChanged; + + /// + public ReadOnlyObservableCollection ItemsRemoved => _inner.ItemsRemoved; + + /// + public IObservable> Removed => _inner.Removed; + + /// + bool IList.IsFixedSize => ((IList)_inner).IsFixedSize; + + /// + bool ICollection.IsSynchronized => ((ICollection)_inner).IsSynchronized; + + /// + object ICollection.SyncRoot => ((ICollection)_inner).SyncRoot; + + /// Gets the number of subscriptions to the stream so far. + internal int Subscriptions => Volatile.Read(ref _subscriptions); + + /// Gets the number of stream subscriptions that are still active. + internal int ActiveSubscriptions => Volatile.Read(ref _subscriptions) - Volatile.Read(ref _disposedSubscriptions); + + /// + public T this[int index] + { + get => _inner[index]; + set => _inner[index] = value; + } + + /// + object? IList.this[int index] + { + get => ((IList)_inner)[index]; + set => ((IList)_inner)[index] = value; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T[] ToArray() => _inner.ToArray(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T[] CopyVersioned(out long version) => ((IVersionedSnapshotSource)_inner).CopyVersioned(out version); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _inner.Dispose(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator GetEnumerator() => _inner.GetEnumerator(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(T item) => _inner.Add(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddRange(IEnumerable items) => _inner.AddRange(items); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() => _inner.Clear(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Contains(T item) => _inner.Contains(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void CopyTo(T[] array, int arrayIndex) => _inner.CopyTo(array, arrayIndex); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Edit(Action> editAction) => _inner.Edit(editAction); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int IndexOf(T item) => _inner.IndexOf(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Insert(int index, T item) => _inner.Insert(index, item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void InsertRange(int index, IEnumerable items) => _inner.InsertRange(index, items); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Move(int oldIndex, int newIndex) => _inner.Move(oldIndex, newIndex); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Remove(T item) => _inner.Remove(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Remove(IEnumerable items) => _inner.Remove(items); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RemoveAt(int index) => _inner.RemoveAt(index); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int RemoveMany(Func predicate) => _inner.RemoveMany(predicate); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RemoveRange(int index, int count) => _inner.RemoveRange(index, count); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ReplaceAll(IEnumerable items) => _inner.ReplaceAll(items); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Update(T item, T newValue) => _inner.Update(item, newValue); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + int IList.Add(object? value) => ((IList)_inner).Add(value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + bool IList.Contains(object? value) => ((IList)_inner).Contains(value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + int IList.IndexOf(object? value) => ((IList)_inner).IndexOf(value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void IList.Insert(int index, object? value) => ((IList)_inner).Insert(index, value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void IList.Remove(object? value) => ((IList)_inner).Remove(value); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void ICollection.CopyTo(Array array, int index) => ((ICollection)_inner).CopyTo(array, index); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// Subscribes to the wrapped versioned stream and counts the subscription. + /// The observer. + /// The subscription. + private IDisposable SubscribeVersioned(IObserver> observer) + { + _ = Interlocked.Increment(ref _subscriptions); + var inner = ((IVersionedSnapshotSource)_inner).VersionedStream.Subscribe(observer); + return Scope.Create((inner, this), static state => + { + state.inner.Dispose(); + _ = Interlocked.Increment(ref state.Item2._disposedSubscriptions); + }); + } + + /// Subscribes to the wrapped stream and counts the subscription. + /// The observer. + /// The subscription. + private IDisposable Subscribe(IObserver> observer) + { + _ = Interlocked.Increment(ref _subscriptions); + var inner = _inner.Stream.Subscribe(observer); + return Scope.Create((inner, this), static state => + { + state.inner.Dispose(); + _ = Interlocked.Increment(ref state.Item2._disposedSubscriptions); + }); + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryVersionedSource.cs b/src/tests/ReactiveList.Tests/LiveQueryVersionedSource.cs new file mode 100644 index 00000000..93cfca2f --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryVersionedSource.cs @@ -0,0 +1,160 @@ +// 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. + +namespace ReactiveList.Tests; + +/// +/// Wraps a sharded source that publishes versioned notifications, forwards both streams and counts every subscription to either of them. +/// A hook can run right after a subscription is made, which lets a test write to the source in the gap before the subscriber is ready. +/// +/// The item type. +internal sealed class LiveQueryVersionedSource : IReactiveSource, IVersionedSnapshotSource + where T : notnull +{ + /// The longest a hook waits for the subscriber to handle the notification the hook caused. + private const int DeliveryTimeoutSeconds = 10; + + /// The wrapped source. + private readonly IReactiveSource _inner; + + /// The versioned view of the wrapped source. + private readonly IVersionedSnapshotSource _versioned; + + /// The number of subscriptions made so far. + private int _subscriptions; + + /// The number of subscriptions that were disposed. + private int _disposedSubscriptions; + + /// The number of values the subscribers have handled. + private int _delivered; + + /// Runs once, right after the next subscription was made. + private Action? _afterSubscribe; + + /// Initializes a new instance of the class. + /// The source to wrap, which must publish versioned notifications. + internal LiveQueryVersionedSource(IReactiveSource inner) + { + _inner = inner; + _versioned = (IVersionedSnapshotSource)inner; + Stream = Signal.Create>(SubscribePlain); + VersionedStream = Signal.Create>(SubscribeVersioned); + } + + /// + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add => _inner.CollectionChanged += value; + remove => _inner.CollectionChanged -= value; + } + + /// + public int Count => _inner.Count; + + /// + public bool IsReadOnly => _inner.IsReadOnly; + + /// + public bool IsDisposed => _inner.IsDisposed; + + /// + public long Version => _inner.Version; + + /// + public IObservable> Stream { get; } + + /// + public IObservable> VersionedStream { get; } + + /// Gets the number of subscriptions made so far, to either stream. + internal int Subscriptions => Volatile.Read(ref _subscriptions); + + /// Gets the number of subscriptions that are still active. + internal int ActiveSubscriptions => Volatile.Read(ref _subscriptions) - Volatile.Read(ref _disposedSubscriptions); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T[] ToArray() => _inner.ToArray(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T[] CopyVersioned(out long version) => _versioned.CopyVersioned(out version); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _inner.Dispose(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator GetEnumerator() => _inner.GetEnumerator(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// Sets what runs once, right after the next subscription was made. + /// The action. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void AfterNextSubscribe(Action action) => Volatile.Write(ref _afterSubscribe, action); + + /// Subscribes to the wrapped plain stream. + /// The observer. + /// The subscription. + private IDisposable SubscribePlain(IObserver> observer) + { + _ = Interlocked.Increment(ref _subscriptions); + return Wrap(_inner.Stream.Subscribe(new Tap>(observer, this))); + } + + /// Subscribes to the wrapped versioned stream. + /// The observer. + /// The subscription. + private IDisposable SubscribeVersioned(IObserver> observer) + { + _ = Interlocked.Increment(ref _subscriptions); + return Wrap(_versioned.VersionedStream.Subscribe(new Tap>(observer, this))); + } + + /// Counts the disposal of a subscription and runs the pending hook, then waits until the subscriber has handled what the hook caused. + /// The wrapped subscription. + /// The subscription that counts its disposal. + private IDisposable Wrap(IDisposable inner) + { + if (Interlocked.Exchange(ref _afterSubscribe, null) is { } hook) + { + var before = Volatile.Read(ref _delivered); + hook(); + _ = SpinWait.SpinUntil(() => Volatile.Read(ref _delivered) > before, TimeSpan.FromSeconds(DeliveryTimeoutSeconds)); + } + + return Scope.Create((inner, this), static state => + { + state.inner.Dispose(); + _ = Interlocked.Increment(ref state.Item2._disposedSubscriptions); + }); + } + + /// Forwards values to the subscriber and counts each value once the subscriber has handled it. + /// The value type. + /// The subscriber. + /// The wrapper that counts deliveries. + private sealed class Tap(IObserver inner, LiveQueryVersionedSource owner) : IObserver + { + /// + public void OnNext(TValue value) + { + inner.OnNext(value); + _ = Interlocked.Increment(ref owner._delivered); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnError(Exception error) => inner.OnError(error); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted() => inner.OnCompleted(); + } +} diff --git a/src/tests/ReactiveList.Tests/LiveQueryWindowTests.cs b/src/tests/ReactiveList.Tests/LiveQueryWindowTests.cs new file mode 100644 index 00000000..b7381a6c --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveQueryWindowTests.cs @@ -0,0 +1,116 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks windows whose bounds change over time: when a change is applied, and that a change touches only the items that enter or leave. +public class LiveQueryWindowTests +{ + /// The number of rows the sources hold. + private const int RowTotal = 100; + + /// The number of items a page exposes. + private const int PageSize = TestData.TestValueTen; + + /// Sliding a window by one item over an ordered list removes the item that left and adds the item that entered, and nothing else. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedList_SlidingByOne_ChangesTwoItems() + { + using var list = new ReactiveList(CreateRows()); + var skip = new Signal(); + using var view = list.Live.OrderBy(static r => r.Rank).Skip(skip).Take(PageSize).ToView(Sequencer.Immediate, 0); + skip.OnNext(0); + await TestWaitHelpers.WaitUntilAsync(() => view.Select(static r => r.Id).SequenceEqual(Enumerable.Range(0, PageSize))); + var events = 0; + view.CollectionChanged += (_, _) => Interlocked.Increment(ref events); + + skip.OnNext(1); + + await TestWaitHelpers.WaitUntilAsync(() => view.Select(static r => r.Id).SequenceEqual(Enumerable.Range(1, PageSize))); + await Assert.That(Volatile.Read(ref events)).IsEqualTo(TestData.TestValueTwo); + } + + /// Sliding a window by half a page changes only the items that left and entered. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedList_SlidingByHalfAPage_ChangesOnlyTheDifference() + { + using var list = new ReactiveList(CreateRows()); + var skip = new Signal(); + using var view = list.Live.OrderBy(static r => r.Rank).Skip(skip).Take(PageSize).ToView(Sequencer.Immediate, 0); + skip.OnNext(0); + await TestWaitHelpers.WaitUntilAsync(() => view.Count == PageSize); + var events = 0; + view.CollectionChanged += (_, _) => Interlocked.Increment(ref events); + + skip.OnNext(PageSize / TestData.TestValueTwo); + + await TestWaitHelpers.WaitUntilAsync(() => view.Select(static r => r.Id).SequenceEqual(Enumerable.Range(PageSize / TestData.TestValueTwo, PageSize))); + await Assert.That(Volatile.Read(ref events)).IsEqualTo(PageSize); + } + + /// Items that are inserted into the window while it is shown keep the window consistent with the sequence. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedList_WindowSlidesAfterChanges_StayConsistent() + { + using var list = new ReactiveList(CreateRows()); + var skip = new Signal(); + using var view = list.Live.OrderBy(static r => r.Rank).Skip(skip).Take(PageSize).ToView(Sequencer.Immediate, 0); + skip.OnNext(TestData.TestValueFive); + list.RemoveAt(TestData.TestValueSeven); + list.Add(new(RowTotal, 0, 0)); + skip.OnNext(TestData.TestValueThree); + skip.OnNext(PageSize * TestData.TestValueTwo); + + await TestWaitHelpers.WaitUntilAsync(() => view.Select(static r => r.Id).SequenceEqual(Expected(list, PageSize * TestData.TestValueTwo))); + skip.OnNext(TestData.TestValueFour); + await TestWaitHelpers.WaitUntilAsync(() => view.Select(static r => r.Id).SequenceEqual(Expected(list, TestData.TestValueFour))); + } + + /// A window value that arrives while the view is still being created is applied without waiting for a source write. + /// A task representing the asynchronous test. + [Test] + public async Task WindowValue_ArrivingBeforeTheViewStarts_IsApplied() + { + using var list = new ReactiveList([new(0, 0, 0), new(1, 0, 1), new(TestData.TestValueTwo, 0, TestData.TestValueTwo)]); + var take = new Signal(); + var first = true; + + // The filter runs while the view is created, after the window was read and before the view listens for changes. + using var view = list.Live.Where(r => + { + if (first) + { + first = false; + take.OnNext(TestData.TestValueTwo); + } + + return r.Tag == 0; + }).OrderBy(static r => r.Rank).Take(take).ToView(Sequencer.Immediate, 0); + + await TestWaitHelpers.WaitUntilAsync(() => view.Select(static r => r.Id).SequenceEqual([0, 1])); + } + + /// Creates rows whose rank follows their identity. + /// The rows. + private static LiveQueryRow[] CreateRows() + { + var rows = new LiveQueryRow[RowTotal]; + for (var i = 0; i < rows.Length; i++) + { + rows[i] = new(i, 0, i); + } + + return rows; + } + + /// Computes the identities a page of the list shows, ordered by rank and then identity. + /// The list. + /// The number of items the page skips. + /// The identities. + private static int[] Expected(ReactiveList list, int skip) => + [.. list.ToArray().OrderBy(static r => r.Rank).ThenBy(static r => r.Id).Skip(skip).Take(PageSize).Select(static r => r.Id)]; +} diff --git a/src/tests/ReactiveList.Tests/LiveSequenceTests.cs b/src/tests/ReactiveList.Tests/LiveSequenceTests.cs new file mode 100644 index 00000000..7e79ed2e --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveSequenceTests.cs @@ -0,0 +1,97 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks how the sequence of included entries copes with entries that its bookkeeping no longer holds, and how entries compare. +public class LiveSequenceTests +{ + /// The binding every test uses: every item passes and is exposed as it is. + private static readonly LiveBinding Binding = new(Pass, EqualityComparer.Default, null); + + /// Removing an entry that is marked included but is not in the sequence only clears its mark. + /// A task representing the asynchronous test. + [Test] + public async Task Remove_EntryMissingFromTheSequence_ClearsTheMark() + { + var sequence = new LiveSequence(null, 0, -1, null); + var entry = Binding.CreateEntry(new(0, 0, 0)); + entry.Included = true; + + sequence.Remove(entry, 0); + + await Assert.That(entry.Included).IsFalse(); + await Assert.That(sequence.Target.Count).IsEqualTo(0); + } + + /// Replacing an entry that is marked included but is not in the sequence inserts the replacement. + /// A task representing the asynchronous test. + [Test] + public async Task Replace_EntryMissingFromTheSequence_InsertsTheReplacement() + { + var sequence = new LiveSequence(null, 0, -1, null); + var old = Binding.CreateEntry(new(0, 0, 0)); + old.Included = true; + var replacement = Binding.CreateEntry(new(1, 0, 0)); + _ = replacement.Evaluate(); + + sequence.Replace(old, replacement, 0, revalidate: false, replacementPasses: true); + + await Assert.That(old.Included).IsFalse(); + await Assert.That(replacement.Included).IsTrue(); + await Assert.That(sequence.Target.Select(static r => r.Id)).IsEquivalentTo([1], CollectionOrdering.Matching); + } + + /// Entries that name equal source items are equal and hash alike. + /// A task representing the asynchronous test. + [Test] + public async Task Entries_WithEqualSourceItems_AreEqualAndHashAlike() + { + var first = Binding.CreateEntry(new(0, 0, 0)); + var second = Binding.CreateEntry(new(0, 0, 0)); + var other = Binding.CreateEntry(new(1, 0, 0)); + + object? nothing = null; + var firstHash = first.GetHashCode(); + var secondHash = second.GetHashCode(); + + await Assert.That(first.Equals((object)second)).IsTrue(); + await Assert.That(first.Equals((object)other)).IsFalse(); + await Assert.That(first.Equals(nothing)).IsFalse(); + await Assert.That(firstHash).IsEqualTo(secondHash); + } + + /// Dictionary entries hash by key. + /// A task representing the asynchronous test. + [Test] + public async Task Entries_OfDictionaryItems_HashByKey() + { + var binding = new LiveBinding, KeyValuePair>(PassPair, LiveKeyValueComparer.Instance, null); + var first = binding.CreateEntry(new(1, 1)); + var second = binding.CreateEntry(new(1, 1)); + + await Assert.That(first.GetHashCode()).IsEqualTo(second.GetHashCode()); + await Assert.That(first.Equals(second)).IsTrue(); + } + + /// Exposes an item as it is. + /// The item. + /// Receives the item. + /// Always . + private static bool Pass(LiveQueryRow raw, out LiveQueryRow value) + { + value = raw; + return true; + } + + /// Exposes a dictionary entry as it is. + /// The entry. + /// Receives the entry. + /// Always . + private static bool PassPair(KeyValuePair raw, out KeyValuePair value) + { + value = raw; + return true; + } +} diff --git a/src/tests/ReactiveList.Tests/LiveTallySubscriptionTests.cs b/src/tests/ReactiveList.Tests/LiveTallySubscriptionTests.cs new file mode 100644 index 00000000..bd14dfbc --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveTallySubscriptionTests.cs @@ -0,0 +1,141 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks how counts and presence checks react to a source that fails, completes, is disposed or sends unusual notifications. +public class LiveTallySubscriptionTests +{ + /// A source that is disposed while the count subscribes completes the count. + /// A task representing the asynchronous test. + [Test] + public async Task Count_SourceDisposedWhileSubscribing_Completes() + { + var source = new LiveQueryScriptedSource([new(0, 0, 0)]) { DisposeOnSubscribe = true }; + var recorder = new LiveQueryRecorder(); + + using var subscription = source.Live.Count(static r => r.Tag == 0).Subscribe(recorder); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Completed); + } + + /// A source that fails ends the count with that failure. + /// A task representing the asynchronous test. + [Test] + public async Task Count_SourceFails_ReportsTheFailure() + { + var source = new LiveQueryScriptedSource([new(0, 0, 0)]); + var recorder = new LiveQueryRecorder(); + var failure = new InvalidOperationException("The source failed."); + using var subscription = source.Live.Count(static r => r.Tag == 0).Subscribe(recorder); + + source.Fail(failure); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Error is not null); + await Assert.That(recorder.Error).IsEqualTo(failure); + await Assert.That(recorder.Values).IsEquivalentTo([1], CollectionOrdering.Matching); + } + + /// A condition that throws ends the count with that failure. + /// A task representing the asynchronous test. + [Test] + public async Task Count_ConditionThrows_ReportsTheFailure() + { + var source = new LiveQueryScriptedSource([new(0, 0, 0)]); + var recorder = new LiveQueryRecorder(); + + using var subscription = source.Live.Count(static _ => throw new InvalidOperationException("The condition failed.")).Subscribe(recorder); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Error is not null); + await Assert.That(recorder.Error).IsTypeOf(); + } + + /// An observer that throws while the count completes does not break the subscription, and is told once. + /// A task representing the asynchronous test. + [Test] + public async Task Count_ObserverThrowsOnCompletion_IsToldOnce() + { + var source = new LiveQueryScriptedSource([new(0, 0, 0)]); + var completions = 0; + var observer = new LiveQueryActionObserver( + static _ => { }, + () => + { + _ = Interlocked.Increment(ref completions); + throw new InvalidOperationException("The observer failed."); + }); + using var subscription = source.Live.Count(static r => r.Tag == 0).Subscribe(observer); + + source.Complete(); + + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref completions) > 0); + await Assert.That(Volatile.Read(ref completions)).IsEqualTo(1); + } + + /// A change made while a value is being delivered is counted once delivery returns. + /// A task representing the asynchronous test. + [Test] + public async Task Count_ChangeDuringDelivery_IsCountedAfterwards() + { + var source = new LiveQueryScriptedSource([new(0, 0, 0)]); + var recorder = new LiveQueryRecorder(); + var added = 0; + var observer = new LiveQueryActionObserver( + value => + { + recorder.OnNext(value); + if (Interlocked.Exchange(ref added, 1) == 0) + { + source.Add(new(1, 0, 0)); + } + }, + static () => { }); + + using var subscription = source.Live.Count(static r => r.Tag == 0).Subscribe(observer); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Last == TestData.TestValueTwo); + await Assert.That(recorder.Values).IsEquivalentTo([1, TestData.TestValueTwo], CollectionOrdering.Matching); + } + + /// Notifications that do not describe the change exactly make the count read the source again. + /// A task representing the asynchronous test. + [Test] + public async Task Count_UnusualNotifications_RecountTheSource() + { + var source = new LiveQueryScriptedSource([new(0, 0, 0)]); + var recorder = new LiveQueryRecorder(); + using var subscription = source.Live.Count(static r => r.Tag == 0).Subscribe(recorder); + await TestWaitHelpers.WaitUntilAsync(() => recorder.Last == 1); + + source.AddWithoutNotification(new(1, 0, 0)); + source.Emit(new(CacheAction.Added, null)); + await TestWaitHelpers.WaitUntilAsync(() => recorder.Last == TestData.TestValueTwo); + + var third = new LiveQueryRow(TestData.TestValueTwo, 0, 0); + source.AddWithoutNotification(third); + source.Emit(new(CacheAction.Updated, third)); + await TestWaitHelpers.WaitUntilAsync(() => recorder.Last == TestData.TestValueThree); + + source.AddWithoutNotification(new(TestData.TestValueThree, 0, 0)); + source.Emit(new(CacheAction.BatchAdded, null)); + await TestWaitHelpers.WaitUntilAsync(() => recorder.Last == TestData.TestValueFour); + } + + /// An item that replaces itself after changing in place makes the count read the source again. + /// A task representing the asynchronous test. + [Test] + public async Task Count_ItemReplacingItself_RecountsTheSource() + { + var row = new LiveQueryRow(0, 0, 0); + var source = new LiveQueryScriptedSource([row]); + var recorder = new LiveQueryRecorder(); + using var subscription = source.Live.Count(static r => r.Tag == 0).Subscribe(recorder); + await TestWaitHelpers.WaitUntilAsync(() => recorder.Last == 1); + + row.Change(1, 0); + source.Emit(new(CacheAction.Updated, row, Previous: row)); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Last == 0); + } +} diff --git a/src/tests/ReactiveList.Tests/LiveViewFacadeTests.cs b/src/tests/ReactiveList.Tests/LiveViewFacadeTests.cs new file mode 100644 index 00000000..3c6bd052 --- /dev/null +++ b/src/tests/ReactiveList.Tests/LiveViewFacadeTests.cs @@ -0,0 +1,187 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks the members of the live views, whichever engine sits behind them. +public class LiveViewFacadeTests +{ + /// A view over an ordered list exposes its items, events, reset limit and refresh. + /// A task representing the asynchronous test. + [Test] + public async Task ListView_ExposesItsMembers() + { + using var list = new ReactiveList([new(0, 0, 0)]); + using var view = list.Live.ToView(Sequencer.Immediate, 0); + + await ExerciseAsync(view, () => list.Add(new(1, 1, 1))); + } + + /// A view over a sharded list with an ordering exposes its items, events, reset limit and refresh. + /// A task representing the asynchronous test. + [Test] + public async Task OrderedShardedView_ExposesItsMembers() + { + using var list = new QuaternaryList { new(0, 0, 0) }; + using var view = list.Live.OrderBy(static r => r.Rank).ToView(Sequencer.Immediate, 0); + + await ExerciseAsync(view, () => list.Add(new(1, 1, 1))); + } + + /// A plain filtered view over a sharded list exposes its items, events, reset limit and refresh. + /// A task representing the asynchronous test. + [Test] + public async Task FilteredShardedView_ExposesItsMembers() + { + using var list = new QuaternaryList { new(0, 0, 0) }; + using var view = list.Live.Where(static r => r.Tag >= 0).ToView(Sequencer.Immediate, 0); + + await ExerciseAsync(view, () => list.Add(new(1, 1, 1))); + } + + /// A view that projects an ordered query exposes its items, events, reset limit and refresh. + /// A task representing the asynchronous test. + [Test] + public async Task ProjectedView_ExposesItsMembers() + { + using var list = new ReactiveList([new(0, 0, 0)]); + using var view = list.Live.OrderBy(static r => r.Rank).Select(static r => r.Id).ToView(Sequencer.Immediate, 0); + + await ExerciseAsync(view, () => list.Add(new(1, 1, 1))); + } + + /// A grouped view exposes its groups, events, reset limit and refresh. + /// A task representing the asynchronous test. + [Test] + public async Task GroupView_ExposesItsMembers() + { + using var list = new ReactiveList([new(0, 0, 0)]); + using var view = list.Live.GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0); + var collectionEvents = 0; + var propertyEvents = 0; + NotifyCollectionChangedEventHandler onCollection = (_, _) => Interlocked.Increment(ref collectionEvents); + PropertyChangedEventHandler onProperty = (_, _) => Interlocked.Increment(ref propertyEvents); + view.CollectionChanged += onCollection; + view.PropertyChanged += onProperty; + + list.Add(new(1, 1, 1)); + + await TestWaitHelpers.WaitUntilAsync(() => view.Count == TestData.TestValueTwo && Volatile.Read(ref collectionEvents) > 0 && Volatile.Read(ref propertyEvents) > 0); + view.CollectionChanged -= onCollection; + view.PropertyChanged -= onProperty; + view.BatchResetLimit = TestData.TestValueFive; + await Assert.That(view.BatchResetLimit).IsEqualTo(TestData.TestValueFive); + await Assert.That(() => view.BatchResetLimit = -1).Throws(); + await Assert.That(view.Items).IsEqualTo(view.Groups); + await Assert.That(view.Keys.Order()).IsEquivalentTo([0, 1], CollectionOrdering.Matching); + await Assert.That(view.Values.Count()).IsEqualTo(TestData.TestValueTwo); + await Assert.That(view[1].Count).IsEqualTo(1); + await Assert.That(view[1][0].Id).IsEqualTo(1); + await Assert.That(view.ContainsKey(0)).IsTrue(); + await Assert.That(view.TryGetValue(TestData.TestValueNinetyNine, out var missing)).IsFalse(); + await Assert.That(missing.Count).IsEqualTo(0); + await Assert.That(() => view[TestData.TestValueNinetyNine]).Throws(); + await Assert.That(CountPairs(view)).IsEqualTo(TestData.TestValueTwo); + await Assert.That(CountObjects(view)).IsEqualTo(TestData.TestValueTwo); + await Assert.That(CountMembers(view[1])).IsEqualTo(1); + + view.Refresh(); + + await Assert.That(view.Count).IsEqualTo(TestData.TestValueTwo); + ReadOnlyObservableCollection>? assigned = null; + _ = view.ToProperty(groups => assigned = groups); + await Assert.That(assigned).IsEqualTo(view.Groups); + await Assert.That(view.ToProperty(out var collection)).IsEqualTo(view); + await Assert.That(collection).IsEqualTo(view.Groups); + } + + /// Disposing a grouped view over a list stops it from following the source. + /// A task representing the asynchronous test. + [Test] + public async Task GroupView_Disposed_StopsFollowingTheSource() + { + using var list = new ReactiveList([new(0, 0, 0)]); + var view = list.Live.GroupBy(static r => r.Tag).ToView(Sequencer.Immediate, 0); + view.Dispose(); + + view.Refresh(); + list.Add(new(1, 1, 1)); + + await Assert.That(view.Count).IsEqualTo(1); + } + + /// Counts the pairs a grouped view enumerates through its generic enumerator. + /// The view. + /// The number of pairs. + private static int CountPairs(LiveGroupView view) + { + var count = 0; + foreach (var unused in view) + { + _ = unused; + count++; + } + + return count; + } + + /// Counts the pairs a grouped view enumerates through its non-generic enumerator. + /// The view. + /// The number of pairs. + private static int CountObjects(IEnumerable view) + { + var count = 0; + foreach (var unused in view) + { + _ = unused; + count++; + } + + return count; + } + + /// Counts the members of a group through its non-generic enumerator. + /// The members. + /// The number of members. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int CountMembers(IReadOnlyList members) => CountObjects(members); + + /// Runs the shared checks of every live view against one mutation of its source. + /// The item type of the view. + /// The view. + /// Adds one item to the source. + /// A task that completes when the checks have run. + private static async Task ExerciseAsync(LiveView view, Action mutate) + where T : notnull + { + var collectionEvents = 0; + var propertyEvents = 0; + NotifyCollectionChangedEventHandler onCollection = (_, _) => Interlocked.Increment(ref collectionEvents); + PropertyChangedEventHandler onProperty = (_, _) => Interlocked.Increment(ref propertyEvents); + view.CollectionChanged += onCollection; + view.PropertyChanged += onProperty; + + mutate(); + + await TestWaitHelpers.WaitUntilAsync(() => view.Count == TestData.TestValueTwo && Volatile.Read(ref collectionEvents) > 0 && Volatile.Read(ref propertyEvents) > 0); + view.CollectionChanged -= onCollection; + view.PropertyChanged -= onProperty; + view.BatchResetLimit = TestData.TestValueFive; + await Assert.That(view.BatchResetLimit).IsEqualTo(TestData.TestValueFive); + await Assert.That(() => view.BatchResetLimit = -1).Throws(); + await Assert.That(view.Items.Count).IsEqualTo(TestData.TestValueTwo); + await Assert.That(view[0]).IsEqualTo(view.Items[0]); + await Assert.That(CountObjects(view)).IsEqualTo(TestData.TestValueTwo); + + view.Refresh(); + + await Assert.That(view.Count).IsEqualTo(TestData.TestValueTwo); + ReadOnlyObservableCollection? assigned = null; + _ = view.ToProperty(items => assigned = items); + await Assert.That(assigned).IsEqualTo(view.Items); + await Assert.That(view.ToProperty(out var collection)).IsEqualTo(view); + await Assert.That(collection).IsEqualTo(view.Items); + view.Dispose(); + } +} diff --git a/src/tests/ReactiveList.Tests/ManualObservable.cs b/src/tests/ReactiveList.Tests/ManualObservable.cs new file mode 100644 index 00000000..49001f22 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ManualObservable.cs @@ -0,0 +1,37 @@ +// 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. + +namespace ReactiveList.Tests; + +/// An observable the test drives by hand, which forwards every call to its observer without any terminal-state checks. +/// The element type. +internal sealed class ManualObservable : IObservable +{ + /// The most recent observer, or when nobody is subscribed. + private IObserver? _observer; + + /// Gets a value indicating whether an observer is subscribed. + internal bool HasObserver => Volatile.Read(ref _observer) is not null; + + /// + public IDisposable Subscribe(IObserver observer) + { + Volatile.Write(ref _observer, observer); + return Scope.Create(this, static self => Volatile.Write(ref self._observer, null)); + } + + /// Sends a value to the observer. + /// The value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void Emit(T value) => Volatile.Read(ref _observer)?.OnNext(value); + + /// Sends a failure to the observer. + /// The failure. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void Fail(Exception error) => Volatile.Read(ref _observer)?.OnError(error); + + /// Sends completion to the observer. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void Complete() => Volatile.Read(ref _observer)?.OnCompleted(); +} diff --git a/src/tests/ReactiveList.Tests/MirrorRemovalTests.cs b/src/tests/ReactiveList.Tests/MirrorRemovalTests.cs new file mode 100644 index 00000000..346e053d --- /dev/null +++ b/src/tests/ReactiveList.Tests/MirrorRemovalTests.cs @@ -0,0 +1,82 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks how finds and removes batch items from a mirror. +public class MirrorRemovalTests +{ + /// The number of items removed by the compaction test. + private const int Two = 2; + + /// Finding with repeat tracking reports an item that also occurs later in the mirror. + /// A task representing the asynchronous test. + [Test] + public async Task Find_TrackRepeats_ReportsRepeatedItem() + { + List items = ["a", "b", "a"]; + using var batch = Batch("a"); + var removedAt = new int[1]; + + var found = MirrorRemoval.Find(items, batch, trackRepeats: true, removedAt, out var repeated); + + await Assert.That(found).IsEqualTo(1); + await Assert.That(removedAt[0]).IsEqualTo(0); + await Assert.That(repeated).IsTrue(); + } + + /// Finding with repeat tracking reports no repeat when every found item is unique. + /// A task representing the asynchronous test. + [Test] + public async Task Find_TrackRepeats_UniqueItems_ReportsNoRepeat() + { + List items = ["a", "b"]; + using var batch = Batch("b"); + var removedAt = new int[1]; + + var found = MirrorRemoval.Find(items, batch, trackRepeats: true, removedAt, out var repeated); + + await Assert.That(found).IsEqualTo(1); + await Assert.That(repeated).IsFalse(); + } + + /// Finding without repeat tracking stops once every batch item was found. + /// A task representing the asynchronous test. + [Test] + public async Task Find_WithoutTracking_StopsWhenBatchIsFound() + { + List items = ["a", "a"]; + using var batch = Batch("a"); + var removedAt = new int[1]; + + var found = MirrorRemoval.Find(items, batch, trackRepeats: false, removedAt, out var repeated); + + await Assert.That(found).IsEqualTo(1); + await Assert.That(repeated).IsFalse(); + } + + /// Compacting removes the listed indices and returns the removed items in order. + /// A task representing the asynchronous test. + [Test] + public async Task Compact_RemovesIndicesAndReturnsRemovedItems() + { + List items = ["a", "b", "c"]; + int[] removedAt = [0, Two]; + + var removed = MirrorRemoval.Compact(items, removedAt, Two); + + await Assert.That(removed).IsEquivalentTo(["a", "c"], CollectionOrdering.Matching); + await Assert.That(items).IsEquivalentTo(["b"], CollectionOrdering.Matching); + } + + /// Creates a one-item batch backed by a pooled array. + /// The item. + /// The batch, which returns its array when disposed. + private static PooledBatch Batch(string item) + { + var array = ArrayPool.Shared.Rent(1); + array[0] = item; + return new(array, 1); + } +} diff --git a/src/tests/ReactiveList.Tests/MutableValue.cs b/src/tests/ReactiveList.Tests/MutableValue.cs new file mode 100644 index 00000000..c2687e49 --- /dev/null +++ b/src/tests/ReactiveList.Tests/MutableValue.cs @@ -0,0 +1,27 @@ +// 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. + +namespace ReactiveList.Tests; + +/// A reference item whose value can change after it was added to a list. +/// The initial value. +internal sealed class MutableValue(int value) : IComparable +{ + /// Gets or sets the value used for ordering and filtering. + internal int Value { get; set; } = value; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int CompareTo(MutableValue? other) => other is null ? 1 : Value.CompareTo(other.Value); + + /// Gets a comparer that orders items by value. + /// The comparer. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static IComparer ByValue() => Comparer.Create(static (left, right) => left.CompareTo(right)); + + /// Reads the values of a sequence. + /// The items. + /// The values in order. + internal static int[] Values(IEnumerable items) => [.. items.Select(static item => item.Value)]; +} diff --git a/src/tests/ReactiveList.Tests/NotificationDeferralTests.cs b/src/tests/ReactiveList.Tests/NotificationDeferralTests.cs new file mode 100644 index 00000000..65005829 --- /dev/null +++ b/src/tests/ReactiveList.Tests/NotificationDeferralTests.cs @@ -0,0 +1,168 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks the replay and lifetime of collection-wide notification deferrals. +public class NotificationDeferralTests +{ + /// Copied and nested tokens release one reset even when disposed out of order. + /// A task representing the asynchronous test. + [Test] + public async Task List_NestedAndCopiedTokens_PublishOneReset() + { + const int retained = TestData.TestValueTwo; + const int replacement = TestData.TestValueThree; + using ReactiveList source = [1, retained]; + using var view = new ReactiveView(source.Stream, source.ToArray(), static _ => true, TimeSpan.Zero, Sequencer.Immediate); + var mirror = source.Items; + var stream = new LiveQueryRecorder>(); + using var subscription = source.Stream.Subscribe(stream); + var actions = new List(); + source.CollectionChanged += (_, args) => actions.Add(args.Action); + var first = source.DeferNotifications(); + var copy = first; + var last = source.DeferNotifications(); + + source.RemoveAt(0); + source.Insert(0, replacement); + first.Dispose(); + copy.Dispose(); + + await Assert.That(source.ToArray()).IsEquivalentTo([replacement, retained], CollectionOrdering.Matching); + await Assert.That(mirror.ToArray()).IsEquivalentTo([1, retained], CollectionOrdering.Matching); + await Assert.That(stream.Values).IsEmpty(); + await Assert.That(actions).IsEmpty(); + + last.Dispose(); + + var reset = stream.Values.Single(); + await Assert.That(reset.Action).IsEqualTo(CacheAction.Reset); + await Assert.That(reset.Batch!.Items).IsEquivalentTo([replacement, retained], CollectionOrdering.Matching); + await Assert.That(mirror.ToArray()).IsEquivalentTo([replacement, retained], CollectionOrdering.Matching); + await Assert.That(view.Items.ToArray()).IsEquivalentTo([replacement, retained], CollectionOrdering.Matching); + await Assert.That(actions).IsEquivalentTo([NotifyCollectionChangedAction.Reset]); + await Assert.That(source.ItemsAdded.ToArray()).IsEquivalentTo([replacement]); + await Assert.That(source.ItemsRemoved.ToArray()).IsEquivalentTo([1]); + } + + /// An empty reset is retained by filtered views and maps to a clear change. + /// A task representing the asynchronous test. + [Test] + public async Task List_ClearDuringDeferral_UpdatesFilteredAndChangeSetObservers() + { + using ReactiveList source = [TestData.TestValueTwo]; + using var view = new ReactiveView(source.Stream, source.ToArray(), static value => (value & 1) == 0, TimeSpan.Zero, Sequencer.Immediate); + var changes = new LiveQueryRecorder>(); + using var subscription = source.Stream.ToChangeSets().Subscribe(changes); + using (source.DeferNotifications()) + { + source.Clear(); + } + + var reset = changes.Values.Single(); + await Assert.That(reset.Count).IsEqualTo(1); + await Assert.That(reset[0].Reason).IsEqualTo(ChangeReason.Clear); + await Assert.That(view.Items.ToArray()).IsEmpty(); + } + + /// Starting and releasing a scope without changing the list emits nothing. + /// A task representing the asynchronous test. + [Test] + public async Task List_EmptyScopeAndDefaultToken_PublishNothing() + { + using ReactiveList source = [1, TestData.TestValueTwo]; + var recorder = new LiveQueryRecorder>(); + using var subscription = source.Stream.Subscribe(recorder); + var scope = source.DeferNotifications(); + scope.Dispose(); + default(NotificationDeferral).Dispose(); + + await Assert.That(recorder.Values).IsEmpty(); + } + + /// Disposal cancels the pending reset without losing stream completion. + /// A task representing the asynchronous test. + [Test] + public async Task List_DisposeWithOpenDeferral_CompletesWithoutReset() + { + ReactiveList source = []; + var recorder = new LiveQueryRecorder>(); + using var subscription = source.Stream.Subscribe(recorder); + var scope = source.DeferNotifications(); + source.Add(1); + source.Dispose(); + scope.Dispose(); + + await Assert.That(recorder.Completed).IsTrue(); + await Assert.That(recorder.Values).IsEmpty(); + } + + /// Concurrent shard writes publish one reset followed by ordinary notifications. + /// A task representing the asynchronous test. + [Test] + public async Task ShardedList_ConcurrentNestedScopes_PublishOneOrderedReset() + { + const int writeCount = 32; + using QuaternaryList source = []; + var recorder = new LiveQueryRecorder>(); + using var subscription = source.VersionedStream.Subscribe(recorder); + using (source.DeferNotifications()) + { + await Parallel.ForAsync(0, writeCount, (item, _) => + { + using var inner = source.DeferNotifications(); + source.Add(item); + return ValueTask.CompletedTask; + }); + + await Assert.That(source.Count).IsEqualTo(writeCount); + await Assert.That(recorder.Values).IsEmpty(); + } + + source.Add(writeCount); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Values.Length > 1); + var notifications = recorder.Values; + await Assert.That(notifications.Select(static value => value.Notification.Action).ToArray()) + .IsEquivalentTo([CacheAction.Reset, CacheAction.Added], CollectionOrdering.Matching); + await Assert.That(notifications[0].Notification.Batch!.Items).IsEquivalentTo(Enumerable.Range(0, writeCount).ToArray()); + await Assert.That(notifications[1].Version).IsGreaterThan(notifications[0].Version); + } + + /// A dictionary reset covers upsert and removal while keeping its live query and property events consistent. + /// A task representing the asynchronous test. + [Test] + public async Task ShardedDictionary_MixedWrites_ResetsLiveQueryAndNotifiesPropertiesOnce() + { + const int keyToRemove = 2; + const int keyToAdd = 3; + const int initialValue = 10; + const int updatedValue = 100; + using QuaternaryDictionary source = []; + source.Add(1, initialValue); + source.Add(keyToRemove, initialValue); + var messages = new LiveQueryRecorder>>(); + var values = new LiveQueryRecorder>(); + using var subscription = source.Stream.Subscribe(messages); + using var observer = source.Live.ObserveValue(1).Subscribe(values); + var properties = new List(); + source.PropertyChanged += (_, args) => properties.Add(args.PropertyName ?? string.Empty); + + using (source.DeferNotifications()) + { + source.AddOrUpdate(1, updatedValue); + source.RemoveKeys([keyToRemove]); + source.Add(keyToAdd, initialValue); + await Assert.That(properties).IsEmpty(); + await Assert.That(values.Last.Value).IsEqualTo(initialValue); + } + + await TestWaitHelpers.WaitUntilAsync(() => messages.Values.Length != 0 && values.Last.Value == updatedValue); + var reset = messages.Values.Single(); + await Assert.That(reset.Action).IsEqualTo(CacheAction.Reset); + await Assert.That(reset.Batch!.Items).IsEquivalentTo(source.ToArray()); + await Assert.That(properties).IsEquivalentTo(["Count", "Item[]"], CollectionOrdering.Matching); + } +} diff --git a/src/tests/ReactiveList.Tests/ObservableFromEventPatternTests.cs b/src/tests/ReactiveList.Tests/ObservableFromEventPatternTests.cs new file mode 100644 index 00000000..a010d245 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ObservableFromEventPatternTests.cs @@ -0,0 +1,47 @@ +// 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 +using InternalObservable = ReactiveList.Reactive.Internal.Observable; +#else +using InternalObservable = ReactiveList.Internal.Observable; +#endif + +namespace ReactiveList.Tests; + +/// Checks that the internal FromEventPattern adapts a property-changed event. +public class ObservableFromEventPatternTests +{ + /// A property-changed event is delivered with its sender and arguments, and unsubscribing detaches the handler. + /// A task representing the asynchronous test. + [Test] + public async Task FromEventPattern_PropertyChanged_DeliversEventsUntilDisposed() + { + PropertySource source = new(); + List names = []; + var subscription = InternalObservable + .FromEventPattern( + handler => source.PropertyChanged += handler, + handler => source.PropertyChanged -= handler) + .Subscribe(pattern => names.Add(pattern.EventArgs.PropertyName!)); + + source.Raise("First"); + subscription.Dispose(); + source.Raise("Second"); + + await Assert.That(names).IsEquivalentTo(["First"], CollectionOrdering.Matching); + } + + /// A source that raises property-changed events. + private sealed class PropertySource : INotifyPropertyChanged + { + /// + public event PropertyChangedEventHandler? PropertyChanged; + + /// Raises the event. + /// The property name. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Raise(string name) => PropertyChanged?.Invoke(this, new(name)); + } +} diff --git a/src/tests/ReactiveList.Tests/PendingNotificationQueueTests.cs b/src/tests/ReactiveList.Tests/PendingNotificationQueueTests.cs new file mode 100644 index 00000000..58ec8c3e --- /dev/null +++ b/src/tests/ReactiveList.Tests/PendingNotificationQueueTests.cs @@ -0,0 +1,53 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies against a queue that is missing, empty or filled. +public sealed class PendingNotificationQueueTests +{ + /// The revision of the first queued notification. + private const long FirstVersion = 4; + + /// The revision of the second queued notification. + private const long SecondVersion = 5; + + /// The count the caller read before the queue was emptied. + private const int StaleCount = 3; + + /// Verifies a missing or empty queue yields nothing and leaves the published count alone. + /// Whether the queue exists. + /// A task representing the asynchronous test. + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task TryDequeue_MissingOrEmptyQueue_ReturnsFalse(bool hasQueue) + { + Queue>? queue = hasQueue ? new() : null; + var count = StaleCount; + + var taken = PendingNotificationQueue.TryDequeue(queue, ref count, out var next); + + await Assert.That(taken).IsFalse(); + await Assert.That(next).IsEqualTo(default(PendingNotification)); + await Assert.That(count).IsEqualTo(StaleCount); + } + + /// Verifies the oldest notification is taken and the remaining count is published. + /// A task representing the asynchronous test. + [Test] + public async Task TryDequeue_FilledQueue_TakesTheOldestAndPublishesTheCount() + { + Queue> queue = new(); + queue.Enqueue(new(new(CacheAction.Added, 1), FirstVersion)); + queue.Enqueue(new(new(CacheAction.Added, 1), SecondVersion)); + var count = queue.Count; + + var taken = PendingNotificationQueue.TryDequeue(queue, ref count, out var next); + + await Assert.That(taken).IsTrue(); + await Assert.That(next.Version).IsEqualTo(FirstVersion); + await Assert.That(count).IsEqualTo(1); + } +} diff --git a/src/tests/ReactiveList.Tests/QuaternaryCollectionCoverageTests.cs b/src/tests/ReactiveList.Tests/QuaternaryCollectionCoverageTests.cs index f1a25c92..52e8e269 100644 --- a/src/tests/ReactiveList.Tests/QuaternaryCollectionCoverageTests.cs +++ b/src/tests/ReactiveList.Tests/QuaternaryCollectionCoverageTests.cs @@ -4,13 +4,10 @@ #if NET8_0_OR_GREATER || NETFRAMEWORK -using System.Reflection; -using System.Threading.Channels; - namespace ReactiveList.Tests; /// Covers quaternary list, dictionary, and base notification paths that are not reached by the public API tests. -public class QuaternaryCollectionCoverageTests +public sealed class QuaternaryCollectionCoverageTests { /// The second collection value used by test data. private const int CollectionValueTwo = 2; @@ -42,9 +39,6 @@ public class QuaternaryCollectionCoverageTests /// The value used by replacement tests. private const int ReplacementValue = 42; - /// The interval used when polling the event processor. - private const int ProcessorPollMilliseconds = 50; - /// A value deliberately absent from test collections. private const int MissingCollectionValue = 99; @@ -293,10 +287,10 @@ public async Task QuaternaryList_SnapshotAndInvalidIndexes_ShouldBehaveAsExpecte list.Dispose(); } - /// Verifies QuaternaryBase dispatches legacy collection changes through a captured synchronization context. + /// Verifies the list dispatches legacy collection changes through a captured synchronization context. /// A task representing the asynchronous test. [Test] - public async Task QuaternaryBase_CollectionChanged_ShouldUseCapturedSynchronizationContext() + public async Task List_CollectionChanged_ShouldUseCapturedSynchronizationContext() { var previousContext = SynchronizationContext.Current; var context = new ImmediateSynchronizationContext(); @@ -514,135 +508,92 @@ public async Task QuaternaryDictionary_GuardsAndCollectionChanged_ShouldBehaveAs await Assert.That(action).IsEqualTo(NotifyCollectionChangedAction.Reset); } - /// Verifies protected QuaternaryBase batch helpers and null guard paths through a minimal harness. + /// Verifies that batch operations publish their cache actions and that null arguments are rejected by name. /// A task representing the asynchronous test. [Test] - public async Task QuaternaryBase_BatchHelpers_ShouldEmitAndValidateArguments() + public async Task List_BatchOperations_ShouldPublishAndValidateArguments() { - using var harness = new QuaternaryBaseHarness(); + using var list = new QuaternaryList(); var received = new List>(); - using var subscription = harness.Stream.Subscribe(received.Add); + using var subscription = list.Stream.Subscribe(received.Add); - harness.EmitDirect([1, CollectionValueTwo]); - harness.EmitAddedFromList([CollectionValueThree, CollectionValueFour]); - harness.EmitRemovedFromList([CollectionValueFive, CollectionValueSix]); - await Assert.That(SpinWait.SpinUntil(() => received.Count >= 3, TimeSpan.FromSeconds(CollectionValueTwo))).IsTrue(); + list.AddRange([1, CollectionValueTwo]); + list.RemoveRange([1, CollectionValueTwo]); + list.Edit(static editor => editor.Add(CollectionValueThree)); + await TestWaitHelpers.WaitUntilAsync(() => received.Count >= CollectionValueThree); - await Assert.That(ExtractActions(received)).IsEquivalentTo([CacheAction.BatchOperation, CacheAction.BatchAdded, CacheAction.BatchRemoved], CollectionOrdering.Matching); - await Assert.That(ExtractBatchCounts(received)).IsEquivalentTo([CollectionValueTwo, CollectionValueTwo, CollectionValueTwo], CollectionOrdering.Matching); + await Assert.That(ExtractActions(received)).IsEquivalentTo([CacheAction.BatchAdded, CacheAction.BatchRemoved, CacheAction.BatchOperation], CollectionOrdering.Matching); - Action nullAdded = () => harness.EmitAddedFromList(null!); - Action nullRemoved = () => harness.EmitRemovedFromList(null!); + await Assert.That(ExtractBatchCounts(received.GetRange(0, CollectionValueTwo))).IsEquivalentTo([CollectionValueTwo, CollectionValueTwo], CollectionOrdering.Matching); - await Assert.That(nullAdded).Throws().WithParameterName("items"); - await Assert.That(nullRemoved).Throws().WithParameterName("items"); + Action nullAdded = () => list.AddRange(null!); + Action nullRemoved = () => list.RemoveRange(null!); - foreach (var notification in received) - { - notification.Batch!.Dispose(); - } + await Assert.That(nullAdded).Throws().WithParameterName("collection"); + await Assert.That(nullRemoved).Throws().WithParameterName("collection"); } - /// Verifies QuaternaryBase no-observer fast paths and legacy collection changed mappings. + /// Verifies the no-observer fast paths and that every legacy collection change is reported as a reset. /// A task representing the asynchronous test. [Test] - public async Task QuaternaryBase_NoObserverAndLegacyCollectionChangedBranches_ShouldExecute() + public async Task List_NoObserverAndLegacyCollectionChangedBranches_ShouldExecute() { - using var noObserverHarness = new QuaternaryBaseHarness(); + using var noObserverList = new QuaternaryList(); NotifyCollectionChangedEventHandler? nullHandler = null; - noObserverHarness.CollectionChanged += nullHandler; - noObserverHarness.CollectionChanged -= nullHandler; + noObserverList.CollectionChanged += nullHandler; + noObserverList.CollectionChanged -= nullHandler; - noObserverHarness.EmitDirect([1, CollectionValueTwo]); - noObserverHarness.EmitOwnedRemoved([CollectionValueThree, CollectionValueFour]); - noObserverHarness.EmitRemovedFromList([CollectionValueFive, CollectionValueSix]); + noObserverList.AddRange([1, CollectionValueTwo]); + noObserverList.RemoveRange([1, CollectionValueTwo]); + noObserverList.Clear(); - using var harness = new QuaternaryBaseHarness(); + using var list = new QuaternaryList(); var actions = new List(); - harness.CollectionChanged += (_, args) => actions.Add(args.Action); + list.CollectionChanged += (_, args) => actions.Add(args.Action); - harness.EmitDirect([1, CollectionValueTwo]); - harness.EmitSingle(CacheAction.Added, CollectionValueThree); - harness.EmitSingle(CacheAction.Removed, CollectionValueFour); - harness.EmitSingle(CacheAction.Moved, CollectionValueFive); + list.AddRange([1, CollectionValueTwo]); + list.Add(CollectionValueThree); + _ = list.Remove(CollectionValueThree); + list.Clear(); - await Assert.That(SpinWait.SpinUntil(() => actions.Count >= 4, TimeSpan.FromSeconds(CollectionValueTwo))).IsTrue(); + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref actions).Count >= CollectionValueFour); NotifyCollectionChangedAction[] expectedActions = [NotifyCollectionChangedAction.Reset, NotifyCollectionChangedAction.Reset, NotifyCollectionChangedAction.Reset, NotifyCollectionChangedAction.Reset]; await Assert.That(actions).IsEquivalentTo(expectedActions, CollectionOrdering.Matching); } - /// Verifies private event processor edge cases that have no stable public timing path. + /// Verifies that changing without observers, after disposal, and while the processor starts concurrently behaves correctly. /// A task representing the asynchronous unit test. - /// Thrown when processEvents.Invoke(nullStateHarness, null) is . [Test] - public async Task QuaternaryBase_PrivateEventProcessorEdges_ShouldExecute() + public async Task List_EventProcessorEdges_ShouldExecute() { - var baseType = typeof(QuaternaryBase); - var processEvents = FindInstanceMethod(baseType, "ProcessEventsAsync"); - var ensureStarted = FindInstanceMethod(baseType, "EnsureEventProcessorStarted"); - - using (var nullStateHarness = new QuaternaryBaseHarness()) - { - await (Task)(processEvents.Invoke(nullStateHarness, null) - ?? throw new InvalidOperationException("The event processor did not return a task.")); - } - - using (var completedReaderHarness = new QuaternaryBaseHarness()) + using (var unobservedList = new QuaternaryList()) { - var completedChannel = Channel.CreateUnbounded>(); - completedChannel.Writer.Complete(); - SetPrivateField(completedReaderHarness, "_eventChannel", completedChannel); - SetPrivateField(completedReaderHarness, "_pipeline", new Signal>()); - SetPrivateField(completedReaderHarness, "_cts", new CancellationTokenSource()); - - await (Task)(processEvents.Invoke(completedReaderHarness, null) - ?? throw new InvalidOperationException("The event processor did not return a task.")); + unobservedList.AddRange([1, CollectionValueTwo]); + await Assert.That(unobservedList.Version).IsGreaterThan(0L); } - using (var failedWriteHarness = new QuaternaryBaseHarness()) - { - var completedChannel = Channel.CreateUnbounded>(); - completedChannel.Writer.Complete(); - SetPrivateField(failedWriteHarness, "_eventProcessorStarted", 1); - SetPrivateField(failedWriteHarness, "_hasSubscribers", 1); - SetPrivateField(failedWriteHarness, "_eventChannel", completedChannel); - SetPrivateField(failedWriteHarness, "_pipeline", new Signal>()); - SetPrivateField(failedWriteHarness, "_cts", new CancellationTokenSource()); - - failedWriteHarness.EmitDirect([1, CollectionValueTwo]); - } + var disposedList = new QuaternaryList(); + var actions = new List(); + disposedList.Dispose(); + disposedList.CollectionChanged += (_, args) => actions.Add(args.Action); + Action addToDisposed = () => disposedList.Add(1); - using (var nullHandlerHarness = new QuaternaryBaseHarness()) - { - _ = InvokePrivate( - nullHandlerHarness, - "InvokeLegacyINCC", - new CacheNotify(CacheAction.BatchAdded, default, CreateBatch(1, CollectionValueTwo))); - } + await Assert.That(addToDisposed).Throws(); + await Assert.That(actions).IsEmpty(); - using (var legacyHarness = new QuaternaryBaseHarness()) + using var startedRaceList = new QuaternaryList(); + var handled = 0; + var subscribers = new Task[CollectionValueFive]; + for (var i = 0; i < subscribers.Length; i++) { - var actions = new List(); - legacyHarness.CollectionChanged += (_, args) => actions.Add(args.Action); - - _ = InvokePrivate(legacyHarness, "InvokeLegacyINCC", new CacheNotify(CacheAction.Cleared, default)); - - await Assert.That(actions).Contains(NotifyCollectionChangedAction.Reset); + subscribers[i] = Task.Run(() => startedRaceList.CollectionChanged += (_, _) => Interlocked.Increment(ref handled)); } - using var startedRaceHarness = new QuaternaryBaseHarness(); - var gate = startedRaceHarness.GetOrCreateEventGate(); - - Task ensureTask; - lock (gate) - { - ensureTask = Task.Run(() => ensureStarted.Invoke(startedRaceHarness, null)); - _ = SpinWait.SpinUntil(() => ensureTask.IsCompleted, TimeSpan.FromMilliseconds(ProcessorPollMilliseconds)); - SetPrivateField(startedRaceHarness, "_eventProcessorStarted", 1); - } + await Task.WhenAll(subscribers); + startedRaceList.Add(CollectionValueThree); - await ensureTask; + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref handled) == subscribers.Length); } /// Captures editor results before the synchronous edit scope closes. @@ -856,71 +807,6 @@ private static IEnumerable Yield(params T[] items) } } - /// Provides CreateBatch. - /// The values value. - /// The result. - private static PooledBatch CreateBatch(params int[] values) - { - var array = ArrayPool.Shared.Rent(Math.Max(1, values.Length)); - Array.Copy(values, array, values.Length); - return new(array, values.Length); - } - - /// Provides InvokePrivate. - /// The target value. - /// The methodName value. - /// The args value. - /// The result. - /// Thrown when target.GetType().BaseType is . - private static object? InvokePrivate(object target, string methodName, params object?[] args) - { - var baseType = target.GetType().BaseType ?? throw new InvalidOperationException("The test harness has no base type."); - var method = FindInstanceMethod(baseType, methodName); - return method.Invoke(target, args); - } - - /// Finds an instance method, including an internal implementation detail required by the coverage harness. - /// The type to inspect. - /// The required method name. - /// The matching instance method. - /// Thrown when the requested method cannot be found. - private static MethodInfo FindInstanceMethod(Type type, string methodName) - { - foreach (var method in type.GetRuntimeMethods()) - { - if (!method.IsStatic && method.Name == methodName) - { - return method; - } - } - - throw new MissingMethodException(type.FullName, methodName); - } - - /// Provides SetPrivateField. - /// The target value. - /// The fieldName value. - /// The value. - /// Thrown when the requested field cannot be found. - private static void SetPrivateField(object target, string fieldName, object? value) - { - for (var type = target.GetType(); type is not null; type = type.BaseType) - { - foreach (var field in type.GetRuntimeFields()) - { - if (field.IsStatic || field.Name != fieldName) - { - continue; - } - - field.SetValue(target, value); - return; - } - } - - throw new MissingFieldException(target.GetType().FullName, fieldName); - } - /// Stores editor observations until they can be asserted asynchronously. private sealed class DictionaryEditorSnapshot { @@ -1028,40 +914,5 @@ private sealed class ConstantShardKey : IEquatable public override int GetHashCode() => 0; } - - /// Provides QuaternaryBaseHarness. - private sealed class QuaternaryBaseHarness : QuaternaryBase - { - protected override IReadOnlyList> BaseQuads { get; } = - [ - new QuadList(), - new QuadList(), - new QuadList(), - new QuadList() - ]; - - /// Provides EmitDirect. - /// The items value. - public void EmitDirect(int[] items) => EmitBatchDirect(items, items.Length); - - /// Provides EmitAddedFromList. - /// The items value. - public void EmitAddedFromList(IList items) => EmitBatchAddedFromList(items, items?.Count ?? 0); - - /// Provides EmitRemovedFromList. - /// The items value. - public void EmitRemovedFromList(IList items) => EmitBatchRemovedFromList(items, items?.Count ?? 0); - - /// Provides EmitOwnedRemoved. - /// The items value. - public void EmitOwnedRemoved(int[] items) => EmitOwnedBatchRemoved(items, items.Length); - - /// Provides EmitSingle. - /// The action value. - /// The item value. - public void EmitSingle(CacheAction action, int item) => Emit(action, item); - - public override IEnumerator GetEnumerator() => ((IEnumerable)Array.Empty()).GetEnumerator(); - } } #endif diff --git a/src/tests/ReactiveList.Tests/QuaternaryConcurrencyFuzzTests.cs b/src/tests/ReactiveList.Tests/QuaternaryConcurrencyFuzzTests.cs new file mode 100644 index 00000000..44e30956 --- /dev/null +++ b/src/tests/ReactiveList.Tests/QuaternaryConcurrencyFuzzTests.cs @@ -0,0 +1,223 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Stresses the quaternary collections from many threads and checks linearizability and quiescent consistency. +public sealed class QuaternaryConcurrencyFuzzTests +{ + /// The number of seeds each stress test tries. + private const int SeedCount = 4; + + /// The number of rounds of the racing index tests. + private const int RaceRounds = 20; + + /// The highest item identity the linearizability generators produce. + private const int ParallelItemMax = 5; + + /// The longest initial item list the linearizability generators produce. + private const int ParallelInitialMax = 6; + + /// The number of linearizability iterations. + private const int ParallelIterations = 60; + + /// The seed multiplier of the list replay test. + private const int ListReplaySeedFactor = 7_919; + + /// The seed multiplier of the dictionary replay test. + private const int DictionaryReplaySeedFactor = 104_729; + + /// The number of items each racing adder adds. + private const int AddsPerRacer = 500; + + /// The spacing between the item identities of different racers. + private const int RacerSpacing = 1000; + + /// The number of operations each clear racer performs. + private const int ClearRaceOperations = 400; + + /// How often the clearing racer clears instead of adding. + private const int ClearEvery = 25; + + /// Verifies that parallel list operations are linearizable. + /// A task representing the asynchronous test. + [Test] + public Task List_ParallelOperations_AreLinearizable() + { + var item = Gen.Int[0, ParallelItemMax]; + Check.SampleParallel( + item.List[0, ParallelInitialMax].Select(static items => + { + var list = new QuaternaryList(); + list.AddRange(items); + return list; + }), + item.Operation>(static (list, i) => list.Add(i)), + item.Operation>(static (list, i) => _ = list.Remove(i)), + item.Operation>(static (list, i) => list.AddRange([i, i + 1])), + ConcurrencyFuzzHelpers.SameListContents, + iter: ParallelIterations, + print: static list => string.Join(",", list.ToArray())); + return Task.CompletedTask; + } + + /// Verifies that parallel dictionary operations are linearizable. + /// A task representing the asynchronous test. + [Test] + public Task Dictionary_ParallelOperations_AreLinearizable() + { + var item = Gen.Int[0, ParallelItemMax]; + Check.SampleParallel( + item.List[0, ParallelInitialMax].Select(static items => + { + var dictionary = new QuaternaryDictionary(); + foreach (var i in items) + { + dictionary[i] = i; + } + + return dictionary; + }), + item.Operation>(static (dictionary, i) => dictionary.AddOrUpdate(i, i + i)), + item.Operation>(static (dictionary, i) => _ = dictionary.Remove(i)), + item.Operation>(static (dictionary, i) => _ = dictionary.TryAdd(i, i)), + ConcurrencyFuzzHelpers.SameDictionaryContents, + iter: ParallelIterations, + print: static dictionary => string.Join(",", dictionary.Select(static p => $"{p.Key}={p.Value}"))); + return Task.CompletedTask; + } + + /// Verifies list consistency at quiescence after a mixed multi-threaded workload. + /// A task representing the asynchronous test. + [Test] + public async Task List_MixedWorkload_StaysConsistent() + { + for (var seed = 1; seed <= SeedCount; seed++) + { + await new ListStressWorkload(seed).RunAsync().ConfigureAwait(false); + } + } + + /// Verifies dictionary consistency at quiescence after a mixed multi-threaded workload. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_MixedWorkload_StaysConsistent() + { + for (var seed = 1; seed <= SeedCount; seed++) + { + await new DictionaryStressWorkload(seed).RunAsync().ConfigureAwait(false); + } + } + + /// Verifies that a stream replaying notifications always ends equal to the list, so notifications keep mutation order. + /// A task representing the asynchronous test. + [Test] + public async Task List_StreamReplay_MatchesListAfterConflictingWrites() + { + for (var seed = 1; seed <= SeedCount; seed++) + { + using var list = new QuaternaryList(); + var replica = new ListReplica(); + using var subscription = list.Stream.Subscribe(replica.Apply); + + var workers = new Task[StressSettings.WorkerCount]; + for (var worker = 0; worker < workers.Length; worker++) + { + var random = new StressRandom(unchecked((seed * ListReplaySeedFactor) + worker)); + workers[worker] = Task.Run(() => ConcurrencyFuzzHelpers.ConflictingWrites(list, random)); + } + + await Task.WhenAll(workers).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + await TestWaitHelpers.WaitUntilAsync(() => replica.Matches(list.ToArray())).ConfigureAwait(false); + await Assert.That(replica.WentNegative).IsFalse(); + } + } + + /// Verifies that a stream replaying dictionary notifications ends equal to the dictionary. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_StreamReplay_MatchesDictionaryAfterConflictingWrites() + { + for (var seed = 1; seed <= SeedCount; seed++) + { + using var dictionary = new QuaternaryDictionary(); + var replica = new Dictionary(); + var gate = new Lock(); + using var subscription = dictionary.Stream.Subscribe(n => ConcurrencyFuzzHelpers.ApplyToReplica(replica, gate, n)); + + var workers = new Task[StressSettings.WorkerCount]; + for (var worker = 0; worker < workers.Length; worker++) + { + var random = new StressRandom(unchecked((seed * DictionaryReplaySeedFactor) + worker)); + workers[worker] = Task.Run(() => ConcurrencyFuzzHelpers.ConflictingDictionaryWrites(dictionary, random)); + } + + await Task.WhenAll(workers).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + await TestWaitHelpers.WaitUntilAsync(() => ConcurrencyFuzzHelpers.ReplicaMatches(dictionary, replica, gate)).ConfigureAwait(false); + } + } + + /// Verifies that an index added while items are being added ends up complete. + /// A task representing the asynchronous test. + [Test] + public async Task List_AddIndexDuringAdds_IndexesEveryItem() + { + for (var round = 0; round < RaceRounds; round++) + { + using var list = new QuaternaryList(); + var tasks = new List(); + for (var worker = 0; worker < StressSettings.WorkerCount; worker++) + { + var start = worker * RacerSpacing; + tasks.Add(Task.Run(() => + { + for (var i = 0; i < AddsPerRacer; i++) + { + list.Add(start + i); + } + })); + } + + tasks.Add(Task.Run(() => list.AddIndex(ConcurrencyFuzzHelpers.ModIndex, static i => i % ConcurrencyFuzzHelpers.IndexModulus))); + await Task.WhenAll(tasks).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + + ConcurrencyFuzzHelpers.AssertIndexMatchesContents(list); + } + } + + /// Verifies that Clear and Add racing together leave the indexes equal to the contents. + /// A task representing the asynchronous test. + [Test] + public async Task List_ClearRacingAdds_KeepsIndexesEqualToContents() + { + for (var round = 0; round < RaceRounds; round++) + { + using var list = new QuaternaryList(); + list.AddIndex(ConcurrencyFuzzHelpers.ModIndex, static i => i % ConcurrencyFuzzHelpers.IndexModulus); + var tasks = new Task[StressSettings.WorkerCount]; + for (var worker = 0; worker < tasks.Length; worker++) + { + var start = worker * RacerSpacing; + var clears = worker == 0; + tasks[worker] = Task.Run(() => + { + for (var i = 0; i < ClearRaceOperations; i++) + { + if (clears && i % ClearEvery == 0) + { + list.Clear(); + } + else + { + list.Add(start + i); + } + } + }); + } + + await Task.WhenAll(tasks).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + ConcurrencyFuzzHelpers.AssertIndexMatchesContents(list); + } + } +} diff --git a/src/tests/ReactiveList.Tests/QuaternaryDeferralsTests.cs b/src/tests/ReactiveList.Tests/QuaternaryDeferralsTests.cs new file mode 100644 index 00000000..2be53103 --- /dev/null +++ b/src/tests/ReactiveList.Tests/QuaternaryDeferralsTests.cs @@ -0,0 +1,49 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks the begin and end rules of . +public class QuaternaryDeferralsTests +{ + /// Releasing the same scope a second time changes nothing. + /// A task representing the asynchronous test. + [Test] + public async Task End_ReleasedTwice_SecondReleaseDoesNothing() + { + var state = CreateState(); + NotificationDeferralState? release = null; + var token = QuaternaryDeferrals.Begin(state, captured => release = captured); + token.Dispose(); + + var first = QuaternaryDeferrals.End(state, release!, static () => []); + var second = QuaternaryDeferrals.End(state, release!, static () => []); + + await Assert.That(first).IsFalse(); + await Assert.That(second).IsFalse(); + } + + /// Opening a scope while holding a shard lock is rejected. + /// A task representing the asynchronous test. + [Test] + public async Task Begin_ShardLockHeld_Throws() + { + var state = CreateState(); + state.Locks[0].EnterReadLock(); + try + { + await Assert.That(() => QuaternaryDeferrals.Begin(state, static _ => { })).Throws(); + } + finally + { + state.Locks[0].ExitReadLock(); + } + } + + /// Creates a state with four empty shards. + /// The state. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static QuaternaryState CreateState() => + QuaternaryCore.CreateState([new QuadList(), new QuadList(), new QuadList(), new QuadList()], "test"); +} diff --git a/src/tests/ReactiveList.Tests/QuaternaryDictionaryContractTests.cs b/src/tests/ReactiveList.Tests/QuaternaryDictionaryContractTests.cs new file mode 100644 index 00000000..41d00550 --- /dev/null +++ b/src/tests/ReactiveList.Tests/QuaternaryDictionaryContractTests.cs @@ -0,0 +1,63 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks the interface members of and the span append of . +public class QuaternaryDictionaryContractTests +{ + /// The key of the entry added by the enumerator test. + private const int EntryKey = 7; + + /// A removed collection-changed handler no longer receives events. + /// A task representing the asynchronous test. + [Test] + public async Task CollectionChanged_RemovedHandler_ReceivesNothing() + { + using QuaternaryDictionary dictionary = new(); + var raised = 0; + NotifyCollectionChangedEventHandler handler = (_, _) => Interlocked.Increment(ref raised); + dictionary.CollectionChanged += handler; + dictionary.CollectionChanged -= handler; + + dictionary.Add(1, "one"); + dictionary.Add(EntryKey, "seven"); + + await Assert.That(Volatile.Read(ref raised)).IsEqualTo(0); + } + + /// The dictionary is writable and enumerates through the non-generic interface. + /// A task representing the asynchronous test. + [Test] + public async Task IsReadOnlyAndNonGenericEnumeration_ReportTheContents() + { + using QuaternaryDictionary dictionary = new(); + dictionary.Add(EntryKey, "seven"); + IEnumerable enumerable = dictionary; + List entries = []; + + foreach (var entry in enumerable) + { + entries.Add(entry); + } + + await Assert.That(dictionary.IsReadOnly).IsFalse(); + await Assert.That(entries.Count).IsEqualTo(1); + await Assert.That(((KeyValuePair)entries[0]).Key).IsEqualTo(EntryKey); + } + + /// Appending a span adds its items and an empty span changes nothing. + /// A task representing the asynchronous test. + [Test] + public async Task QuadListAddRange_Span_AppendsItems() + { + QuadList list = []; + ReadOnlySpan items = [1, EntryKey]; + list.AddRange(in items); + list.AddRange(ReadOnlySpan.Empty); + + await Assert.That(list.Count).IsEqualTo(items.Length); + await Assert.That(list[1]).IsEqualTo(EntryKey); + } +} diff --git a/src/tests/ReactiveList.Tests/QuaternaryDictionaryCountRaceTests.cs b/src/tests/ReactiveList.Tests/QuaternaryDictionaryCountRaceTests.cs new file mode 100644 index 00000000..19e019fb --- /dev/null +++ b/src/tests/ReactiveList.Tests/QuaternaryDictionaryCountRaceTests.cs @@ -0,0 +1,72 @@ +// 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. + +namespace ReactiveList.Tests; + +/// A lock-free read of a sharded dictionary's count stays within the range of states the writer produced. +public sealed class QuaternaryDictionaryCountRaceTests +{ + /// The number of keys the writer adds and removes in each round. + private const int KeysPerRound = 4; + + /// The number of add, remove and clear rounds. + private const int Rounds = 400_000; + + /// The count read while a writer adds and removes keys is never negative and never above the writer's peak. + /// A task representing the asynchronous test. + [Test] + public async Task Count_ReadWhileAWriterAddsAndRemoves_StaysInRange() + { + using var dictionary = new QuaternaryDictionary(); + using var started = new ManualResetEventSlim(false); + var done = 0; + var lowest = 0; + var highest = 0; + + var reader = Task.Run(() => + { + started.Set(); + while (Volatile.Read(ref done) == 0) + { + var count = dictionary.Count; + if (count < lowest) + { + lowest = count; + } + + if (count > highest) + { + highest = count; + } + } + }); + + var writer = Task.Run(() => + { + started.Wait(); + for (var round = 0; round < Rounds; round++) + { + for (var key = 0; key < KeysPerRound; key++) + { + dictionary.Add(key, round); + } + + for (var key = 0; key < KeysPerRound; key++) + { + _ = dictionary.Remove(key); + } + + // A clear rewinds the shard's entry position, so the next round's removals refill its free list. + dictionary.Clear(); + } + + Volatile.Write(ref done, 1); + }); + + await Task.WhenAll(reader, writer); + + await Assert.That(lowest).IsEqualTo(0); + await Assert.That(highest).IsLessThanOrEqualTo(KeysPerRound); + } +} diff --git a/src/tests/ReactiveList.Tests/QuaternaryDictionaryExtensionsTests.cs b/src/tests/ReactiveList.Tests/QuaternaryDictionaryExtensionsTests.cs index 9345b40b..1115daeb 100644 --- a/src/tests/ReactiveList.Tests/QuaternaryDictionaryExtensionsTests.cs +++ b/src/tests/ReactiveList.Tests/QuaternaryDictionaryExtensionsTests.cs @@ -7,7 +7,7 @@ namespace ReactiveList.Tests; /// Contains unit tests for the QuaternaryDictionary extension methods in QuaternaryExtensions. -public class QuaternaryDictionaryExtensionsTests +public sealed class QuaternaryDictionaryExtensionsTests { /// The second key used by dictionary test data. private const int SecondEntryKey = 2; @@ -207,6 +207,61 @@ await TestWaitHelpers.WaitForPropertyChangedAsync( await Assert.That(view.Items).HasSingleItem(); } + /// Verifies that CreateViewBySecondaryIndex with multiple keys updates when a matching entry is added later. + /// A task representing the asynchronous test operation. + [Test] + public async Task CreateViewBySecondaryIndex_WithMultipleKeys_ShouldUpdateOnAdd() + { + using var dict = new QuaternaryDictionary(); + dict.AddValueIndex(CityIndexName, static p => p.City); + dict.Add(1, new(AliceName, "NYC")); + + using var view = dict.CreateViewBySecondaryIndex(CityIndexName, ["NYC", "LA"], Sequencer.Default, throttleMs: 50); + + await TestWaitHelpers.WaitForViewAsync( + view, + () => view.Items.Count == SecondEntryKey, + () => dict.Add(SecondEntryKey, new("Bob", "LA"))); + + await Assert.That(view.Items.Count).IsEqualTo(SecondEntryKey); + } + + /// Verifies that CreateViewBySecondaryIndex with multiple keys replaces the entry of a key whose value is updated. + /// A task representing the asynchronous test operation. + [Test] + public async Task CreateViewBySecondaryIndex_WithMultipleKeys_ShouldReplaceUpdatedEntry() + { + using var dict = new QuaternaryDictionary(); + dict.AddValueIndex(CityIndexName, static p => p.City); + dict.Add(1, new(AliceName, "NYC")); + + using var view = dict.CreateViewBySecondaryIndex(CityIndexName, ["NYC", "LA"], Sequencer.Default, throttleMs: 50); + + await TestWaitHelpers.WaitForViewAsync( + view, + () => view.Items.Count == 1 && view.Items[0].Value.City == "LA", + () => dict.AddOrUpdate(1, new(AliceName, "LA"))); + + await Assert.That(view.Items).HasSingleItem(); + } + + /// Verifies that a stream filter with no keys, or for an entry without a value, matches nothing. + /// A task representing the asynchronous test operation. + [Test] + public async Task MatchesAnyDictionaryKey_NoKeysOrNullValue_MatchesNothing() + { + using var dict = new QuaternaryDictionary(); + dict.AddValueIndex(CityIndexName, static p => p.City); + SecondaryIndexFilterRequest, string> empty = new(dict, CityIndexName, null, []); + SecondaryIndexFilterRequest, string> withKey = new(dict, CityIndexName, null, ["NYC"]); + + using (Assert.Multiple()) + { + await Assert.That(QuaternaryExtensions.MatchesAnyDictionaryKey(new(1, new(AliceName, "NYC")), empty)).IsFalse(); + await Assert.That(QuaternaryExtensions.MatchesAnyDictionaryKey(new(1, null!), withKey)).IsFalse(); + } + } + /// Provides TestPerson. /// The Name value. /// The City value. diff --git a/src/tests/ReactiveList.Tests/QuaternaryDictionaryFuzzTests.cs b/src/tests/ReactiveList.Tests/QuaternaryDictionaryFuzzTests.cs new file mode 100644 index 00000000..5f68155e --- /dev/null +++ b/src/tests/ReactiveList.Tests/QuaternaryDictionaryFuzzTests.cs @@ -0,0 +1,39 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks against a plain dictionary model using generated operation sequences. +public sealed class QuaternaryDictionaryFuzzTests +{ + /// Verifies int keys against the model. + /// A task representing the asynchronous test. + [Test] + public Task IntKeys_FollowDictionaryModel() + { + var run = new DictionaryModelRun(static i => i); + Check.Sample(FuzzSupport.Operations(), run.Execute, iter: FuzzSupport.DefaultIterations, print: FuzzSupport.Describe); + return Task.CompletedTask; + } + + /// Verifies string keys against the model. + /// A task representing the asynchronous test. + [Test] + public Task StringKeys_FollowDictionaryModel() + { + var run = new DictionaryModelRun(static i => $"k{i}"); + Check.Sample(FuzzSupport.Operations(), run.Execute, iter: FuzzSupport.DefaultIterations, print: FuzzSupport.Describe); + return Task.CompletedTask; + } + + /// Verifies keys with heavily colliding hash codes against the model. + /// A task representing the asynchronous test. + [Test] + public Task CollidingKeys_FollowDictionaryModel() + { + var run = new DictionaryModelRun(static i => new CollidingItem(i, i % DictionaryModelRun.FirstModulus)); + Check.Sample(FuzzSupport.Operations(), run.Execute, iter: FuzzSupport.DefaultIterations, print: FuzzSupport.Describe); + return Task.CompletedTask; + } +} diff --git a/src/tests/ReactiveList.Tests/QuaternaryDictionaryTests.cs b/src/tests/ReactiveList.Tests/QuaternaryDictionaryTests.cs index abb58189..d6b158c8 100644 --- a/src/tests/ReactiveList.Tests/QuaternaryDictionaryTests.cs +++ b/src/tests/ReactiveList.Tests/QuaternaryDictionaryTests.cs @@ -13,7 +13,7 @@ namespace ReactiveList.Tests; /// These tests ensure that QuaternaryDictionary methods and properties behave as expected under various /// scenarios, including duplicate key handling, event notifications, and secondary value indexing. The tests are /// intended to validate the public API and observable behaviors of QuaternaryDictionary. -public class QuaternaryDictionaryTests +public sealed class QuaternaryDictionaryTests { /// The second key used by dictionary test data. private const int SecondDictionaryKey = 2; @@ -268,7 +268,7 @@ public async Task RemoveKeys_ShouldRemoveMultipleKeysAndEmitBatch() using var reset = new ManualResetEventSlim(false); using var subscription = dict.Stream.Subscribe(evt => { - if (evt.Action != CacheAction.BatchOperation) + if (evt.Action != CacheAction.BatchRemoved) { return; } diff --git a/src/tests/ReactiveList.Tests/QuaternaryDisposalNameTests.cs b/src/tests/ReactiveList.Tests/QuaternaryDisposalNameTests.cs new file mode 100644 index 00000000..d54aa127 --- /dev/null +++ b/src/tests/ReactiveList.Tests/QuaternaryDisposalNameTests.cs @@ -0,0 +1,56 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies that using a disposed collection always names the collection type. +public sealed class QuaternaryDisposalNameTests +{ + /// Verifies the list names its own type, with and without an observer. + /// A task representing the asynchronous test. + [Test] + public async Task List_UseAfterDispose_NamesTheListType() + { + var unobserved = new QuaternaryList(); + unobserved.Dispose(); + var observed = new QuaternaryList(); + observed.CollectionChanged += static (_, _) => { }; + observed.Dispose(); + + await Assert.That(NameOf(() => unobserved.Add(1))).IsEqualTo(nameof(QuaternaryList<>)); + await Assert.That(NameOf(() => observed.Add(1))).IsEqualTo(nameof(QuaternaryList<>)); + } + + /// Verifies the dictionary names its own type, with and without an observer. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_UseAfterDispose_NamesTheDictionaryType() + { + var unobserved = new QuaternaryDictionary(); + unobserved.Dispose(); + var observed = new QuaternaryDictionary(); + observed.CollectionChanged += static (_, _) => { }; + observed.Dispose(); + + await Assert.That(NameOf(() => unobserved.Add(1, 1))).IsEqualTo(nameof(QuaternaryDictionary<,>)); + await Assert.That(NameOf(() => observed.Add(1, 1))).IsEqualTo(nameof(QuaternaryDictionary<,>)); + } + + /// Runs an action that must throw and returns the reported object name. + /// The action to run. + /// The object name, or when nothing was thrown. + private static string? NameOf(Action action) + { + try + { + action(); + } + catch (ObjectDisposedException ex) + { + return ex.ObjectName; + } + + return null; + } +} diff --git a/src/tests/ReactiveList.Tests/QuaternaryExtensionsAdditionalTests.cs b/src/tests/ReactiveList.Tests/QuaternaryExtensionsAdditionalTests.cs index 625653aa..ea2a2d4c 100644 --- a/src/tests/ReactiveList.Tests/QuaternaryExtensionsAdditionalTests.cs +++ b/src/tests/ReactiveList.Tests/QuaternaryExtensionsAdditionalTests.cs @@ -10,7 +10,7 @@ namespace ReactiveList.Tests; /// Additional comprehensive tests for QuaternaryExtensions covering dynamic secondary index views /// using CreateViewBySecondaryIndex with observable keys. /// -public class QuaternaryExtensionsAdditionalTests +public sealed class QuaternaryExtensionsAdditionalTests { /// The expected number of items in a pair. private const int ExpectedPairCount = 2; diff --git a/src/tests/ReactiveList.Tests/QuaternaryExtensionsTests.cs b/src/tests/ReactiveList.Tests/QuaternaryExtensionsTests.cs index a422a6a7..49a7236e 100644 --- a/src/tests/ReactiveList.Tests/QuaternaryExtensionsTests.cs +++ b/src/tests/ReactiveList.Tests/QuaternaryExtensionsTests.cs @@ -7,7 +7,7 @@ namespace ReactiveList.Tests; /// Contains unit tests for the QuaternaryExtensions class. -public class QuaternaryExtensionsTests +public sealed class QuaternaryExtensionsTests { /// The second integer value used by collection tests. private const int SecondCollectionValue = 2; @@ -217,6 +217,24 @@ await TestWaitHelpers.WaitForPropertyChangedAsync( await Assert.That(view.Items).HasSingleItem(); } + /// Verifies that a stream filter with no keys matches nothing. + /// A task representing the asynchronous test. + [Test] + public async Task MatchesAnyListKey_NoKeys_MatchesNothing() + { + using var list = new QuaternaryList(); + list.AddIndex(CityIndexName, static p => p.City); + SecondaryIndexFilterRequest, string> empty = new(list, CityIndexName, null, []); + SecondaryIndexFilterRequest, string> withKey = new(list, CityIndexName, null, ["NYC"]); + list.Add(new(AliceName, "NYC")); + + using (Assert.Multiple()) + { + await Assert.That(QuaternaryExtensions.MatchesAnyListKey(new(AliceName, "NYC"), empty)).IsFalse(); + await Assert.That(QuaternaryExtensions.MatchesAnyListKey(new(AliceName, "LA"), withKey)).IsFalse(); + } + } + /// Provides TestPerson. /// The Name value. /// The City value. diff --git a/src/tests/ReactiveList.Tests/QuaternaryHandlerListTests.cs b/src/tests/ReactiveList.Tests/QuaternaryHandlerListTests.cs new file mode 100644 index 00000000..7e1efbfd --- /dev/null +++ b/src/tests/ReactiveList.Tests/QuaternaryHandlerListTests.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. + +namespace ReactiveList.Tests; + +/// Checks how the sharded collections swap their collection-changed handler list when another thread changed it first. +public class QuaternaryHandlerListTests +{ + /// Adding with a stale list fails and reports the list that is stored; adding with the current list succeeds. + /// A task representing the asynchronous test. + [Test] + public async Task TryCombine_StaleList_FailsAndReturnsTheStoredList() + { + var stored = new NotifyCollectionChangedEventHandler(static (_, _) => { }); + var added = new NotifyCollectionChangedEventHandler(static (_, _) => { }); + var field = stored; + NotifyCollectionChangedEventHandler? current = null; + + var staleResult = QuaternaryEvents.TryCombine(ref field, ref current, added); + var observed = current; + var freshResult = QuaternaryEvents.TryCombine(ref field, ref current, added); + + await Assert.That(staleResult).IsFalse(); + await Assert.That(observed).IsSameReferenceAs(stored); + await Assert.That(freshResult).IsTrue(); + await Assert.That(field!.GetInvocationList().Length).IsEqualTo(1 + 1); + } + + /// Removing with a stale list fails and reports the list that is stored; removing with the current list succeeds. + /// A task representing the asynchronous test. + [Test] + public async Task TryRemove_StaleList_FailsAndReturnsTheStoredList() + { + var stored = new NotifyCollectionChangedEventHandler(static (_, _) => { }); + var field = stored; + NotifyCollectionChangedEventHandler? current = null; + + var staleResult = QuaternaryEvents.TryRemove(ref field, ref current, stored); + var observed = current; + var freshResult = QuaternaryEvents.TryRemove(ref field, ref current, stored); + + await Assert.That(staleResult).IsFalse(); + await Assert.That(observed).IsSameReferenceAs(stored); + await Assert.That(freshResult).IsTrue(); + await Assert.That(field).IsNull(); + } +} diff --git a/src/tests/ReactiveList.Tests/QuaternaryLifecycleTests.cs b/src/tests/ReactiveList.Tests/QuaternaryLifecycleTests.cs new file mode 100644 index 00000000..a9bfb95d --- /dev/null +++ b/src/tests/ReactiveList.Tests/QuaternaryLifecycleTests.cs @@ -0,0 +1,728 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies disposal, notification delivery, enumeration, and argument handling of the quaternary collections. +public sealed class QuaternaryLifecycleTests +{ + /// The first sample value. + private const int First = 1; + + /// The second sample value. + private const int Second = 2; + + /// The third sample value. + private const int Third = 3; + + /// The number of items in a small sample collection. + private const int SampleCount = 5; + + /// The number of items in a larger sample collection. + private const int LargeSampleCount = 100; + + /// A value that no sample collection holds. + private const int MissingValue = 999; + + /// The offset added to values that a callback inserts. + private const int InsertedOffset = 100; + + /// The number of threads used by concurrent tests. + private const int ThreadCount = 8; + + /// The number of handlers each thread adds. + private const int HandlersPerThread = 50; + + /// The number of subscribe and dispose cycles per thread. + private const int SubscribeCycles = 500; + + /// The number of notifications queued before disposal. + private const int QueuedNotifications = 200; + + /// The number of rounds of the dispose while running test. + private const int DisposeRounds = 10; + + /// The number of worker threads in the dispose while running test. + private const int DisposeWorkers = 4; + + /// The number of loop iterations per worker in the dispose while running test. + private const int DisposeIterations = 20_000; + + /// The spacing between the item ranges of different workers. + private const int WorkerSpacing = 100_000; + + /// How often a worker does a heavier operation. + private const int HeavyEvery = 50; + + /// The number of values in the remove by predicate sample. + private const int PredicateSample = 30; + + /// The modulus of the sample indexes. + private const int IndexModulus = 3; + + /// The iteration count of the allocation test warm-up. + private const int WarmupIterations = 256; + + /// The iteration count of the measured allocation test. + private const int MeasuredIterations = 1024; + + /// The number of keys cycled by the allocation test. + private const int AllocationKeys = 64; + + /// The key offset for values the allocation test adds and removes. + private const int AllocationOffset = 1000; + + /// The value that makes the predicate test throw. + private const int ThrowingValue = 20; + + /// The name of the sample index. + private const string IndexName = "index"; + + /// The property name raised for the count. + private const string CountName = "Count"; + + /// The property name raised for the indexer. + private const string ItemName = "Item[]"; + + /// The maximum time a possibly blocking operation may take before the test fails. + private static readonly TimeSpan BlockingTimeout = TimeSpan.FromSeconds(30); + + /// Verifies that concurrent Dispose calls complete the stream exactly once. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_ConcurrentCalls_CompleteStreamOnce() + { + var list = new QuaternaryList(); + var completions = 0; + using var subscription = list.Stream.Subscribe(static notification => { }, () => Interlocked.Increment(ref completions)); + + var disposers = new Task[ThreadCount]; + for (var i = 0; i < disposers.Length; i++) + { + disposers[i] = Task.Run(list.Dispose); + } + + await Task.WhenAll(disposers).WaitAsync(BlockingTimeout); + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref completions) >= 1); + + await Assert.That(list.IsDisposed).IsTrue(); + await Assert.That(Volatile.Read(ref completions)).IsEqualTo(1); + } + + /// Verifies that every list operation throws after disposal. + /// A task representing the asynchronous test. + [Test] + public async Task List_AfterDispose_OperationsThrowObjectDisposed() + { + var list = new QuaternaryList { First }; + list.Dispose(); + + Action[] operations = + [ + () => list.Add(Second), + () => _ = list.Remove(First), + () => _ = list.Contains(First), + () => list.AddRange([First, Second]), + () => list.RemoveRange([First]), + () => _ = list.RemoveMany(static value => true), + () => list.Edit(static collection => { }), + () => list.ReplaceAll([First]), + () => list.Clear(), + () => list.AddIndex(IndexName, static value => value), + () => _ = list[0], + () => _ = list.ToArray(), + () => _ = list.Snapshot(), + () => _ = list.GetEnumerator(), + () => list.CopyTo(new int[SampleCount], 0), + () => _ = list.GetItemsBySecondaryIndex(IndexName, First), + ]; + + foreach (var operation in operations) + { + await Assert.That(operation).Throws(); + } + + await Assert.That(list.IsDisposed).IsTrue(); + } + + /// Verifies that every dictionary operation throws after disposal. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_AfterDispose_OperationsThrowObjectDisposed() + { + var dictionary = new QuaternaryDictionary(); + dictionary[First] = First; + dictionary.Dispose(); + + Action[] operations = + [ + () => dictionary.Add(Second, Second), + () => _ = dictionary.TryAdd(Second, Second), + () => dictionary.AddOrUpdate(First, Second), + () => _ = dictionary.Remove(First), + () => _ = dictionary.TryGetValue(First, out _), + () => _ = dictionary.ContainsKey(First), + () => dictionary.AddRange([new(Third, Third)]), + () => dictionary.RemoveKeys([First]), + () => _ = dictionary.RemoveMany(static pair => true), + () => dictionary.Edit(static target => { }), + () => dictionary.Clear(), + () => dictionary.AddValueIndex(IndexName, static value => value), + () => _ = dictionary.ToArray(), + () => _ = dictionary.Keys, + () => _ = dictionary.Values, + () => _ = dictionary.GetEnumerator(), + () => dictionary.CopyTo(new KeyValuePair[SampleCount], 0), + ]; + + foreach (var operation in operations) + { + await Assert.That(operation).Throws(); + } + } + + /// Checks that disposal completes a stream whose first subscriber starts concurrently. + /// A task representing the asynchronous test. + [Test] + public async Task Stream_FirstSubscribeRacesSourceDisposal_Completes() + { + const int rounds = 128; + await Parallel.ForAsync(0, rounds, static async (_, cancellationToken) => + { + var source = new QuaternaryList(); + var observer = new LiveQueryRecorder>(); + var subscribe = Task.Run(() => source.Stream.Subscribe(observer), cancellationToken); + var dispose = Task.Run(source.Dispose, cancellationToken); + using var subscription = await subscribe; + await dispose; + await TestWaitHelpers.WaitUntilAsync(() => observer.Completed || observer.Error is not null); + await Assert.That(observer.Error).IsNull(); + }); + } + + /// Verifies that Count, Version, and Dispose stay usable after disposal. + /// A task representing the asynchronous test. + [Test] + public async Task AfterDispose_CountVersionAndDispose_DoNotThrow() + { + var list = new QuaternaryList { First, Second }; + list.Dispose(); + list.Dispose(); + + await Assert.That(list.Count).IsEqualTo(Second); + await Assert.That(list.Version).IsGreaterThan(0L); + } + + /// Verifies that subscribing to a disposed collection completes immediately. + /// A task representing the asynchronous test. + [Test] + public async Task Stream_SubscribeAfterDispose_Completes() + { + var list = new QuaternaryList(); + list.Dispose(); + var completed = false; + using var subscription = list.Stream.Subscribe(static notification => { }, () => completed = true); + + await Assert.That(completed).IsTrue(); + } + + /// Verifies that queued notifications are delivered before the stream completes on disposal. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_DeliversQueuedNotificationsBeforeCompletion() + { + var list = new QuaternaryList(); + var received = 0; + var completed = 0; + var receivedAfterCompleted = 0; + using var subscription = list.Stream.Subscribe( + notification => + { + if (Volatile.Read(ref completed) != 0) + { + _ = Interlocked.Increment(ref receivedAfterCompleted); + } + + _ = Interlocked.Increment(ref received); + }, + () => Volatile.Write(ref completed, 1)); + + for (var i = 0; i < QueuedNotifications; i++) + { + list.Add(i); + } + + list.Dispose(); + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref completed) == 1); + + await Assert.That(Volatile.Read(ref received)).IsEqualTo(QueuedNotifications); + await Assert.That(Volatile.Read(ref receivedAfterCompleted)).IsEqualTo(0); + } + + /// Verifies that disposing while workers run only produces . + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_WhileWorkersRun_OnlyThrowsObjectDisposed() + { + for (var round = 0; round < DisposeRounds; round++) + { + var list = new QuaternaryList(); + list.AddIndex(IndexName, static i => i % IndexModulus); + var unexpected = new System.Collections.Concurrent.ConcurrentQueue(); + using var subscription = list.Stream.Subscribe(static notification => { }); + + var workers = new Task[DisposeWorkers]; + for (var worker = 0; worker < workers.Length; worker++) + { + var offset = worker * WorkerSpacing; + workers[worker] = Task.Run(() => HammerUntilDisposed(list, offset, unexpected)); + } + + await TestWaitHelpers.WaitUntilAsync(() => list.Count > 0); + list.Dispose(); + await Task.WhenAll(workers).WaitAsync(BlockingTimeout); + + await Assert.That(unexpected.ToArray()).IsEmpty(); + } + } + + /// Verifies that an observer that throws does not stop notifications to other observers. + /// A task representing the asynchronous test. + [Test] + public async Task Stream_ThrowingObserver_DoesNotStopOtherObservers() + { + using var list = new QuaternaryList(); + var received = 0; + var errors = 0; + using var faulty = list.Stream.Subscribe( + static notification => throw new InvalidOperationException("observer failure"), + error => Interlocked.Increment(ref errors)); + using var healthy = list.Stream.Subscribe(notification => Interlocked.Increment(ref received)); + + list.Add(First); + list.Add(Second); + list.Add(Third); + + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref received) == Third); + await Assert.That(Volatile.Read(ref errors)).IsEqualTo(1); + } + + /// Verifies that a throwing CollectionChanged handler does not stop later notifications. + /// A task representing the asynchronous test. + [Test] + public async Task CollectionChanged_ThrowingHandler_DoesNotStopLaterNotifications() + { + using var list = new QuaternaryList(); + var calls = 0; + list.CollectionChanged += (sender, args) => + { + _ = Interlocked.Increment(ref calls); + throw new InvalidOperationException("handler failure"); + }; + + list.Add(First); + list.Add(Second); + list.Add(Third); + + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref calls) == Third); + } + + /// Verifies that handlers subscribed from many threads are all kept. + /// A task representing the asynchronous test. + [Test] + public async Task CollectionChanged_ConcurrentSubscribe_KeepsEveryHandler() + { + using var list = new QuaternaryList(); + var calls = 0; + var subscribers = new Task[ThreadCount]; + for (var t = 0; t < subscribers.Length; t++) + { + subscribers[t] = Task.Run(() => + { + for (var i = 0; i < HandlersPerThread; i++) + { + list.CollectionChanged += (sender, args) => Interlocked.Increment(ref calls); + } + }); + } + + await Task.WhenAll(subscribers).WaitAsync(BlockingTimeout); + list.Add(First); + + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref calls) == ThreadCount * HandlersPerThread); + } + + /// Verifies that stream subscribe and unsubscribe from many threads leaves no phantom observer. + /// A task representing the asynchronous test. + [Test] + public async Task Stream_ConcurrentSubscribeAndDispose_LeavesNoObservers() + { + using var list = new QuaternaryList(); + var workers = new Task[ThreadCount]; + for (var w = 0; w < workers.Length; w++) + { + workers[w] = Task.Run(async () => + { + for (var i = 0; i < SubscribeCycles; i++) + { + var subscription = list.Stream.Subscribe(static notification => { }); + var other = Task.Run(subscription.Dispose); + subscription.Dispose(); + await other.ConfigureAwait(false); + } + }); + } + + await Task.WhenAll(workers).WaitAsync(BlockingTimeout); + + var delivered = 0; + using var late = list.Stream.Subscribe(_ => Interlocked.Increment(ref delivered)); + list.Add(First); + + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref delivered) == 1); + } + + /// Verifies that enumerating while adding to the same list neither throws nor loops forever. + /// A task representing the asynchronous test. + [Test] + public async Task Enumeration_WithReentrantAdd_UsesSnapshot() + { + using var list = new QuaternaryList(); + list.AddRange(Enumerable.Range(0, SampleCount)); + var seen = 0; + foreach (var item in list) + { + list.Add(item + InsertedOffset); + seen++; + } + + await Assert.That(seen).IsEqualTo(SampleCount); + await Assert.That(list.Count).IsEqualTo(SampleCount + SampleCount); + } + + /// Verifies that an abandoned enumerator does not block writers. + /// A task representing the asynchronous test. + [Test] + public async Task Enumeration_Abandoned_DoesNotBlockWriters() + { + using var list = new QuaternaryList(); + list.AddRange(Enumerable.Range(0, SampleCount)); + var enumerator = list.GetEnumerator(); + _ = enumerator.MoveNext(); + + await Task.Run(() => list.Add(MissingValue)).WaitAsync(BlockingTimeout); + await Task.Run(list.Clear).WaitAsync(BlockingTimeout); + + await Assert.That(list.Count).IsEqualTo(0); + } + + /// Verifies that dictionary enumeration with a reentrant write uses a snapshot. + /// A task representing the asynchronous test. + [Test] + public async Task DictionaryEnumeration_WithReentrantWrite_UsesSnapshot() + { + using var dictionary = new QuaternaryDictionary(); + foreach (var i in Enumerable.Range(0, SampleCount)) + { + dictionary[i] = i; + } + + var seen = 0; + foreach (var pair in dictionary) + { + dictionary[pair.Key + InsertedOffset] = pair.Value; + seen++; + } + + await Assert.That(seen).IsEqualTo(SampleCount); + await Assert.That(dictionary.Count).IsEqualTo(SampleCount + SampleCount); + } + + /// Verifies that a RemoveMany predicate may call back into the list. + /// A task representing the asynchronous test. + [Test] + public async Task RemoveMany_PredicateReadingTheList_DoesNotThrowOrDeadlock() + { + using var list = new QuaternaryList(); + list.AddRange(Enumerable.Range(0, LargeSampleCount)); + + var removed = await Task.Run(() => list.RemoveMany(i => list.Contains(i) && i % Second == 0)).WaitAsync(BlockingTimeout); + + await Assert.That(removed).IsEqualTo(LargeSampleCount / Second); + await Assert.That(list.Count).IsEqualTo(LargeSampleCount / Second); + } + + /// Verifies that a failing RemoveMany predicate leaves the list unchanged and consistent. + /// A task representing the asynchronous test. + [Test] + public async Task RemoveMany_ThrowingPredicate_LeavesListConsistent() + { + using var list = new QuaternaryList(); + list.AddIndex(IndexName, static i => i % IndexModulus); + list.AddRange(Enumerable.Range(0, PredicateSample)); + + await Assert.That(() => list.RemoveMany(static i => i == ThrowingValue ? throw new InvalidOperationException() : i % Second == 0)) + .Throws(); + + await Assert.That(list.Count).IsEqualTo(list.ToArray().Length); + for (var key = 0; key < IndexModulus; key++) + { + await Assert.That(list.GetItemsBySecondaryIndex(IndexName, key).Count()).IsEqualTo(list.ToArray().Count(i => i % IndexModulus == key)); + } + } + + /// Verifies that a failing Edit action keeps Count and the indexes consistent with the partial edit. + /// A task representing the asynchronous test. + [Test] + public async Task Edit_ThrowingAction_KeepsCountAndIndexesConsistent() + { + using var list = new QuaternaryList(); + list.AddIndex(IndexName, static i => i % IndexModulus); + list.Add(First); + + await Assert.That(() => list.Edit(static collection => + { + collection.Add(Second); + collection.Add(Third); + throw new InvalidOperationException(); + })).Throws(); + + await Assert.That(list.Count).IsEqualTo(Third); + await Assert.That(list.GetItemsBySecondaryIndex(IndexName, Second).ToArray()).IsEquivalentTo([Second]); + await Assert.That(list.Contains(Third)).IsTrue(); + } + + /// Verifies that PropertyChanged handlers run outside the collection locks. + /// A task representing the asynchronous test. + [Test] + public async Task PropertyChanged_Handler_CanReenterTheCollection() + { + using var list = new QuaternaryList(); + var failures = 0; + list.PropertyChanged += (sender, args) => + { + try + { + _ = list.Contains(First); + _ = list.ToArray(); + _ = list.Snapshot(); + } + catch (Exception) + { + _ = Interlocked.Increment(ref failures); + } + }; + + list.Add(First); + list.AddRange([Second, Third]); + _ = list.Remove(First); + list.Clear(); + + await Assert.That(failures).IsEqualTo(0); + } + + /// Verifies that a batch mutation raises each property change once. + /// A task representing the asynchronous test. + [Test] + public async Task AddRange_RaisesEachPropertyChangeOnce() + { + using var list = new QuaternaryList(); + var names = new List(); + list.PropertyChanged += (sender, args) => names.Add(args.PropertyName); + + list.AddRange(Enumerable.Range(0, SampleCount)); + + await Assert.That(names.Count(static n => n == CountName)).IsEqualTo(1); + await Assert.That(names.Count(static n => n == ItemName)).IsEqualTo(1); + } + + /// Verifies the version increases once per effective mutation and not for no-ops. + /// A task representing the asynchronous test. + [Test] + public async Task Version_IncreasesOncePerEffectiveMutation() + { + using var list = new QuaternaryList(); + var start = list.Version; + + list.Add(First); + await Assert.That(list.Version).IsEqualTo(start + 1); + + list.AddRange([Second, Third]); + await Assert.That(list.Version).IsEqualTo(start + Second); + + _ = list.Remove(MissingValue); + await Assert.That(list.Version).IsEqualTo(start + Second); + + _ = list.Remove(First); + await Assert.That(list.Version).IsEqualTo(start + Third); + } + + /// Verifies the argument checks of the list. + /// A task representing the asynchronous test. + [Test] + public async Task List_NullArguments_ThrowArgumentNull() + { + using var list = new QuaternaryList(); + + Action[] operations = + [ + () => list.AddRange(null!), + () => list.RemoveRange(null!), + () => _ = list.RemoveMany(null!), + () => list.Edit(null!), + () => list.ReplaceAll(null!), + () => list.CopyTo(null!, 0), + () => list.AddIndex(null!, static s => s.Length), + () => list.AddIndex(IndexName, null!), + () => _ = list.GetItemsBySecondaryIndex(null!, First), + ]; + + foreach (var operation in operations) + { + await Assert.That(operation).Throws(); + } + } + + /// Verifies the argument checks of the dictionary. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_NullArguments_ThrowArgumentNull() + { + using var dictionary = new QuaternaryDictionary(); + + Action[] operations = + [ + () => dictionary.AddRange(null!), + () => dictionary.RemoveKeys(null!), + () => _ = dictionary.RemoveMany(null!), + () => dictionary.Edit(null!), + () => dictionary.CopyTo(null!, 0), + () => dictionary.AddValueIndex(null!, static s => s.Length), + () => dictionary.AddValueIndex(IndexName, null!), + () => _ = dictionary.GetValuesBySecondaryIndex(null!, First), + ]; + + foreach (var operation in operations) + { + await Assert.That(operation).Throws(); + } + } + + /// Verifies that CopyTo validates its destination. + /// A task representing the asynchronous test. + [Test] + public async Task CopyTo_InvalidDestination_Throws() + { + using var list = new QuaternaryList(); + list.AddRange(Enumerable.Range(0, Third)); + using var dictionary = new QuaternaryDictionary { [First] = First, [Second] = Second }; + + await Assert.That(() => list.CopyTo(new int[Second], 0)).Throws(); + await Assert.That(() => list.CopyTo(new int[Third], 1)).Throws(); + await Assert.That(() => list.CopyTo(new int[Third], -1)).Throws(); + await Assert.That(() => dictionary.CopyTo(new KeyValuePair[1], 0)).Throws(); + await Assert.That(() => dictionary.CopyTo(new KeyValuePair[Second], -1)).Throws(); + } + + /// Verifies that indexing outside the list throws. + /// A task representing the asynchronous test. + [Test] + public async Task Indexer_OutOfRange_Throws() + { + using var list = new QuaternaryList(); + list.AddRange(Enumerable.Range(0, Third)); + + await Assert.That(() => list[Third]).Throws(); + await Assert.That(() => list[-1]).Throws(); + } + + /// Verifies that adding an index with an existing name replaces it and rebuilds from the current items. + /// A task representing the asynchronous test. + [Test] + public async Task AddIndex_SameNameDifferentKeyType_ReplacesTheIndex() + { + using var list = new QuaternaryList(); + list.AddRange(Enumerable.Range(1, SampleCount - 1)); + list.AddIndex(IndexName, static i => i % Second); + await Assert.That(list.GetItemsBySecondaryIndex(IndexName, First).Count()).IsEqualTo(Second); + + list.AddIndex(IndexName, static i => $"v{i}"); + + await Assert.That(list.GetItemsBySecondaryIndex(IndexName, First).Any()).IsFalse(); + await Assert.That(list.GetItemsBySecondaryIndex(IndexName, "v3").ToArray()).IsEquivalentTo([Third]); + } + + /// Verifies that unobserved single-item mutations and reads allocate nothing. + /// A task representing the asynchronous test. + [Test] + public async Task UnobservedSingleOperations_AllocateNothing() + { + using var list = new QuaternaryList(); + using var dictionary = new QuaternaryDictionary(); + for (var i = 0; i < AllocationKeys; i++) + { + list.Add(i); + dictionary[i] = i; + } + + Exercise(list, dictionary, WarmupIterations); + + var before = GC.GetAllocatedBytesForCurrentThread(); + Exercise(list, dictionary, MeasuredIterations); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + await Assert.That(allocated).IsEqualTo(0L); + } + + /// Adds, checks, and removes items until the list is disposed. + /// The list to use. + /// The first item identity for this worker. + /// Receives any exception that is not an . + private static void HammerUntilDisposed(QuaternaryList list, int offset, System.Collections.Concurrent.ConcurrentQueue unexpected) + { + try + { + for (var i = 0; i < DisposeIterations; i++) + { + list.Add(offset + i); + _ = list.Contains(offset + i); + _ = list.Remove(offset + i - 1); + if (i % HeavyEvery != 0) + { + continue; + } + + _ = list.ToArray(); + list.AddRange([i, i + 1, i + Second]); + } + } + catch (ObjectDisposedException) + { + // Expected once the list is disposed. + } + catch (Exception ex) + { + unexpected.Enqueue(ex); + } + } + + /// Runs single-item operations that must not allocate. + /// The list to exercise. + /// The dictionary to exercise. + /// The number of iterations. + private static void Exercise(QuaternaryList list, QuaternaryDictionary dictionary, int iterations) + { + for (var i = 0; i < iterations; i++) + { + var key = i % AllocationKeys; + list.Add(AllocationOffset + key); + _ = list.Contains(key); + _ = list.Remove(AllocationOffset + key); + dictionary.AddOrUpdate(key, i); + _ = dictionary.TryGetValue(key, out _); + _ = dictionary.TryAdd(AllocationOffset + key, i); + _ = dictionary.Remove(AllocationOffset + key); + } + } +} diff --git a/src/tests/ReactiveList.Tests/QuaternaryListFuzzTests.cs b/src/tests/ReactiveList.Tests/QuaternaryListFuzzTests.cs new file mode 100644 index 00000000..09c22ab0 --- /dev/null +++ b/src/tests/ReactiveList.Tests/QuaternaryListFuzzTests.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. + +namespace ReactiveList.Tests; + +/// Checks against a plain list model using generated operation sequences. +public sealed class QuaternaryListFuzzTests +{ + /// Verifies int items against the model, with many duplicates. + /// A task representing the asynchronous test. + [Test] + public Task IntItems_FollowListModel() + { + var run = new ListModelRun( + static i => i, + static i => i % ListModelRun.FirstModulus, + static i => i % ListModelRun.SecondModulus); + Check.Sample(FuzzSupport.Operations(), run.Execute, iter: FuzzSupport.DefaultIterations, print: FuzzSupport.Describe); + return Task.CompletedTask; + } + + /// Verifies string items against the model. + /// A task representing the asynchronous test. + [Test] + public Task StringItems_FollowListModel() + { + var run = new ListModelRun( + static i => $"s{i}", + static s => s.Length, + static s => s[^1] % ListModelRun.SecondModulus); + Check.Sample(FuzzSupport.Operations(), run.Execute, iter: FuzzSupport.DefaultIterations, print: FuzzSupport.Describe); + return Task.CompletedTask; + } + + /// Verifies items with heavily colliding hash codes against the model. + /// A task representing the asynchronous test. + [Test] + public Task CollidingItems_FollowListModel() + { + var run = new ListModelRun( + static i => new CollidingItem(i, i % ListModelRun.FirstModulus), + static c => c.Group, + static c => c.Id % ListModelRun.SecondModulus); + Check.Sample(FuzzSupport.Operations(), run.Execute, iter: FuzzSupport.DefaultIterations, print: FuzzSupport.Describe); + return Task.CompletedTask; + } +} diff --git a/src/tests/ReactiveList.Tests/QuaternaryListTests.cs b/src/tests/ReactiveList.Tests/QuaternaryListTests.cs index 28dbd854..196e7c5d 100644 --- a/src/tests/ReactiveList.Tests/QuaternaryListTests.cs +++ b/src/tests/ReactiveList.Tests/QuaternaryListTests.cs @@ -10,7 +10,7 @@ namespace ReactiveList.Tests; /// These tests cover scenarios such as adding and removing items, index-based access, batch operations, /// index management, and validation of unsupported operations. The tests ensure that QuaternaryList behaves as expected /// under various conditions and that its public API contracts are enforced. -public class QuaternaryListTests +public sealed class QuaternaryListTests { /// The second collection value used by test data. private const int SecondCollectionValue = 2; @@ -263,26 +263,22 @@ public async Task RemoveMany_WithPredicate_ShouldRemoveMatchingItems() await Assert.That(list).Contains(ThirdCollectionValue); } - /// Snapshot should release earlier shard locks when reentrant acquisition fails. + /// A RemoveMany predicate runs outside the shard locks, so it can read the list. /// A task representing the asynchronous test. [Test] - public async Task Snapshot_ReentrantFailure_ShouldReleaseAcquiredShardLocks() + public async Task RemoveMany_PredicateReadingTheList_ShouldNotDeadlockOrThrow() { using var list = new QuaternaryList { 1 }; - await Assert.That(() => list.RemoveMany(item => + var removed = list.RemoveMany(item => { - if (item != 1) - { - return false; - } - _ = list.Snapshot(); return false; - })).Throws(); + }); list.Add(FourthCollectionValue); + await Assert.That(removed).IsEqualTo(0); await Assert.That(list).Contains(FourthCollectionValue); } diff --git a/src/tests/ReactiveList.Tests/QuaternaryReadRaceTests.cs b/src/tests/ReactiveList.Tests/QuaternaryReadRaceTests.cs new file mode 100644 index 00000000..0940b709 --- /dev/null +++ b/src/tests/ReactiveList.Tests/QuaternaryReadRaceTests.cs @@ -0,0 +1,375 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies that readers racing writers never fail and that snapshots pair exactly with notification versions. +public sealed class QuaternaryReadRaceTests +{ + /// The number of writer threads. + private const int WriterCount = 4; + + /// The number of items each writer adds. + private const int ItemsPerWriter = 1_500; + + /// The spacing between the item identities of different writers. + private const int WriterSpacing = 1_000_000; + + /// The spare slots in arrays that receive a copy. + private const int Spare = 4_096; + + /// Selects the write step from the low bits of the operation number. + private const int StepMask = 3; + + /// The step that removes the item it just added. + private const int RemoveStep = 0; + + /// The step that adds a pair of extra items. + private const int RangeStep = 1; + + /// Selects the operations that clear the collection. + private const int ClearMask = 255; + + /// The number of snapshots the pairing test keeps. + private const int SnapshotCount = 40; + + /// The first key of the replaced entry in the update test. + private const int FirstValue = 10; + + /// The second value of the replaced entry in the update test. + private const int SecondValue = 20; + + /// The longest a writer keeps writing. + private static readonly TimeSpan WriteBudget = TimeSpan.FromSeconds(10); + + /// The read paths exercised against a list. + private static readonly Action>[] ListReads = + [ + static list => _ = list.ToArray(), + static list => _ = list.Snapshot(), + static list => list.CopyTo(new int[list.Count + Spare], 0), + static list => + { + foreach (var item in list) + { + _ = item; + } + }, + static list => _ = list.Contains(WriterCount), + static list => _ = list.CopyVersioned(out _) + ]; + + /// The read paths exercised against a dictionary. + private static readonly Action>[] DictionaryReads = + [ + static dictionary => _ = dictionary.ToArray(), + static dictionary => + { + _ = dictionary.Keys; + _ = dictionary.Values; + }, + static dictionary => dictionary.CopyTo(new KeyValuePair[dictionary.Count + Spare], 0), + static dictionary => + { + foreach (var pair in dictionary) + { + _ = pair; + } + }, + static dictionary => _ = dictionary.TryGetValue(WriterCount, out _), + static dictionary => _ = dictionary.CopyVersioned(out _) + ]; + + /// Verifies that every list read path survives concurrent adds, removes, replacements and clears. + /// A task representing the asynchronous test. + [Test] + public async Task List_ReadersRacingWriters_NeverThrow() + { + using var list = new QuaternaryList(); + using var stop = new CancellationTokenSource(); + var failures = new System.Collections.Concurrent.ConcurrentQueue(); + var readers = new Task[ListReads.Length]; + for (var r = 0; r < readers.Length; r++) + { + var read = ListReads[r]; + readers[r] = RunOnOwnThread(() => ReadLoop(list, read, failures, stop.Token)); + } + + var writers = new Task[WriterCount]; + for (var w = 0; w < writers.Length; w++) + { + var worker = w; + writers[w] = RunOnOwnThread(() => WriteList(list, worker)); + } + + await Task.WhenAll(writers).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + await stop.CancelAsync().ConfigureAwait(false); + await Task.WhenAll(readers).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + + await Assert.That(failures.IsEmpty).IsTrue(); + } + + /// Verifies that every dictionary read path survives concurrent writes. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_ReadersRacingWriters_NeverThrow() + { + using var dictionary = new QuaternaryDictionary(); + using var stop = new CancellationTokenSource(); + var failures = new System.Collections.Concurrent.ConcurrentQueue(); + var readers = new Task[DictionaryReads.Length]; + for (var r = 0; r < readers.Length; r++) + { + var read = DictionaryReads[r]; + readers[r] = RunOnOwnThread(() => ReadLoop(dictionary, read, failures, stop.Token)); + } + + var writers = new Task[WriterCount]; + for (var w = 0; w < writers.Length; w++) + { + var worker = w; + writers[w] = RunOnOwnThread(() => WriteDictionary(dictionary, worker)); + } + + await Task.WhenAll(writers).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + await stop.CancelAsync().ConfigureAwait(false); + await Task.WhenAll(readers).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + + await Assert.That(failures.IsEmpty).IsTrue(); + } + + /// Verifies that replacing a dictionary value reports the replaced entry. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_AddOrUpdate_ReportsThePreviousEntry() + { + using var dictionary = new QuaternaryDictionary(); + var updates = new System.Collections.Concurrent.ConcurrentQueue>>(); + using var subscription = dictionary.Stream.Subscribe(n => + { + if (n.Action == CacheAction.Updated) + { + updates.Enqueue(n); + } + }); + + dictionary.AddOrUpdate(1, FirstValue); + dictionary.AddOrUpdate(1, SecondValue); + + await TestWaitHelpers.WaitUntilAsync(() => updates.Count == 1).ConfigureAwait(false); + _ = updates.TryDequeue(out var update); + KeyValuePair expectedItem = new(1, SecondValue); + KeyValuePair expectedPrevious = new(1, FirstValue); + await Assert.That(update!.Item).IsEqualTo(expectedItem); + await Assert.That(update.Previous).IsEqualTo(expectedPrevious); + } + + /// Verifies that a list snapshot contains exactly the items whose notification version is at most the snapshot version. + /// A task representing the asynchronous test. + [Test] + public async Task List_VersionedSnapshot_PairsExactlyWithNotificationVersions() + { + using var list = new QuaternaryList(); + var delivered = new System.Collections.Concurrent.ConcurrentQueue<(int Item, long Version)>(); + using var subscription = list.VersionedStream.Subscribe(n => delivered.Enqueue((n.Notification.Item, n.Version))); + + var snapshots = new List<(HashSet Items, long Version)>(); + var writers = new Task[WriterCount]; + for (var w = 0; w < writers.Length; w++) + { + var worker = w; + writers[w] = Task.Run(() => + { + for (var i = 0; i < ItemsPerWriter; i++) + { + list.Add((worker * WriterSpacing) + i); + } + }); + } + + for (var s = 0; s < SnapshotCount; s++) + { + var items = list.CopyVersioned(out var version); + snapshots.Add(([.. items], version)); + await Task.Yield(); + } + + await Task.WhenAll(writers).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + await TestWaitHelpers.WaitUntilAsync(() => delivered.Count == WriterCount * ItemsPerWriter).ConfigureAwait(false); + + foreach (var (items, version) in snapshots) + { + foreach (var (item, itemVersion) in delivered) + { + await Assert.That(items.Contains(item)).IsEqualTo(itemVersion <= version); + } + } + } + + /// Verifies that a dictionary snapshot contains exactly the entries whose notification version is at most the snapshot version. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_VersionedSnapshot_PairsExactlyWithNotificationVersions() + { + using var dictionary = new QuaternaryDictionary(); + var delivered = new System.Collections.Concurrent.ConcurrentQueue<(int Key, long Version)>(); + using var subscription = dictionary.VersionedStream.Subscribe(n => delivered.Enqueue((n.Notification.Item.Key, n.Version))); + + var snapshots = new List<(HashSet Keys, long Version)>(); + var writers = new Task[WriterCount]; + for (var w = 0; w < writers.Length; w++) + { + var worker = w; + writers[w] = Task.Run(() => + { + for (var i = 0; i < ItemsPerWriter; i++) + { + dictionary.AddOrUpdate((worker * WriterSpacing) + i, i); + } + }); + } + + for (var s = 0; s < SnapshotCount; s++) + { + var entries = dictionary.CopyVersioned(out var version); + var keys = new HashSet(); + foreach (var entry in entries) + { + _ = keys.Add(entry.Key); + } + + snapshots.Add((keys, version)); + await Task.Yield(); + } + + await Task.WhenAll(writers).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + await TestWaitHelpers.WaitUntilAsync(() => delivered.Count == WriterCount * ItemsPerWriter).ConfigureAwait(false); + + foreach (var (keys, version) in snapshots) + { + foreach (var (key, keyVersion) in delivered) + { + await Assert.That(keys.Contains(key)).IsEqualTo(keyVersion <= version); + } + } + } + + /// Runs a loop on a thread of its own, so spinning readers cannot keep the writers waiting for a pool thread. + /// The loop. + /// A task that completes when the loop returns. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Task RunOnOwnThread(Action loop) => + Task.Factory.StartNew(loop, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + + /// + /// Gets whether a writer may keep going. A write waits for every spinning reader to leave its lock, which is slow on a + /// small machine, so the writers stop after a fixed time instead of a fixed count. A deadlock still reaches the test timeout. + /// + /// The timestamp at which the writer started. + /// while the writer is inside its time budget. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool WithinBudget(long started) => System.Diagnostics.Stopwatch.GetElapsedTime(started) < WriteBudget; + + /// Runs a read path against a list until cancelled. + /// The list to read. + /// The read path. + /// Receives any exception. + /// Cancels the loop. + private static void ReadLoop( + QuaternaryList list, + Action> read, + System.Collections.Concurrent.ConcurrentQueue failures, + CancellationToken token) + { + try + { + while (!token.IsCancellationRequested) + { + read(list); + } + } + catch (Exception ex) + { + failures.Enqueue(ex); + } + } + + /// Runs a read path against a dictionary until cancelled. + /// The dictionary to read. + /// The read path. + /// Receives any exception. + /// Cancels the loop. + private static void ReadLoop( + QuaternaryDictionary dictionary, + Action> read, + System.Collections.Concurrent.ConcurrentQueue failures, + CancellationToken token) + { + try + { + while (!token.IsCancellationRequested) + { + read(dictionary); + } + } + catch (Exception ex) + { + failures.Enqueue(ex); + } + } + + /// Applies a mixed write workload to a list. + /// The list to write. + /// The writer index. + private static void WriteList(QuaternaryList list, int worker) + { + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + for (var i = 0; i < ItemsPerWriter && WithinBudget(started); i++) + { + var item = (worker * WriterSpacing) + i; + list.Add(item); + var step = i & StepMask; + if (step == RemoveStep) + { + _ = list.Remove(item); + } + else if (step == RangeStep) + { + list.AddRange([item + 1, item + WriterCount]); + } + + if ((i & ClearMask) == ClearMask) + { + list.Clear(); + } + } + } + + /// Applies a mixed write workload to a dictionary. + /// The dictionary to write. + /// The writer index. + private static void WriteDictionary(QuaternaryDictionary dictionary, int worker) + { + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + for (var i = 0; i < ItemsPerWriter && WithinBudget(started); i++) + { + var key = (worker * WriterSpacing) + i; + dictionary.AddOrUpdate(key, i); + var step = i & StepMask; + if (step == RemoveStep) + { + _ = dictionary.Remove(key); + } + else if (step == RangeStep) + { + dictionary.AddRange([new(key + 1, i), new(key + WriterCount, i)]); + } + + if ((i & ClearMask) == ClearMask) + { + dictionary.Clear(); + } + } + } +} diff --git a/src/tests/ReactiveList.Tests/QuaternaryReplayTests.cs b/src/tests/ReactiveList.Tests/QuaternaryReplayTests.cs new file mode 100644 index 00000000..b34fa68f --- /dev/null +++ b/src/tests/ReactiveList.Tests/QuaternaryReplayTests.cs @@ -0,0 +1,175 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies that a view built from a versioned snapshot and the versioned stream ends equal to the collection. +public sealed class QuaternaryReplayTests +{ + /// The number of writer threads. + private const int WriterCount = 4; + + /// The number of operations each writer runs. + private const int OperationsPerWriter = 3_000; + + /// The spacing between the identities used by different writers. + private const int WriterSpacing = 1_000_000; + + /// Every nth added item is removed again. + private const int RemoveEvery = 3; + + /// The number of finished operations after which the replay starts. + private const int SubscribeAfter = 1_000; + + /// Verifies that replaying the versioned stream over a snapshot taken mid-stream reproduces the list. + /// A task representing the asynchronous test. + [Test] + public async Task List_ReplayFromVersionedSnapshot_EndsEqualToTheList() + { + using var list = new QuaternaryList(); + var replay = new System.Collections.Concurrent.ConcurrentDictionary(); + var progress = 0; + var writers = StartWriters( + WriterCount, + writer => + { + for (var i = 0; i < OperationsPerWriter; i++) + { + var item = (writer * WriterSpacing) + i; + list.Add(item); + if (i % RemoveEvery == 0) + { + _ = list.Remove(item); + } + + _ = Interlocked.Increment(ref progress); + } + }); + + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref progress) >= SubscribeAfter).ConfigureAwait(false); + + // Notifications that arrive before the snapshot is applied are held back, because a late delivery of a change older + // than the snapshot would otherwise overwrite the snapshot's newer state before the version filter is armed. + ReplayGate gate = new(replay); + using var subscription = list.VersionedStream.Subscribe( + notification => gate.Receive(notification.Notification, notification.Version, Apply)); + + var snapshot = list.CopyVersioned(out var version); + gate.Complete(version, snapshot, static (map, item) => map[item] = 0, Apply); + + await Task.WhenAll(writers).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + var final = list.ToArray(); + await TestWaitHelpers.WaitUntilAsync(() => replay.Count == final.Length && Array.TrueForAll(final, replay.ContainsKey)).ConfigureAwait(false); + + await Assert.That(replay.Count).IsEqualTo(final.Length); + } + + /// Verifies that replaying the versioned stream over a snapshot taken mid-stream reproduces the dictionary. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_ReplayFromVersionedSnapshot_EndsEqualToTheDictionary() + { + using var dictionary = new QuaternaryDictionary(); + var replay = new System.Collections.Concurrent.ConcurrentDictionary(); + var progress = 0; + var writers = StartWriters( + WriterCount, + writer => + { + for (var i = 0; i < OperationsPerWriter; i++) + { + var key = (writer * WriterSpacing) + i; + dictionary.AddOrUpdate(key, i); + dictionary.AddOrUpdate(key, i + 1); + if (i % RemoveEvery == 0) + { + _ = dictionary.Remove(key); + } + + _ = Interlocked.Increment(ref progress); + } + }); + + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref progress) >= SubscribeAfter).ConfigureAwait(false); + + // Notifications that arrive before the snapshot is applied are held back, because a late delivery of a change older + // than the snapshot would otherwise overwrite the snapshot's newer value before the version filter is armed. + ReplayGate, int> gate = new(replay); + using var subscription = dictionary.VersionedStream.Subscribe( + notification => gate.Receive(notification.Notification, notification.Version, ApplyEntry)); + + var snapshot = dictionary.CopyVersioned(out var version); + gate.Complete(version, snapshot, static (map, entry) => map[entry.Key] = entry.Value, ApplyEntry); + + await Task.WhenAll(writers).WaitAsync(StressSettings.Timeout).ConfigureAwait(false); + var final = dictionary.ToArray(); + await TestWaitHelpers.WaitUntilAsync(() => replay.Count == final.Length && Matches(final, replay)).ConfigureAwait(false); + + await Assert.That(replay.Count).IsEqualTo(final.Length); + } + + /// Starts the writer threads. + /// The number of writers. + /// The work one writer performs, given its number. + /// The writer tasks. + private static Task[] StartWriters(int count, Action body) + { + var writers = new Task[count]; + for (var w = 0; w < writers.Length; w++) + { + var writer = w; + writers[w] = Task.Run(() => body(writer)); + } + + return writers; + } + + /// Applies one list notification to the replayed set. + /// The replayed set. + /// The notification to apply. + private static void Apply(System.Collections.Concurrent.ConcurrentDictionary replay, CacheNotify notification) + { + if (notification.Action == CacheAction.Removed) + { + _ = replay.TryRemove(notification.Item, out _); + } + else + { + replay[notification.Item] = 0; + } + } + + /// Applies one dictionary notification to the replayed map. + /// The replayed map. + /// The notification to apply. + private static void ApplyEntry(System.Collections.Concurrent.ConcurrentDictionary replay, CacheNotify> notification) + { + var entry = notification.Item; + if (notification.Action == CacheAction.Removed) + { + _ = replay.TryRemove(entry.Key, out _); + } + else + { + replay[entry.Key] = entry.Value; + } + } + + /// Determines whether the replayed map holds every entry of the final array. + /// The entries of the dictionary. + /// The replayed map. + /// when every entry matches. + private static bool Matches(KeyValuePair[] final, System.Collections.Concurrent.ConcurrentDictionary replay) + { + foreach (var entry in final) + { + if (!replay.TryGetValue(entry.Key, out var value) || value != entry.Value) + { + return false; + } + } + + return true; + } +} diff --git a/src/tests/ReactiveList.Tests/QuaternarySubscriptionTests.cs b/src/tests/ReactiveList.Tests/QuaternarySubscriptionTests.cs new file mode 100644 index 00000000..960a0f48 --- /dev/null +++ b/src/tests/ReactiveList.Tests/QuaternarySubscriptionTests.cs @@ -0,0 +1,210 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks how and account for observer faults. +public class QuaternarySubscriptionTests +{ + /// An error reaches the observer and ends the subscription. + /// A task representing the asynchronous test. + [Test] + public async Task OnError_ReportsToObserverAndEndsTheSubscription() + { + var state = CreateState(); + ScriptedObserver observer = new(); + QuaternarySubscription subscription = new(state, observer); + _ = Interlocked.Increment(ref state.SubscriberCount); + InvalidOperationException failure = new(); + + subscription.OnError(failure); + subscription.OnError(new ArgumentException()); + subscription.OnNext(1); + + await Assert.That(observer.Error).IsSameReferenceAs(failure); + await Assert.That(observer.Values).IsEmpty(); + await Assert.That(Volatile.Read(ref state.SubscriberCount)).IsEqualTo(0); + } + + /// An observer that throws while receiving the error does not escape the subscription. + /// A task representing the asynchronous test. + [Test] + public async Task OnError_ObserverThrows_IsSwallowed() + { + var state = CreateState(); + QuaternarySubscription subscription = new(state, new ScriptedObserver(throwOnEnd: true)); + _ = Interlocked.Increment(ref state.SubscriberCount); + + subscription.OnError(new InvalidOperationException()); + + await Assert.That(Volatile.Read(ref state.SubscriberCount)).IsEqualTo(0); + } + + /// An observer that throws while completing is still released. + /// A task representing the asynchronous test. + [Test] + public async Task OnCompleted_ObserverThrows_IsSwallowedAndReleased() + { + var state = CreateState(); + _ = Interlocked.Increment(ref state.SubscriberCount); + QuaternarySubscription subscription = new(state, new ScriptedObserver(throwOnEnd: true)); + + subscription.OnCompleted(); + subscription.OnCompleted(); + + await Assert.That(Volatile.Read(ref state.SubscriberCount)).IsEqualTo(0); + } + + /// A pipeline subscription attached after the subscription ended is disposed at once. + /// A task representing the asynchronous test. + [Test] + public async Task Attach_AfterDispose_DisposesTheInnerSubscription() + { + var state = CreateState(); + QuaternarySubscription subscription = new(state, new ScriptedObserver()); + StrongBox disposals = new(); + subscription.Dispose(); + + subscription.Attach(Scope.Create(disposals, static box => box.Value++)); + + await Assert.That(disposals.Value).IsEqualTo(1); + } + + /// A pipeline that fails to subscribe releases the subscriber count and rethrows. + /// A task representing the asynchronous test. + [Test] + public async Task Attach_PipelineThrows_ReleasesTheSubscriberAndRethrows() + { + var state = CreateState(); + ScriptedObserver observer = new(); + + await Assert.That(() => QuaternaryEvents.Attach(state, observer, new FailingPipeline())).Throws(); + + await Assert.That(Volatile.Read(ref state.SubscriberCount)).IsEqualTo(0); + } + + /// A pipeline that reports disposal while the collection is disposed completes the observer instead of failing. + /// A task representing the asynchronous test. + [Test] + public async Task Attach_PipelineDisposedWithTheCollection_CompletesTheObserver() + { + var state = CreateState(); + _ = Interlocked.Exchange(ref state.Disposed, 1); + ScriptedObserver observer = new(); + + _ = QuaternaryEvents.Attach(state, observer, new DisposedPipeline()); + + await Assert.That(observer.Completions).IsEqualTo(1); + } + + /// A throwing subscriber of the pipeline does not escape delivery. + /// A task representing the asynchronous test. + [Test] + public async Task DeliverToObservers_SubscriberThrows_IsSwallowed() + { + using Signal pipeline = new(); + using var subscription = pipeline.Subscribe(new ScriptedObserver(throwOnNext: true)); + + QuaternaryEvents.DeliverToObservers(pipeline, 1); + + await Assert.That(pipeline).IsNotNull(); + } + + /// Taking every write lock releases the locks already held when one cannot be taken. + /// A task representing the asynchronous test. + [Test] + public async Task EnterAllWriteLocks_LockCannotBeTaken_ReleasesHeldLocksAndRethrows() + { + ReaderWriterLockSlim[] locks = [new(), new()]; + locks[1].EnterWriteLock(); + + await Assert.That(() => QuaternaryShardHelpers.EnterAllWriteLocks(locks)).Throws(); + + await Assert.That(locks[0].IsWriteLockHeld).IsFalse(); + locks[1].ExitWriteLock(); + } + + /// Taking every read lock releases the locks already held when one cannot be taken. + /// A task representing the asynchronous test. + [Test] + public async Task EnterAllReadLocks_LockCannotBeTaken_ReleasesHeldLocksAndRethrows() + { + ReaderWriterLockSlim[] locks = [new(), new()]; + locks[1].EnterWriteLock(); + + await Assert.That(() => QuaternaryShardHelpers.EnterAllReadLocks(locks)).Throws(); + + await Assert.That(locks[0].IsReadLockHeld).IsFalse(); + locks[1].ExitWriteLock(); + } + + /// Creates an empty shared state for a subscription. + /// The state. + private static QuaternaryState CreateState() => new([], [], [], null, "test"); + + /// A pipeline that reports it was disposed when it is subscribed. + private sealed class DisposedPipeline : IObservable + { + /// + /// Always thrown. + public IDisposable Subscribe(IObserver observer) => throw new ObjectDisposedException(nameof(DisposedPipeline)); + } + + /// A pipeline whose subscription always fails. + private sealed class FailingPipeline : IObservable + { + /// + /// Always thrown. + public IDisposable Subscribe(IObserver observer) => throw new InvalidOperationException(); + } + + /// An observer that records what it receives and throws from the callbacks selected at construction. + /// Whether throws. + /// Whether and throw. + private sealed class ScriptedObserver(bool throwOnNext = false, bool throwOnEnd = false) : IObserver + { + /// Gets the received values. + public List Values { get; } = []; + + /// Gets the received error. + public Exception? Error { get; private set; } + + /// Gets the number of completions received. + public int Completions { get; private set; } + + /// + /// Thrown when configured to fail on completion. + public void OnCompleted() + { + Completions++; + if (throwOnEnd) + { + throw new InvalidOperationException(); + } + } + + /// + /// Thrown when configured to fail on errors. + public void OnError(Exception error) + { + Error = error; + if (throwOnEnd) + { + throw new InvalidOperationException(); + } + } + + /// + /// Thrown when configured to fail on values. + public void OnNext(int value) + { + if (throwOnNext) + { + throw new InvalidOperationException(); + } + + Values.Add(value); + } + } +} diff --git a/src/tests/ReactiveList.Tests/QuaternaryThrowingUserCodeTests.cs b/src/tests/ReactiveList.Tests/QuaternaryThrowingUserCodeTests.cs new file mode 100644 index 00000000..51e325c6 --- /dev/null +++ b/src/tests/ReactiveList.Tests/QuaternaryThrowingUserCodeTests.cs @@ -0,0 +1,203 @@ +// 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. + +namespace ReactiveList.Tests; + +/// User key selectors and equality code that throw in the middle of an operation must neither corrupt a sharded collection nor leave a change unannounced. +public sealed class QuaternaryThrowingUserCodeTests +{ + /// The name of the index used by the tests. + private const string IndexName = "key"; + + /// The message of the exception thrown by key selectors. + private const string SelectorMessage = "selector"; + + /// The value for which the key selector throws. + private const int PoisonedValue = 3; + + /// The shared hash code that puts every item in one shard. + private const int OneShard = 0; + + /// The name of the first item. + private const string Alpha = "alpha"; + + /// The name of the item that a removal asks for. + private const string Wanted = "wanted"; + + /// The name of the second kept item. + private const string Beta = "beta"; + + /// The name of the last item, which fails. + private const string Gamma = "gamma"; + + /// A single item whose key selector throws is stored, counted and announced, and the exception reaches the caller. + /// A task representing the asynchronous test. + [Test] + public async Task List_Add_WhenKeySelectorThrows_CommitsCountAndAnnouncesTheItem() + { + using var list = new QuaternaryList(); + list.AddIndex(IndexName, Selector); + using var replica = new VersionedListReplica(list); + + Action add = () => list.Add(PoisonedValue); + + await Assert.That(add).Throws(); + await Assert.That(list.Count).IsEqualTo(Contents(list).Length); + await Assert.That(list.Count).IsEqualTo(1); + await TestWaitHelpers.WaitUntilAsync(() => replica.Snapshot().SequenceEqual(Contents(list))); + } + + /// A batch that stops at an item whose key selector throws keeps the count equal to the contents and announces what was stored. + /// A task representing the asynchronous test. + [Test] + public async Task List_AddRange_WhenKeySelectorThrows_KeepsCountEqualToContentsAndAnnounces() + { + using var list = new QuaternaryList(); + list.AddIndex(IndexName, Selector); + using var replica = new VersionedListReplica(list); + + Action add = () => list.AddRange([1, PoisonedValue, TestData.TestValueFive]); + + await Assert.That(add).Throws(); + await Assert.That(list.Count).IsEqualTo(Contents(list).Length); + await TestWaitHelpers.WaitUntilAsync(() => replica.Snapshot().Order().SequenceEqual(Contents(list).Order())); + } + + /// A removal whose key selector throws is still counted and announced. + /// A task representing the asynchronous test. + [Test] + public async Task List_Remove_WhenKeySelectorThrows_CommitsCountAndAnnouncesTheRemoval() + { + var failOn = -1; + using var list = new QuaternaryList(); + list.AddIndex(IndexName, value => value == failOn ? throw new InvalidOperationException(SelectorMessage) : value); + list.Add(PoisonedValue); + using var replica = new VersionedListReplica(list); + failOn = PoisonedValue; + + Action remove = () => _ = list.Remove(PoisonedValue); + + await Assert.That(remove).Throws(); + await Assert.That(list.Count).IsEqualTo(0); + await TestWaitHelpers.WaitUntilAsync(() => replica.Snapshot().Length == 0); + } + + /// A hash code that throws part-way through a range removal leaves the shard intact and the count equal to the contents. + /// A task representing the asynchronous test. + [Test] + public async Task List_RemoveRange_WhenHashingThrowsPartWay_KeepsTheShardIntact() + { + ThrowingEqualityItem[] items = [new(Alpha, OneShard), new(Wanted, OneShard), new(Beta, OneShard), new(Gamma, OneShard)]; + using var list = new QuaternaryList(); + list.AddRange(items); + using var replica = new VersionedListReplica(list); + items[^1].Failure.OnHash = true; + + Action remove = () => list.RemoveRange([new ThrowingEqualityItem(Wanted, OneShard)]); + + await Assert.That(remove).Throws(); + await Assert.That(list.Count).IsEqualTo(Contents(list).Length); + await Assert.That(Names(Contents(list))).IsEquivalentTo([Alpha, Beta, Gamma], CollectionOrdering.Matching); + await TestWaitHelpers.WaitUntilAsync(() => Names(replica.Snapshot()).SequenceEqual(Names(Contents(list)))); + } + + /// A key whose hash code throws part-way through a key removal keeps the count equal to the contents and announces the removed entries. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_RemoveKeys_WhenHashingThrowsPartWay_KeepsCountEqualToContentsAndAnnounces() + { + ThrowingEqualityItem[] keys = [new(Alpha), new(Beta), new(Gamma)]; + using var dictionary = new QuaternaryDictionary(); + dictionary.AddRange([new(keys[0], 1), new(keys[1], TestData.TestValueTwo), new(keys[2], TestData.TestValueThree)]); + using var replica = new VersionedListReplica>(dictionary); + keys[1].Failure.OnHash = true; + + Action remove = () => dictionary.RemoveKeys([keys[0], keys[1]]); + + await Assert.That(remove).Throws(); + await Assert.That(dictionary.Count).IsEqualTo(Contents(dictionary).Length); + await Assert.That(dictionary.Count).IsEqualTo(TestData.TestValueTwo); + await TestWaitHelpers.WaitUntilAsync(() => replica.Snapshot().Length == dictionary.Count); + } + + /// A value whose key selector throws during an update is stored, counted and announced. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_AddOrUpdate_WhenKeySelectorThrows_CommitsAndAnnounces() + { + using var dictionary = new QuaternaryDictionary(); + dictionary.AddValueIndex(IndexName, Selector); + using var replica = new VersionedDictionaryReplica(dictionary); + + Action add = () => dictionary.AddOrUpdate(1, PoisonedValue); + + await Assert.That(add).Throws(); + await Assert.That(dictionary.Count).IsEqualTo(Contents(dictionary).Length); + await Assert.That(dictionary.Count).IsEqualTo(1); + await TestWaitHelpers.WaitUntilAsync(() => replica.Snapshot().SequenceEqual(Contents(dictionary))); + } + + /// A batch that stops at a value whose key selector throws keeps the count equal to the contents and announces what was stored. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_AddRange_WhenKeySelectorThrows_KeepsCountEqualToContentsAndAnnounces() + { + using var dictionary = new QuaternaryDictionary(); + dictionary.AddValueIndex(IndexName, Selector); + using var replica = new VersionedDictionaryReplica(dictionary); + + Action add = () => dictionary.AddRange([new(1, 1), new(TestData.TestValueTwo, PoisonedValue), new(TestData.TestValueFive, 1)]); + + await Assert.That(add).Throws(); + await Assert.That(dictionary.Count).IsEqualTo(Contents(dictionary).Length); + await TestWaitHelpers.WaitUntilAsync(() => replica.Snapshot().SequenceEqual(Contents(dictionary).OrderBy(static pair => pair.Key))); + } + + /// A predicate removal whose key selector throws keeps the count equal to the contents and announces the removed entries. + /// A task representing the asynchronous test. + [Test] + public async Task Dictionary_RemoveMany_WhenKeySelectorThrows_KeepsCountEqualToContentsAndAnnounces() + { + var failOn = -1; + using var dictionary = new QuaternaryDictionary(); + dictionary.AddValueIndex(IndexName, value => value == failOn ? throw new InvalidOperationException(SelectorMessage) : value); + dictionary.AddRange([new(1, 1), new(TestData.TestValueTwo, TestData.TestValueTwo), new(TestData.TestValueFive, PoisonedValue), new(TestData.TestValueSix, TestData.TestValueFour)]); + using var replica = new VersionedDictionaryReplica(dictionary); + failOn = PoisonedValue; + + Action remove = () => _ = dictionary.RemoveMany(static _ => true); + + await Assert.That(remove).Throws(); + await Assert.That(dictionary.Count).IsEqualTo(Contents(dictionary).Length); + await TestWaitHelpers.WaitUntilAsync(() => replica.Snapshot().SequenceEqual(Contents(dictionary).OrderBy(static pair => pair.Key))); + } + + /// Copies what the shards really hold; unlike ToArray it does not trust the cached count. + /// The item type. + /// The list. + /// The contents. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static T[] Contents(QuaternaryList list) + where T : notnull => list.CopyVersioned(out _); + + /// Copies what the shards really hold; unlike ToArray it does not trust the cached count. + /// The key type. + /// The value type. + /// The dictionary. + /// The contents. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static KeyValuePair[] Contents(QuaternaryDictionary dictionary) + where TKey : notnull => dictionary.CopyVersioned(out _); + + /// A key selector that throws for one value. + /// The value to key. + /// The key. + /// The value is the poisoned one. + private static int Selector(int value) => value == PoisonedValue ? throw new InvalidOperationException(SelectorMessage) : value; + + /// Projects the names of items. + /// The items. + /// The names in order. + private static string[] Names(ThrowingEqualityItem[] items) => [.. items.Select(static item => item.Name).Order(StringComparer.Ordinal)]; +} diff --git a/src/tests/ReactiveList.Tests/RangeObservableCollectionTests.cs b/src/tests/ReactiveList.Tests/RangeObservableCollectionTests.cs new file mode 100644 index 00000000..8cc17ddd --- /dev/null +++ b/src/tests/ReactiveList.Tests/RangeObservableCollectionTests.cs @@ -0,0 +1,50 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks that raises one reset per range change and nothing for no-ops. +public class RangeObservableCollectionTests +{ + /// The value inserted by the tests. + private const int Inserted = 7; + + /// The number of range changes that do something in the second test. + private const int ResetCount = 4; + + /// Empty range operations and clearing an empty collection raise nothing. + /// A task representing the asynchronous test. + [Test] + public async Task EmptyOperations_RaiseNoNotification() + { + RangeObservableCollection collection = []; + var raised = 0; + collection.CollectionChanged += (_, _) => raised++; + + collection.InsertRange(0, []); + collection.RemoveRange(0, 0); + collection.ClearIfNotEmpty(); + collection.ReplaceAll([]); + + await Assert.That(raised).IsEqualTo(0); + } + + /// Each range change that does something raises exactly one reset. + /// A task representing the asynchronous test. + [Test] + public async Task RangeOperations_RaiseOneResetEach() + { + RangeObservableCollection collection = []; + var raised = 0; + collection.CollectionChanged += (_, _) => raised++; + + collection.InsertRange(0, [1, Inserted]); + collection.RemoveRange(0, 1); + collection.ReplaceAll([Inserted, Inserted]); + collection.ClearIfNotEmpty(); + + await Assert.That(raised).IsEqualTo(ResetCount); + await Assert.That(collection).IsEmpty(); + } +} diff --git a/src/tests/ReactiveList.Tests/Reactive2DListForwardingTests.cs b/src/tests/ReactiveList.Tests/Reactive2DListForwardingTests.cs new file mode 100644 index 00000000..57678b26 --- /dev/null +++ b/src/tests/ReactiveList.Tests/Reactive2DListForwardingTests.cs @@ -0,0 +1,145 @@ +// 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. + +using CsCheck; + +namespace ReactiveList.Tests; + +/// Checks that behaves exactly like the of rows it forwards to. +public class Reactive2DListForwardingTests +{ + /// The number of distinct rows a scenario draws from. + private const int RowPool = 5; + + /// The number of operation kinds. + private const int OperationKinds = 9; + + /// The largest generated operation count. + private const int MaxOperations = 20; + + /// The number of random inputs. + private const int Iterations = 300; + + /// The number of CsCheck worker threads; one keeps runs repeatable per seed. + private const int Threads = 1; + + /// The operations the generator picks from; operations that do not fit the current contents do nothing. + private static readonly Action>, ReactiveList[], int, int>[] Operations = + [ + static (list, pool, a, _) => list.Add(pool[a]), + static (list, pool, a, b) => list.Insert(list.Count == 0 ? 0 : b % (list.Count + 1), pool[a]), + static (list, pool, a, b) => _ = list.Remove(pool[a]) && b >= 0, + static (list, _, a, _) => + { + if (list.Count > 0) + { + list.RemoveAt(a % list.Count); + } + }, + static (list, _, a, b) => + { + if (list.Count > 1) + { + list.Move(a % list.Count, b % list.Count); + } + }, + static (list, pool, a, b) => + { + if (list.Count > 0) + { + list[a % list.Count] = pool[b]; + } + }, + static (list, pool, a, b) => list.AddRange([pool[a], pool[b]]), + static (list, pool, a, b) => list.ReplaceAll([pool[b], pool[a]]), + static (list, _, _, _) => list.Clear(), + ]; + + /// The generator for one operation. + private static readonly Gen<(int Kind, int A, int B)> Op = Gen.Select( + Gen.Int[0, OperationKinds - 1], + Gen.Int[0, RowPool - 1], + Gen.Int[0, RowPool - 1], + static (kind, a, b) => (kind, a, b)); + + /// Random operations give the same list contents, version, count and stream as the plain list of rows. + /// A completed task. + [Test] + public Task RandomOperations_MatchAPlainListOfRows() + { + Op.Array[0, MaxOperations].Sample( + static operations => + { + ReactiveList[] pool = [new(), new(), new(), new(), new()]; + using Reactive2DList wrapped = []; + using ReactiveList> plain = []; + var wrappedActions = new List(); + var plainActions = new List(); + var wrappedChanges = 0; + var plainChanges = 0; + using var wrappedStream = wrapped.Stream.Subscribe(n => wrappedActions.Add(n.Action)); + using var plainStream = plain.Stream.Subscribe(n => plainActions.Add(n.Action)); + wrapped.CollectionChanged += (_, _) => wrappedChanges++; + plain.CollectionChanged += (_, _) => plainChanges++; + + for (var i = 0; i < operations.Length; i++) + { + Apply(wrapped, pool, operations[i]); + Apply(plain, pool, operations[i]); + } + + return wrapped.ToArray().SequenceEqual(plain.ToArray()) + && wrapped.Count == plain.Count + && wrapped.Version == plain.Version + && wrappedActions.SequenceEqual(plainActions) + && wrappedChanges == plainChanges; + }, + iter: Iterations, + threads: Threads); + return Task.CompletedTask; + } + + /// Disposing the wrapper disposes the rows it holds and the outer list. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_DisposesRowsAndOuterList() + { + ReactiveList row = new(1); + Reactive2DList wrapped = new(row); + + wrapped.Dispose(); + wrapped.Dispose(); + + await Assert.That(row.IsDisposed).IsTrue(); + await Assert.That(wrapped.IsDisposed).IsTrue(); + } + + /// The wrapper reports itself as the sender of forwarded events. + /// A task representing the asynchronous test. + [Test] + public async Task ForwardedEvents_UseTheWrapperAsSender() + { + using Reactive2DList wrapped = []; + object? collectionSender = null; + object? propertySender = null; + wrapped.CollectionChanged += (sender, _) => collectionSender = sender; + wrapped.PropertyChanged += (sender, _) => propertySender = sender; + + ReactiveList row = new(1); + wrapped.Add(row); + + await Assert.That(collectionSender).IsSameReferenceAs(wrapped); + await Assert.That(propertySender).IsSameReferenceAs(wrapped); + } + + /// Applies one operation to a list of rows. + /// The list. + /// The rows to draw from. + /// The operation. + private static void Apply(IReactiveList> list, ReactiveList[] pool, (int Kind, int A, int B) operation) + { + var (kind, a, b) = operation; + Operations[kind](list, pool, a, b); + } +} diff --git a/src/tests/ReactiveList.Tests/Reactive2DListSurfaceTests.cs b/src/tests/ReactiveList.Tests/Reactive2DListSurfaceTests.cs new file mode 100644 index 00000000..77a21632 --- /dev/null +++ b/src/tests/ReactiveList.Tests/Reactive2DListSurfaceTests.cs @@ -0,0 +1,372 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Exercises every member of that forwards to its list of rows or to one row. +public class Reactive2DListSurfaceTests +{ + /// A row count or index used by several tests. + private const int Two = 2; + + /// A row count used by several tests. + private const int Three = 3; + + /// A row count used by several tests. + private const int Six = 6; + + /// A row count used by several tests. + private const int Seven = 7; + + /// An item value used by the inner-row test. + private const int Ten = 10; + + /// An item value used by the inner-row test. + private const int Forty = 40; + + /// An item value that is not a valid index. + private const int OutOfRange = 5; + + /// Removing the last handler stops event forwarding and a remaining handler keeps it. + /// A task representing the asynchronous test. + [Test] + public async Task EventHandlers_RemoveDetachesForwarders() + { + using Reactive2DList list = []; + var collectionA = 0; + var collectionB = 0; + var propertyA = 0; + var propertyB = 0; + NotifyCollectionChangedEventHandler handlerA = (_, _) => collectionA++; + NotifyCollectionChangedEventHandler handlerB = (_, _) => collectionB++; + PropertyChangedEventHandler propA = (_, _) => propertyA++; + PropertyChangedEventHandler propB = (_, _) => propertyB++; + list.CollectionChanged += handlerA; + list.CollectionChanged += handlerB; + list.PropertyChanged += propA; + list.PropertyChanged += propB; + + list.Add(Row(0)); + list.CollectionChanged -= handlerA; + list.PropertyChanged -= propA; + list.Add(Row(0)); + list.CollectionChanged -= handlerB; + list.PropertyChanged -= propB; + list.Add(Row(0)); + + await Assert.That(collectionA).IsEqualTo(1); + await Assert.That(collectionB).IsEqualTo(Two); + await Assert.That(propertyA).IsGreaterThan(0); + await Assert.That(propertyB).IsGreaterThan(propertyA); + } + + /// The state properties report the values of the underlying list. + /// A task representing the asynchronous test. + [Test] + public async Task StateProperties_ReportUnderlyingList() + { + using Reactive2DList list = new(Row(1)); + var seenAdded = 0; + var seenChanged = 0; + var seenRemoved = 0; + var seenCurrent = 0; + var streamed = 0; + var versioned = 0; + using var added = list.Added.Subscribe(_ => seenAdded++); + using var changed = list.Changed.Subscribe(_ => seenChanged++); + using var removed = list.Removed.Subscribe(_ => seenRemoved++); + using var current = list.CurrentItems.Subscribe(_ => seenCurrent++); + using var stream = list.Stream.Subscribe(_ => streamed++); + using var versionedStream = list.VersionedStream.Subscribe(_ => versioned++); + + list.Add(Row(0)); + list.RemoveAt(0); + + using (Assert.Multiple()) + { + await Assert.That(list.Count).IsEqualTo(1); + await Assert.That(list.IsDisposed).IsFalse(); + await Assert.That(list.IsFixedSize).IsFalse(); + await Assert.That(list.IsReadOnly).IsFalse(); + await Assert.That(list.IsSynchronized).IsFalse(); + await Assert.That(list.SyncRoot).IsNotNull(); + await Assert.That(list.Version).IsGreaterThan(0L); + await Assert.That(list.Items.Count).IsEqualTo(1); + await Assert.That(list.ItemsAdded.Count).IsGreaterThanOrEqualTo(0); + await Assert.That(list.ItemsChanged.Count).IsGreaterThanOrEqualTo(0); + await Assert.That(list.ItemsRemoved.Count).IsGreaterThanOrEqualTo(0); + await Assert.That(seenAdded).IsGreaterThan(0); + await Assert.That(seenChanged).IsGreaterThan(0); + await Assert.That(seenRemoved).IsGreaterThan(0); + await Assert.That(seenCurrent).IsGreaterThan(0); + await Assert.That(streamed).IsGreaterThan(0); + await Assert.That(versioned).IsGreaterThan(0); + } + } + + /// Both indexers read and write rows. + /// A task representing the asynchronous test. + [Test] + public async Task Indexers_ReadAndWriteRows() + { + using Reactive2DList list = new(Row(1)); + IList nonGeneric = list; + var replacement = Row(Two); + var other = Row(Three); + + list[0] = replacement; + var first = list[0]; + nonGeneric[0] = other; + var second = nonGeneric[0]; + + await Assert.That(first).IsSameReferenceAs(replacement); + await Assert.That(second).IsSameReferenceAs(other); + } + + /// The row-level add, contains, index, insert, move and remove members forward to the outer list. + /// A task representing the asynchronous test. + [Test] + public async Task RowMembers_ForwardToOuterList() + { + using Reactive2DList list = []; + var a = Row(1); + var b = Row(Two); + var c = Row(Three); + var d = Row(Two + Two); + var e = Row(Seven); + var f = Row(Six); + + list.Add(a); + var objectIndex = list.Add((object)b); + list.AddRange((IEnumerable>)[c]); + list.AddRange(new ReadOnlySpan>([d])); + list.Insert(0, e); + list.Insert(0, (object)f); + list.Move(0, 1); + + using (Assert.Multiple()) + { + await Assert.That(objectIndex).IsEqualTo(1); + await Assert.That(list.Count).IsEqualTo(Six); + await Assert.That(list.Contains(a)).IsTrue(); + await Assert.That(list.Contains((object)b)).IsTrue(); + await Assert.That(list.IndexOf(c)).IsGreaterThanOrEqualTo(0); + await Assert.That(list.IndexOf((object)d)).IsGreaterThanOrEqualTo(0); + } + + list.InsertRange(0, (IEnumerable>)[Row(Seven)]); + await Assert.That(list.Count).IsEqualTo(Seven); + + _ = list.Remove(a); + list.Remove((IEnumerable>)[b]); + list.Remove((object)c); + list.RemoveAt(0); + var removed = list.RemoveMany(static row => row.Count > 0 && row[0] == Two + Two); + await Assert.That(removed).IsEqualTo(1); + + list.RemoveRange(0, list.Count); + list.ReplaceAll([a, b]); + list.Update(a, c); + await Assert.That(list.Count).IsEqualTo(Two); + } + + /// The copy, span, memory and snapshot members read the underlying rows. + /// A task representing the asynchronous test. + [Test] + public async Task CopyAndSnapshotMembers_ReadRows() + { + var a = Row(1); + var b = Row(Two); + using Reactive2DList list = new((IEnumerable>)[a, b]); + var typed = new ReactiveList[Two]; + var untyped = new ReactiveList[Two]; + var spanTarget = new ReactiveList[Two]; + + list.CopyTo(typed, 0); + list.CopyTo((Array)untyped, 0); + list.CopyTo(spanTarget.AsSpan()); + var versionedCopy = list.CopyVersioned(out var version); + var viaEnumerable = 0; + foreach (ReactiveList unused in (IEnumerable)list) + { + viaEnumerable++; + } + + using (Assert.Multiple()) + { + await Assert.That(typed[1]).IsSameReferenceAs(b); + await Assert.That(untyped[0]).IsSameReferenceAs(a); + await Assert.That(spanTarget[1]).IsSameReferenceAs(b); + await Assert.That(versionedCopy.Length).IsEqualTo(Two); + await Assert.That(version).IsEqualTo(list.Version); + await Assert.That(list.AsMemory().Length).IsEqualTo(Two); + await Assert.That(list.AsSpan().Length).IsEqualTo(Two); + await Assert.That(list.ToArray().Length).IsEqualTo(Two); + await Assert.That(viaEnumerable).IsEqualTo(Two); + } + } + + /// The clear, deferral, edit and subscribe members forward to the outer list. + /// A task representing the asynchronous test. + [Test] + public async Task ClearDeferEditAndSubscribe_ForwardToOuterList() + { + using Reactive2DList list = new(Row(1)); + CountingObserver observer = new(); + using var subscription = list.Subscribe(observer); + + using (list.DeferNotifications()) + { + list.Add(Row(Two)); + } + + list.Edit(static editable => editable.Add(Row(Three))); + await Assert.That(list.Count).IsEqualTo(Three); + + list.ClearWithoutDeallocation(); + list.Add(Row(Two + Two)); + list.ClearWithoutDeallocation(notifyChange: false); + list.Add(Row(OutOfRange)); + list.Clear(); + + await Assert.That(list.Count).IsEqualTo(0); + await Assert.That(observer.Emissions).IsGreaterThan(0); + } + + /// The constructors wrap items, rows and nested sequences into rows. + /// A task representing the asynchronous test. + [Test] + public async Task Constructors_BuildRows() + { + IEnumerable> nested = [[1, Two], [Three]]; + IEnumerable flat = [1, Two, Three]; + + using Reactive2DList fromNested = new(nested); + using Reactive2DList fromFlat = new(flat); + using Reactive2DList fromItem = new(1); + using Reactive2DList fromNestedSequence = new(Enumerate(nested)); + + using (Assert.Multiple()) + { + await Assert.That(fromNested.Count).IsEqualTo(Two); + await Assert.That(fromFlat.Count).IsEqualTo(Three); + await Assert.That(fromItem.Count).IsEqualTo(1); + await Assert.That(fromNestedSequence.Count).IsEqualTo(Two); + await Assert.That(static () => new Reactive2DList((ReactiveList)null!)).Throws(); + await Assert.That(static () => new Reactive2DList((IEnumerable)null!)).Throws(); + } + } + + /// A failing source sequence disposes the rows created so far and rethrows. + /// A task representing the asynchronous test. + [Test] + public async Task Constructor_FailingSequence_ThrowsAndDisposesCreatedRows() + { + await Assert.That(static () => new Reactive2DList(FailingRows())).Throws(); + await Assert.That(static () => new Reactive2DList(FailingItems())).Throws(); + } + + /// The inner-row members add, insert, clear, remove, read and write items inside one row. + /// A task representing the asynchronous test. + [Test] + public async Task InnerRowMembers_ChangeItemsInsideOneRow() + { + using Reactive2DList list = new((IEnumerable>)[new([1, Two, Three]), new(Two + Two)]); + IEnumerable> nested = [[OutOfRange, Six]]; + IEnumerable pair = [Seven, Seven + 1]; + + list.AddToInner(0, Ten); + list.AddToInner(0, pair); + list.Insert(0, pair, 0); + list.SetItem(1, 0, Forty); + list.RemoveFromInner(1, 0); + list.AddRange(nested); + list.AddRange(pair); + list.Insert(0, Ten + Ten); + list.InsertRange(0, pair); + list.ClearInner(1); + + using (Assert.Multiple()) + { + await Assert.That(list.GetItem(0, 0)).IsEqualTo(Seven); + await Assert.That(list.TotalCount()).IsGreaterThan(0); + await Assert.That(list.Flatten().Count()).IsEqualTo(list.TotalCount()); + await Assert.That(() => list.AddToInner(0, (IEnumerable)null!)).Throws(); + await Assert.That(() => list.Insert(0, (IEnumerable)null!, 0)).Throws(); + await Assert.That(() => list.AddRange((IEnumerable>)null!)).Throws(); + await Assert.That(() => list.AddRange((IEnumerable)null!)).Throws(); + await Assert.That(() => list.InsertRange(0, (IEnumerable)null!)).Throws(); + } + } + + /// Out-of-range indexes report the parameter the caller got wrong. + /// A task representing the asynchronous test. + [Test] + public async Task OutOfRangeIndexes_ReportTheOffendingParameter() + { + using Reactive2DList list = new(Row(1)); + + var outer = await Assert.That(() => list.GetItem(OutOfRange, 0)).Throws(); + var inner = await Assert.That(() => list.GetItem(0, OutOfRange)).Throws(); + var innerSet = await Assert.That(() => list.SetItem(0, OutOfRange, 1)).Throws(); + + await Assert.That(outer!.ParamName).IsEqualTo("outerIndex"); + await Assert.That(inner!.ParamName).IsEqualTo("innerIndex"); + await Assert.That(innerSet!.ParamName).IsEqualTo("innerIndex"); + } + + /// Creates a row holding one item. + /// The item. + /// The row. + private static ReactiveList Row(int item) => new(item); + + /// Yields the nested sequences one at a time so the constructor cannot see a collection. + /// The sequences to yield. + /// The sequences. + private static IEnumerable> Enumerate(IEnumerable> source) + { + foreach (var row in source) + { + yield return row; + } + } + + /// Yields one row and then throws. + /// The sequences. + /// Always thrown after the first row. + private static IEnumerable> FailingRows() + { + yield return [1]; + throw new InvalidOperationException(); + } + + /// Yields one item and then throws. + /// The items. + /// Always thrown after the first item. + private static IEnumerable FailingItems() + { + yield return 1; + throw new InvalidOperationException(); + } + + /// Counts the batches it receives. + private sealed class CountingObserver : IObserver>> + { + /// Gets the number of batches received. + public int Emissions { get; private set; } + + /// + public void OnCompleted() + { + } + + /// + public void OnError(Exception error) + { + } + + /// + public void OnNext(IEnumerable> value) => Emissions++; + } +} diff --git a/src/tests/ReactiveList.Tests/Reactive2DListVersionedTests.cs b/src/tests/ReactiveList.Tests/Reactive2DListVersionedTests.cs new file mode 100644 index 00000000..0d03627e --- /dev/null +++ b/src/tests/ReactiveList.Tests/Reactive2DListVersionedTests.cs @@ -0,0 +1,79 @@ +// 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. + +namespace ReactiveList.Tests; + +/// exposes the versioned snapshot and stream of its rows so views can start without missing a change. +public sealed class Reactive2DListVersionedTests +{ + /// The number of rows each writer thread adds. + private const int RowsPerWriter = 500; + + /// The number of threads adding rows. + private const int Writers = 4; + + /// The list is a versioned snapshot source of its rows. + /// A task representing the asynchronous test. + [Test] + public async Task Reactive2DList_IsAVersionedSnapshotSourceOfRows() + { + using var list = new Reactive2DList(); + + await Assert.That(list is IVersionedSnapshotSource>).IsTrue(); + } + + /// The copy holds the current rows and its version matches the list version. + /// A task representing the asynchronous test. + [Test] + public async Task CopyVersioned_ReturnsCurrentRowsAndVersion() + { + using var list = new Reactive2DList([[1], [TestData.TestValueTwo]]); + + var copy = list.CopyVersioned(out var version); + + await Assert.That(copy.Length).IsEqualTo(TestData.TestValueTwo); + await Assert.That(version).IsEqualTo(list.Version); + } + + /// A change to the rows reaches the versioned stream with a version above the copy. + /// A task representing the asynchronous test. + [Test] + public async Task VersionedStream_AfterACopy_CarriesLaterRowChanges() + { + using var list = new Reactive2DList(); + LiveQueryRecorder>> recorder = new(); + using var subscription = list.VersionedStream.Subscribe(recorder); + _ = list.CopyVersioned(out var copyVersion); + + list.Add(new([1])); + + await TestWaitHelpers.WaitUntilAsync(() => recorder.Values.Length > 0); + await Assert.That(recorder.Values[0].Version).IsGreaterThan(copyVersion); + } + + /// A view over the list holds every row added by several threads at once. + /// A task representing the asynchronous test. + [Test] + public async Task View_UnderConcurrentRowAdds_ConvergesOnEveryRow() + { + using var list = new Reactive2DList(); + using var view = list.CreateView(static _ => true, Sequencer.Immediate); + var writers = new Task[Writers]; + for (var writer = 0; writer < Writers; writer++) + { + writers[writer] = Task.Run(() => + { + for (var row = 0; row < RowsPerWriter; row++) + { + list.Add(new([row])); + } + }); + } + + await Task.WhenAll(writers); + + await TestWaitHelpers.WaitUntilAsync(() => view.Count == Writers * RowsPerWriter); + await Assert.That(view.Count).IsEqualTo(list.Count); + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveList.Tests.csproj b/src/tests/ReactiveList.Tests/ReactiveList.Tests.csproj index 32d28460..9692f1b0 100644 --- a/src/tests/ReactiveList.Tests/ReactiveList.Tests.csproj +++ b/src/tests/ReactiveList.Tests/ReactiveList.Tests.csproj @@ -12,6 +12,11 @@ + + + + + @@ -23,6 +28,7 @@ + diff --git a/src/tests/ReactiveList.Tests/ReactiveListAutoRefreshTests.cs b/src/tests/ReactiveList.Tests/ReactiveListAutoRefreshTests.cs new file mode 100644 index 00000000..4594fd9a --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListAutoRefreshTests.cs @@ -0,0 +1,447 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Tests that AutoRefresh attaches and detaches its per-item handlers at the right moments. +public class ReactiveListAutoRefreshTests +{ + /// The property name used by most tests. + private const string Watched = "Name"; + + /// The number of raising threads in the concurrency test. + private const int RaiserCount = 4; + + /// The number of property changes raised by each thread. + private const int RaisesPerThread = 500; + + /// The number of items in the end-to-end test. + private const int ItemCount = 5; + + /// The number of refreshes expected when two handlers would each have fired. + private const int DuplicateRefreshes = 1; + + /// Removing an item detaches its handler immediately. + /// A task representing the asynchronous test. + [Test] + public async Task Remove_DetachesHandlerAtOnce() + { + using var source = new Signal>(); + var item = new CountingItem(); + var refreshes = new List>(); + using var subscription = source.AutoRefresh(Watched).Subscribe(refreshes.Add); + + source.OnNext(new(Change.CreateAdd(item, 0))); + await Assert.That(item.HandlerCount).IsEqualTo(1); + + source.OnNext(new(Change.CreateRemove(item, 0))); + await Assert.That(item.HandlerCount).IsEqualTo(0); + + var before = refreshes.Count; + item.Raise(Watched); + await Assert.That(refreshes.Count).IsEqualTo(before); + } + + /// Replacing an item moves the handler from the old item to the new one. + /// A task representing the asynchronous test. + [Test] + public async Task Update_MovesHandlerToNewItem() + { + using var source = new Signal>(); + var oldItem = new CountingItem(); + var newItem = new CountingItem(); + using var subscription = source.AutoRefresh(Watched).Subscribe(static _ => { }); + + source.OnNext(new(Change.CreateAdd(oldItem, 0))); + source.OnNext(new(Change.CreateUpdate(newItem, oldItem, 0))); + + await Assert.That(oldItem.HandlerCount).IsEqualTo(0); + await Assert.That(newItem.HandlerCount).IsEqualTo(1); + } + + /// Updating an item with itself keeps its handler. + /// A task representing the asynchronous test. + [Test] + public async Task Update_WithSameInstance_KeepsHandler() + { + using var source = new Signal>(); + var item = new CountingItem(); + var refreshCount = 0; + using var subscription = source.AutoRefresh(Watched) + .Subscribe(changes => refreshCount += CountRefreshes(changes)); + + source.OnNext(new(Change.CreateAdd(item, 0))); + source.OnNext(new(Change.CreateUpdate(item, item, 0))); + item.Raise(Watched); + + await Assert.That(item.HandlerCount).IsEqualTo(1); + await Assert.That(refreshCount).IsEqualTo(1); + } + + /// A clear detaches every handler. + /// A task representing the asynchronous test. + [Test] + public async Task Clear_DetachesEveryHandler() + { + using var source = new Signal>(); + var first = new CountingItem(); + var second = new CountingItem(); + using var subscription = source.AutoRefresh(Watched).Subscribe(static _ => { }); + + source.OnNext(new( + [ + Change.CreateAdd(first, 0), + Change.CreateAdd(second, 1), + ])); + source.OnNext(new(new Change(ChangeReason.Clear, first))); + + await Assert.That(first.HandlerCount).IsEqualTo(0); + await Assert.That(second.HandlerCount).IsEqualTo(0); + } + + /// Disposing the subscription detaches every handler. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_DetachesEveryHandler() + { + using var source = new Signal>(); + var first = new CountingItem(); + var second = new CountingItem(); + var subscription = source.AutoRefresh(Watched).Subscribe(static _ => { }); + + source.OnNext(new( + [ + Change.CreateAdd(first, 0), + Change.CreateAdd(second, 1), + ])); + subscription.Dispose(); + + await Assert.That(first.HandlerCount).IsEqualTo(0); + await Assert.That(second.HandlerCount).IsEqualTo(0); + await Assert.That(source.HasObservers).IsFalse(); + } + + /// An item added twice is watched once, refreshes once per change and stays watched until its last occurrence is removed. + /// A task representing the asynchronous test. + [Test] + public async Task DuplicateItem_IsWatchedOnceUntilLastOccurrenceLeaves() + { + using var source = new Signal>(); + var item = new CountingItem(); + var refreshCount = 0; + using var subscription = source.AutoRefresh(Watched) + .Subscribe(changes => refreshCount += CountRefreshes(changes)); + + source.OnNext(new(Change.CreateAdd(item, 0))); + source.OnNext(new(Change.CreateAdd(item, 1))); + await Assert.That(item.HandlerCount).IsEqualTo(1); + + item.Raise(Watched); + await Assert.That(refreshCount).IsEqualTo(DuplicateRefreshes); + + source.OnNext(new(Change.CreateRemove(item, 1))); + await Assert.That(item.HandlerCount).IsEqualTo(1); + item.Raise(Watched); + await Assert.That(refreshCount).IsEqualTo(DuplicateRefreshes + 1); + + source.OnNext(new(Change.CreateRemove(item, 0))); + await Assert.That(item.HandlerCount).IsEqualTo(0); + } + + /// Only the watched property, or an unnamed change, produces a refresh. + /// A task representing the asynchronous test. + [Test] + public async Task PropertyFilter_PassesWatchedAndUnnamedChangesOnly() + { + using var source = new Signal>(); + var item = new CountingItem(); + var refreshCount = 0; + using var subscription = source.AutoRefresh(Watched) + .Subscribe(changes => refreshCount += CountRefreshes(changes)); + + source.OnNext(new(Change.CreateAdd(item, 0))); + item.Raise("Other"); + await Assert.That(refreshCount).IsEqualTo(0); + + item.Raise(Watched); + item.Raise(string.Empty); + await Assert.That(refreshCount).IsEqualTo(DuplicateRefreshes + 1); + } + + /// Source completion detaches every handler and completes the output. + /// A task representing the asynchronous test. + [Test] + public async Task SourceCompletion_DetachesHandlersAndCompletes() + { + using var source = new Signal>(); + var item = new CountingItem(); + var completed = false; + using var subscription = source.AutoRefresh(Watched).Subscribe(static _ => { }, static _ => { }, () => completed = true); + + source.OnNext(new(Change.CreateAdd(item, 0))); + source.OnCompleted(); + + await Assert.That(completed).IsTrue(); + await Assert.That(item.HandlerCount).IsEqualTo(0); + } + + /// A source error detaches every handler and reaches the observer. + /// A task representing the asynchronous test. + [Test] + public async Task SourceError_DetachesHandlersAndForwardsError() + { + using var source = new Signal>(); + var item = new CountingItem(); + Exception? received = null; + using var subscription = source.AutoRefresh(Watched).Subscribe(static _ => { }, ex => received = ex, static () => { }); + var failure = new InvalidOperationException("boom"); + + source.OnNext(new(Change.CreateAdd(item, 0))); + source.OnError(failure); + + await Assert.That(received).IsSameReferenceAs(failure); + await Assert.That(item.HandlerCount).IsEqualTo(0); + } + + /// A throwing observer does not leave delivery stuck, and handlers are still detached on dispose. + /// A task representing the asynchronous test. + [Test] + public async Task ThrowingObserver_DoesNotStickDelivery() + { + using var source = new Signal>(); + var item = new CountingItem(); + var calls = 0; + var subscription = source.AutoRefresh(Watched).Subscribe(ignored => + { + calls++; + if (calls == 1) + { + throw new InvalidOperationException("observer failed"); + } + }); + + try + { + source.OnNext(new(Change.CreateAdd(item, 0))); + } + catch (InvalidOperationException) + { + // The first notification throws on purpose. + } + + item.Raise(Watched); + await Assert.That(calls).IsGreaterThanOrEqualTo(1 + DuplicateRefreshes); + + subscription.Dispose(); + await Assert.That(item.HandlerCount).IsEqualTo(0); + } + + /// Property changes on several threads reach the observer one at a time. + /// A task representing the asynchronous test. + [Test] + public async Task ConcurrentPropertyChanges_AreDeliveredSerially() + { + using var source = new Signal>(); + var item = new CountingItem(); + var inside = 0; + var overlaps = 0; + var received = 0; + using var subscription = source.AutoRefresh(Watched).Subscribe(ignored => + { + if (Interlocked.Increment(ref inside) != 1) + { + _ = Interlocked.Increment(ref overlaps); + } + + _ = Interlocked.Increment(ref received); + _ = Interlocked.Decrement(ref inside); + }); + + source.OnNext(new(Change.CreateAdd(item, 0))); + var tasks = new Task[RaiserCount]; + for (var i = 0; i < tasks.Length; i++) + { + tasks[i] = Task.Run(() => + { + for (var n = 0; n < RaisesPerThread; n++) + { + item.Raise(Watched); + } + }); + } + + await Task.WhenAll(tasks); + await Assert.That(overlaps).IsEqualTo(0); + await Assert.That(received).IsEqualTo(1 + (RaiserCount * RaisesPerThread)); + } + + /// Removing items from a real list detaches their handlers. + /// A task representing the asynchronous test. + [Test] + public async Task ConnectedList_RemoveClearAndDispose_DetachHandlers() + { + using var list = new ReactiveList(); + var items = new CountingItem[ItemCount]; + for (var i = 0; i < items.Length; i++) + { + items[i] = new(); + } + + var subscription = list.Connect().AutoRefresh(Watched).Subscribe(static _ => { }); + list.AddRange(items); + await Assert.That(items[0].HandlerCount).IsEqualTo(1); + + _ = list.Remove(items[0]); + await Assert.That(items[0].HandlerCount).IsEqualTo(0); + + list.RemoveAt(0); + await Assert.That(items[1].HandlerCount).IsEqualTo(0); + + list.Clear(); + for (var i = 0; i < items.Length; i++) + { + await Assert.That(items[i].HandlerCount).IsEqualTo(0); + } + + list.Add(items[0]); + await Assert.That(items[0].HandlerCount).IsEqualTo(1); + subscription.Dispose(); + await Assert.That(items[0].HandlerCount).IsEqualTo(0); + } + + /// Notifications that arrive after the subscription ended are ignored. + /// A task representing the asynchronous test. + [Test] + public async Task Notifications_AfterTheSubscriptionEnded_AreIgnored() + { + List> received = []; + var completions = 0; + AutoRefreshSubscription subscription = new(new RecordingObserver(received, () => completions++), Watched); + var item = new CountingItem(); + + subscription.OnCompleted(); + subscription.OnNext(new(Change.CreateAdd(item, 0))); + subscription.OnError(new InvalidOperationException()); + + await Assert.That(item.HandlerCount).IsEqualTo(0); + await Assert.That(received).IsEmpty(); + await Assert.That(completions).IsEqualTo(1); + } + + /// Connecting after the subscription ended releases the source subscription at once. + /// A task representing the asynchronous test. + [Test] + public async Task Connect_AfterDispose_ReleasesTheSourceSubscription() + { + using var source = new Signal>(); + AutoRefreshSubscription subscription = new(new RecordingObserver([], static () => { }), Watched); + subscription.Dispose(); + + subscription.Connect(source); + + await Assert.That(source.HasObservers).IsFalse(); + } + + /// Removing an item that was never watched changes nothing. + /// A task representing the asynchronous test. + [Test] + public async Task Remove_ItemThatWasNeverWatched_IsIgnored() + { + using var source = new Signal>(); + var item = new CountingItem(); + using var subscription = source.AutoRefresh(Watched).Subscribe(static _ => { }); + + source.OnNext(new(Change.CreateRemove(item, 0))); + + await Assert.That(item.HandlerCount).IsEqualTo(0); + } + + /// A property change delivered to a handler that was just detached raises no refresh. + /// A task representing the asynchronous test. + [Test] + public async Task PropertyChanged_HandlerDetachedDuringTheEvent_RaisesNoRefresh() + { + using var source = new Signal>(); + var item = new CountingItem(); + var refreshCount = 0; + var subscription = source.AutoRefresh(Watched).Subscribe(changes => refreshCount += CountRefreshes(changes)); + + // This handler runs before the refresh handler and ends the subscription; the event still reaches the detached refresh handler. + item.PropertyChanged += (_, _) => subscription.Dispose(); + source.OnNext(new(Change.CreateAdd(item, 0))); + item.Raise(Watched); + + await Assert.That(refreshCount).IsEqualTo(0); + } + + /// Counts the refresh changes in a change set. + /// The change set. + /// The number of refresh changes. + private static int CountRefreshes(ChangeSet changes) + { + var count = 0; + for (var i = 0; i < changes.Count; i++) + { + if (changes[i].Reason == ChangeReason.Refresh) + { + count++; + } + } + + return count; + } + + /// An observer that records change sets and counts completions. + /// The list that receives the change sets. + /// Called when the sequence completes. + private sealed class RecordingObserver(List> received, Action onCompleted) : IObserver> + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted() => onCompleted(); + + /// + public void OnError(Exception error) + { + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnNext(ChangeSet value) => received.Add(value); + } + + /// An item that counts how many handlers are attached to its property-changed event. + private sealed class CountingItem : INotifyPropertyChanged + { + /// The attached handlers. + private PropertyChangedEventHandler? _handlers; + + /// The number of attached handlers. + private int _handlerCount; + + /// + public event PropertyChangedEventHandler? PropertyChanged + { + add + { + _ = Interlocked.Increment(ref _handlerCount); + _handlers += value; + } + + remove + { + _ = Interlocked.Decrement(ref _handlerCount); + _handlers -= value; + } + } + + /// Gets the number of attached handlers. + public int HandlerCount => Volatile.Read(ref _handlerCount); + + /// Raises the property-changed event. + /// The property name. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Raise(string propertyName) => _handlers?.Invoke(this, new(propertyName)); + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListConcurrencyFuzzTests.cs b/src/tests/ReactiveList.Tests/ReactiveListConcurrencyFuzzTests.cs new file mode 100644 index 00000000..0de7716d --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListConcurrencyFuzzTests.cs @@ -0,0 +1,508 @@ +// 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. + +using System.Collections.Concurrent; +using System.Security.Cryptography; +using CsCheck; + +namespace ReactiveList.Tests; + +/// Linearizability and multi-thread stress tests for . +public class ReactiveListConcurrencyFuzzTests +{ + /// The number of random operation schedules checked for linearizability. + private const int LinearizabilityIterations = 150; + + /// The number of threads CsCheck uses to run schedules. + private const int LinearizabilityThreads = 4; + + /// The largest item value used by the linearizability operations. + private const int MaxValue = 5; + + /// The largest divisor used by the removal predicate. + private const int MaxDivisor = 3; + + /// The number of writer tasks in the stress tests. + private const int Writers = 4; + + /// The number of reader tasks in the stress tests. + private const int Readers = 3; + + /// The number of operations each writer performs. + private const int WriterOperations = 4000; + + /// The number of distinct item values in the stress tests. + private const int ValueCount = 9; + + /// The number of reads each reader performs. + private const int ReaderOperations = 1500; + + /// The timeout, in milliseconds, for waits that must not deadlock. + private const int DeadlockTimeoutMilliseconds = 5000; + + /// The number of disposing tasks in the dispose race test. + private const int Disposers = 4; + + /// The number of operations per writer in the notification-order test. + private const int OrderedOperations = 600; + + /// The offset that separates the values written by different writers. + private const int WriterValueStride = 100_000; + + /// The first sample item. + private const int First = 1; + + /// The second sample item and the pair size. + private const int Second = 2; + + /// The third sample item. + private const int Third = 3; + + /// The mutations that keep every value's multiplicity even. + private static readonly Action, string>[] PairOperations = + [ + static (list, value) => list.AddRange([value, value]), + static (list, value) => list.RemoveMany(item => item == value), + static (list, value) => list.InsertRange(0, [value, value]), + static (list, value) => list.Edit(editable => + { + editable.Add(value); + editable.Add(value); + }), + static (list, value) => list.ReplaceAll([value, value, value, value]), + static (list, value) => list.Remove([value, value]), + static (list, _) => list.Clear(), + ]; + + /// Checks that parallel mutations always match some sequential ordering of the same operations. + /// A completed task. + [Test] + public Task Parallel_Mutations_AreLinearizable() + { + var value = Gen.Int[0, MaxValue]; + var values = value.Array[0, MaxValue]; + Gen.Const(static () => (new ReactiveList(), (List)[])).SampleParallel( + value.Operation, List>( + static v => $"Add({v})", + static (list, v) => list.Add(v), + static (model, v) => model.Add(v)), + value.Operation, List>( + static v => $"Insert(0, {v})", + static (list, v) => list.Insert(0, v), + static (model, v) => model.Insert(0, v)), + value.Operation, List>( + static v => $"Remove({v})", + static (list, v) => list.Remove(v), + static (model, v) => model.Remove(v)), + Gen.Int[1, MaxDivisor].Operation, List>( + static k => $"RemoveMany(v % {k} == 0)", + static (list, k) => list.RemoveMany(v => v % k == 0), + static (model, k) => model.RemoveAll(v => v % k == 0)), + values.Operation, List>( + static a => $"AddRange([{string.Join(",", a)}])", + static (list, a) => list.AddRange(a), + static (model, a) => model.AddRange(a)), + values.Operation, List>( + static a => $"ReplaceAll([{string.Join(",", a)}])", + static (list, a) => list.ReplaceAll(a), + ReplaceAll), + equal: static (list, model) => list.ToArray().AsSpan().SequenceEqual(model.ToArray()) && list.Count == model.Count, + iter: LinearizabilityIterations, + threads: LinearizabilityThreads); + return Task.CompletedTask; + } + + /// Checks that readers never see torn state while writers apply atomic pair operations. + /// A task representing the asynchronous test. + [Test] + public async Task Stress_ReadersNeverObserveTornState() + { + using var list = new ReactiveList(); + var failures = new ConcurrentQueue(); + var tasks = new List(); + for (var writer = 0; writer < Writers; writer++) + { + tasks.Add(Task.Run(() => RunWriter(list, failures))); + } + + for (var reader = 0; reader < Readers; reader++) + { + tasks.Add(Task.Run(() => RunReader(list, failures))); + } + + await Task.WhenAll(tasks); + + await Assert.That(failures).IsEmpty(); + await Assert.That(HasEvenMultiplicities(list.ToArray())).IsTrue(); + } + + /// Checks that the stream replays, in order and without overlap, to the final list under concurrent writers. + /// A task representing the asynchronous test. + [Test] + public async Task Stress_StreamAndCollectionChanged_ReplayToFinalState() + { + using var list = new ReactiveList(); + var streamShadow = new List(); + var collectionShadow = new List(); + var overlaps = 0; + var active = 0; + using var subscription = list.Stream.Subscribe(notification => + { + if (Interlocked.Increment(ref active) != 1) + { + _ = Interlocked.Increment(ref overlaps); + } + + ReplayStream(streamShadow, notification); + _ = Interlocked.Decrement(ref active); + }); + list.CollectionChanged += (_, args) => ReplayCollection(collectionShadow, args, list.ToArray); + + var tasks = new List(); + for (var writer = 0; writer < Writers; writer++) + { + var offset = writer * WriterValueStride; + tasks.Add(Task.Run(() => RunOrderedWriter(list, offset))); + } + + await Task.WhenAll(tasks); + + var expected = list.ToArray(); + await Assert.That(overlaps).IsEqualTo(0); + await Assert.That(streamShadow.ToArray()).IsEquivalentTo(expected, CollectionOrdering.Matching); + await Assert.That(collectionShadow.ToArray()).IsEquivalentTo(expected, CollectionOrdering.Matching); + } + + /// Checks that concurrent disposal completes the stream exactly once and never throws anything but disposal errors. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_Concurrent_CompletesOnceWithoutUnexpectedErrors() + { + var list = new ReactiveList([First, Second, Third]); + var completions = 0; + var unexpected = new ConcurrentQueue(); + using var subscription = list.Stream.Subscribe(static _ => { }, static _ => { }, () => Interlocked.Increment(ref completions)); + + var tasks = new List(); + for (var disposer = 0; disposer < Disposers; disposer++) + { + tasks.Add(Task.Run(list.Dispose)); + } + + for (var writer = 0; writer < Writers; writer++) + { + tasks.Add(Task.Run(() => AddUntilDisposed(list, unexpected))); + } + + await Task.WhenAll(tasks); + + await Assert.That(unexpected).IsEmpty(); + await Assert.That(Volatile.Read(ref completions)).IsEqualTo(1); + await Assert.That(list.IsDisposed).IsTrue(); + } + + /// Checks that a handler can mutate the list and that its changes are delivered after the current notification. + /// A task representing the asynchronous test. + [Test] + public async Task Reentrancy_HandlerMutatingList_DeliversInOrderWithoutDeadlock() + { + using var list = new ReactiveList(); + var seen = new List(); + using var subscription = list.Stream.Subscribe(notification => + { + seen.Add(notification.Item); + if (notification.Item == 1) + { + list.Add(Second); + } + }); + + list.Add(1); + + await Assert.That(seen.ToArray()).IsEquivalentTo([First, Second], CollectionOrdering.Matching); + await Assert.That(list.ToArray()).IsEquivalentTo([First, Second], CollectionOrdering.Matching); + } + + /// Checks that a handler waiting for another thread's mutation does not deadlock that thread. + /// A task representing the asynchronous test. + [Test] + public async Task CrossThread_HandlerWaitingForAnotherWriter_DoesNotDeadlock() + { + using var list = new ReactiveList(); + using var otherDone = new ManualResetEventSlim(); + var waitResult = false; + using var subscription = list.Stream.Subscribe(notification => + { + if (notification.Item != 1) + { + return; + } + + var other = Task.Run(() => + { + list.Add(Second); + otherDone.Set(); + }); + waitResult = otherDone.Wait(DeadlockTimeoutMilliseconds); + GC.KeepAlive(other); + }); + + list.Add(1); + + await Assert.That(waitResult).IsTrue(); + await Assert.That(list.ToArray()).IsEquivalentTo([First, Second], CollectionOrdering.Matching); + } + + /// Checks that an exception thrown by a handler leaves the list consistent and later notifications flowing. + /// A task representing the asynchronous test. + [Test] + public async Task HandlerException_LeavesListConsistentAndNotificationsFlowing() + { + using var list = new ReactiveList(); + var received = new List(); + var throwOnce = true; + list.CollectionChanged += (_, _) => + { + if (!throwOnce) + { + return; + } + + throwOnce = false; + throw new InvalidOperationException("handler failure"); + }; + using var subscription = list.Stream.Subscribe(notification => received.Add(notification.Item)); + + Action first = () => list.Add(1); + await Assert.That(first).Throws(); + list.Add(Second); + + await Assert.That(list.ToArray()).IsEquivalentTo([First, Second], CollectionOrdering.Matching); + await Assert.That(received.ToArray()).IsEquivalentTo([First, Second], CollectionOrdering.Matching); + } + + /// Checks that mutating the list from inside its own edit action is rejected. + /// A task representing the asynchronous test. + [Test] + public async Task Edit_ReentrantMutation_IsRejected() + { + using var list = new ReactiveList([1]); + + Action edit = () => list.Edit(_ => list.Add(Second)); + + await Assert.That(edit).Throws(); + await Assert.That(list.ToArray()).IsEquivalentTo([1], CollectionOrdering.Matching); + } + + /// Replaces the model contents. + /// The model. + /// The new contents. + private static void ReplaceAll(List model, int[] values) + { + model.Clear(); + model.AddRange(values); + } + + /// Tests that every distinct value appears an even number of times. + /// The items. + /// when all multiplicities are even. + private static bool HasEvenMultiplicities(string[] items) + { + var counts = new Dictionary(StringComparer.Ordinal); + foreach (var item in items) + { + counts[item] = counts.GetValueOrDefault(item) + 1; + } + + return counts.Values.All(static count => count % Second == 0); + } + + /// Copies the list through a single enumerator. + /// The shared list. + /// The items one enumerator produced. + private static string[] EnumerateOnce(ReactiveList list) + { + // A spread or LINQ copy reads Count and then enumerates, which is two separate reads under concurrent writers. + var items = new List(); + foreach (var item in list) + { + items.Add(item); + } + + return [.. items]; + } + + /// Applies pair-preserving mutations. + /// The shared list. + /// Receives unexpected failures. + private static void RunWriter(ReactiveList list, ConcurrentQueue failures) + { + try + { + for (var i = 0; i < WriterOperations; i++) + { + ApplyPairOperation(list); + } + } + catch (Exception ex) + { + failures.Enqueue($"writer: {ex}"); + } + } + + /// Applies one randomly chosen operation that keeps every value's multiplicity even. + /// The shared list. + private static void ApplyPairOperation(ReactiveList list) + { + var value = RandomNumberGenerator.GetInt32(1, ValueCount + 1).ToString(); + PairOperations[RandomNumberGenerator.GetInt32(PairOperations.Length)](list, value); + } + + /// Reads the list through every unlocked-looking API and validates what it sees. + /// The shared list. + /// Receives unexpected failures. + private static void RunReader(ReactiveList list, ConcurrentQueue failures) + { + try + { + for (var i = 0; i < ReaderOperations; i++) + { + if (!HasEvenMultiplicities(list.ToArray()) || !HasEvenMultiplicities(EnumerateOnce(list))) + { + failures.Enqueue("a snapshot had an odd multiplicity"); + } + + ReadByIndex(list, failures); + } + } + catch (Exception ex) + { + failures.Enqueue($"reader: {ex}"); + } + } + + /// Reads items through the count and indexer while writers run. + /// The shared list. + /// Receives unexpected failures. + private static void ReadByIndex(ReactiveList list, ConcurrentQueue failures) + { + var count = list.Count; + for (var index = 0; index < count; index++) + { + try + { + if (list[index] is null) + { + failures.Enqueue("indexer returned null for a list that never holds null"); + } + } + catch (ArgumentOutOfRangeException) + { + // The list legitimately shrank between reading Count and reading the item. + return; + } + } + } + + /// Adds and inserts distinct values and removes some of them again. + /// The shared list. + /// The first value this writer uses. + private static void RunOrderedWriter(ReactiveList list, int offset) + { + for (var i = 0; i < OrderedOperations; i++) + { + var value = offset + i; + if (i % MaxDivisor == 0) + { + list.Insert(0, value); + } + else + { + list.Add(value); + } + + if (i % ValueCount == 0) + { + _ = list.Remove(value); + } + } + } + + /// Adds items until the list is disposed. + /// The shared list. + /// Receives unexpected exceptions. + private static void AddUntilDisposed(ReactiveList list, ConcurrentQueue unexpected) + { + try + { + for (var i = 0; i < WriterOperations; i++) + { + list.Add(i); + } + } + catch (ObjectDisposedException) + { + // Mutating a disposed list is the documented outcome. + } + catch (Exception ex) + { + unexpected.Enqueue(ex); + } + } + + /// Replays a stream notification onto a shadow list. + /// The shadow list. + /// The notification. + private static void ReplayStream(List shadow, CacheNotify notification) + { + switch (notification.Action) + { + case CacheAction.Added: + { + shadow.Insert(notification.CurrentIndex, notification.Item); + break; + } + + case CacheAction.Removed: + { + shadow.RemoveAt(notification.CurrentIndex); + break; + } + + default: + { + break; + } + } + } + + /// Replays a collection-changed notification onto a shadow list. + /// The shadow list. + /// The notification arguments. + /// Reads the authoritative contents for a reset. + private static void ReplayCollection(List shadow, NotifyCollectionChangedEventArgs args, Func resync) + { + switch (args.Action) + { + case NotifyCollectionChangedAction.Add: + { + shadow.Insert(args.NewStartingIndex, (int)args.NewItems![0]!); + break; + } + + case NotifyCollectionChangedAction.Remove: + { + shadow.RemoveAt(args.OldStartingIndex); + break; + } + + default: + { + shadow.Clear(); + shadow.AddRange(resync()); + break; + } + } + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListConcurrentCreationTests.cs b/src/tests/ReactiveList.Tests/ReactiveListConcurrentCreationTests.cs new file mode 100644 index 00000000..74e83572 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListConcurrentCreationTests.cs @@ -0,0 +1,198 @@ +// 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. + +namespace ReactiveList.Tests; + +/// +/// Checks the lazily created signals, mirrors and subscriptions of in the states a second thread +/// leaves behind when it wins a creation race. +/// +public class ReactiveListConcurrentCreationTests +{ + /// A value carried by the test items. + private const int Value = 7; + + /// The count of the first two items of a three item array. + private const int PartialCount = 2; + + /// A sequence number above any a fresh mirror holds. + private const long NewerSequence = 10; + + /// A sequence number at or below the one a mirror already holds. + private const long OlderSequence = 5; + + /// A failure raised while subscribing is treated as the end of the stream once the list is disposed. + /// A task representing the asynchronous test. + [Test] + public async Task TrySubscribe_SourceDisposedWhileSubscribing_ReturnsNullOnlyForADisposedList() + { + DisposedObservable failing = new(); + var observer = new CountingObserver(); + var disposed = 1; + var live = 0; + + var whenDisposed = SignalSubscription.TrySubscribe(failing, observer, ref disposed); + ObjectDisposedException? escaped = null; + try + { + _ = SignalSubscription.TrySubscribe(failing, observer, ref live); + } + catch (ObjectDisposedException ex) + { + escaped = ex; + } + + await Assert.That(whenDisposed).IsNull(); + await Assert.That(escaped).IsNotNull(); + } + + /// A pooled batch is copied to an array of exactly its count. + /// A task representing the asynchronous test. + [Test] + public async Task GetItemsFromNotification_PartialBatch_CopiesOnlyTheCountedItems() + { + using PooledBatch batch = new([1, PartialCount, Value], PartialCount, ReturnToPool: false); + CacheNotify notification = new(CacheAction.Added, default, batch); + + var items = ReactiveList.GetItemsFromNotification(notification); + + await Assert.That(items).IsEquivalentTo([1, PartialCount], CollectionOrdering.Matching); + } + + /// A change the items mirror already reflects is skipped. + /// A task representing the asynchronous test. + [Test] + public async Task ApplyToItems_ChangeAtOrBelowTheAppliedSequence_IsSkipped() + { + RangeObservableCollection mirror = new() { AppliedSequence = NewerSequence }; + ListChange change = new(ListChangeKind.Added, OlderSequence, Value, default, null, null, 0, -1, null); + + ReactiveList.ApplyToItems(mirror, in change); + + await Assert.That(mirror).IsEmpty(); + await Assert.That(mirror.AppliedSequence).IsEqualTo(NewerSequence); + } + + /// A pipeline another thread installed first is returned and the new signal is discarded. + /// A task representing the asynchronous test. + [Test] + public async Task CreateStreamPipeline_AlreadyInstalled_ReturnsTheInstalledSignal() + { + using ReactiveList list = []; + Signal? slot = new(); + var installed = slot; + + var result = list.CreateStreamPipeline(ref slot); + + await Assert.That(result).IsSameReferenceAs(installed); + } + + /// A current-items signal another thread created first is returned. + /// A task representing the asynchronous test. + [Test] + public async Task CreateCurrentSignal_CalledTwice_ReturnsTheFirstSignal() + { + using ReactiveList list = [Value]; + + var first = list.CreateCurrentSignal(); + var second = list.CreateCurrentSignal(); + + await Assert.That(second).IsSameReferenceAs(first); + } + + /// A current-items signal created after the list was disposed is already completed. + /// A task representing the asynchronous test. + [Test] + public async Task CreateCurrentSignal_ListDisposed_ReturnsACompletedSignal() + { + ReactiveList list = [Value]; + list.Dispose(); + var completed = false; + + var signal = list.CreateCurrentSignal(); + using var subscription = signal.Subscribe(static _ => { }, static _ => { }, () => completed = true); + + await Assert.That(completed).IsTrue(); + } + + /// A history mirror another thread created first is returned. + /// A task representing the asynchronous test. + [Test] + public async Task EnsureHistoryMirror_CalledTwice_ReturnsTheFirstMirror() + { + using ReactiveList list = [Value]; + RangeObservableCollection? slot = null; + + var first = list.EnsureHistoryMirror(ref slot, ReactiveList.HistoryKind.Added); + var second = list.EnsureHistoryMirror(ref slot, ReactiveList.HistoryKind.Added); + + await Assert.That(second).IsSameReferenceAs(first); + } + + /// A stale refresh that another thread already queued does nothing. + /// A task representing the asynchronous test. + [Test] + public async Task QueueStaleRefresh_NothingStale_ChangesNothing() + { + using ReactiveList list = [Value]; + + list.QueueStaleRefresh(); + + await Assert.That(list.Count).IsEqualTo(1); + } + + /// Restoring runtime state after deserialization recounts the items. + /// A task representing the asynchronous test. + [Test] + public async Task OnDeserialized_RestoresTheCount() + { + using ReactiveList list = [Value, Value]; + + list.OnDeserialized(default); + + await Assert.That(list.Count).IsEqualTo(PartialCount); + } + + /// Releasing a deferral from inside an edit callback is rejected. + /// A task representing the asynchronous test. + [Test] + public async Task ResumeNotifications_FromInsideEditCallback_IsRejected() + { + using ReactiveList list = [Value]; + var deferral = list.DeferNotifications(); + + await Assert.That(() => list.Edit(_ => deferral.Dispose())).Throws(); + + deferral.Dispose(); + } + + /// An observable whose signal was disposed, so every subscription fails. + private sealed class DisposedObservable : IObservable + { + /// + public IDisposable Subscribe(IObserver observer) => throw new ObjectDisposedException(nameof(DisposedObservable)); + } + + /// An observer that ignores everything it receives. + private sealed class CountingObserver : IObserver + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnNext(int value) + { + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnError(Exception error) + { + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted() + { + } + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListConnectTests.cs b/src/tests/ReactiveList.Tests/ReactiveListConnectTests.cs index c9e805d9..c2bef0ec 100644 --- a/src/tests/ReactiveList.Tests/ReactiveListConnectTests.cs +++ b/src/tests/ReactiveList.Tests/ReactiveListConnectTests.cs @@ -106,10 +106,7 @@ public async Task Connect_EmitsRemoveChanges_WhenItemsRemoved() await Assert.That(receivedChanges[0][0].Current).IsEqualTo(TestData.TestValueTwo); } - /// - /// Connect emits clear changes when collection is cleared. - /// Clear emits individual Remove changes for each cleared item (consistent with DynamicData behavior). - /// + /// Connect emits one Remove change for each cleared item when the collection is cleared. /// A task representing the asynchronous test. [Test] public async Task Connect_EmitsClearChanges_WhenCleared() @@ -123,7 +120,7 @@ public async Task Connect_EmitsClearChanges_WhenCleared() // Act list.Clear(); - // Assert - Clear emits Remove changes for each item (DynamicData compatible behavior) + // Assert - Clear emits Remove changes for each item await Assert.That(receivedChanges).Count().IsEqualTo(1); await Assert.That(receivedChanges[0].Count).IsEqualTo(TestData.TestValueThree); // One Remove change per cleared item await Assert.That(receivedChanges[0].Removes).IsEqualTo(TestData.TestValueThree); diff --git a/src/tests/ReactiveList.Tests/ReactiveListCoverageTests.cs b/src/tests/ReactiveList.Tests/ReactiveListCoverageTests.cs index 447d93ee..575e842f 100644 --- a/src/tests/ReactiveList.Tests/ReactiveListCoverageTests.cs +++ b/src/tests/ReactiveList.Tests/ReactiveListCoverageTests.cs @@ -86,8 +86,8 @@ public async Task NonGenericCollectionMembers_ShouldValidateAndMutate() ((ICollection)invalidFixture).CopyTo(new string[1], 0); }; - await Assert.That(addWrongType).Throws(); - await Assert.That(insertWrongType).Throws(); + await Assert.That(addWrongType).Throws(); + await Assert.That(insertWrongType).Throws(); await Assert.That(copyNull).Throws().WithParameterName(TestData.ArrayParameterName); await Assert.That(copyMultiDimensional).Throws().WithParameterName(TestData.ArrayParameterName); await Assert.That(copyNonZeroLowerBound).Throws().WithParameterName(TestData.ArrayParameterName); @@ -268,7 +268,7 @@ public async Task CollectionChanged_ShouldUseSpecificActionsForSingleChangesAndR await Assert.That(events[TestData.TestValueTwo].NewStartingIndex).IsEqualTo(1); } - /// ReplaceAll should emit old and new batches when either side is populated. + /// ReplaceAll should emit a clear followed by the new contents, and skip the contents when they are empty. /// A task representing the asynchronous test. [Test] public async Task ReplaceAll_ShouldEmitOldAndNewBatchesWhenPresent() @@ -285,7 +285,7 @@ public async Task ReplaceAll_ShouldEmitOldAndNewBatchesWhenPresent() fixture.ReplaceAll([]); await Assert.That(fixture.Count).IsEqualTo(0); - await Assert.That(actions).IsEquivalentTo([CacheAction.BatchAdded, CacheAction.BatchRemoved], CollectionOrdering.Matching); + await Assert.That(actions).IsEquivalentTo([CacheAction.Cleared, CacheAction.BatchAdded, CacheAction.Cleared], CollectionOrdering.Matching); } /// Subscribe should delegate to CurrentItems and Dispose should release resources. @@ -304,10 +304,6 @@ public async Task SubscribeAndDispose_ShouldUseCurrentItemsAndReleaseResources() fixture.Dispose(); await Assert.That(fixture.IsDisposed).IsTrue(); - - using var disposeHarness = new DisposeHarness(); - disposeHarness.DisposeWithoutManagedResources(); - await Assert.That(disposeHarness.IsDisposed).IsFalse(); } /// Public notification paths should preserve stream behavior and handle empty batch no-ops. @@ -364,16 +360,6 @@ private static void AddSnapshot(List snapshots, IEnumerable items) snapshots.Add([.. snapshot]); } - /// Provides DisposeHarness. - /// The T type. - private sealed class DisposeHarness : ReactiveList - where T : notnull - { - /// Provides DisposeWithoutManagedResources. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void DisposeWithoutManagedResources() => Dispose(false); - } - /// Provides RecordingObserver. /// The T type. private sealed class RecordingObserver : IObserver> diff --git a/src/tests/ReactiveList.Tests/ReactiveListCurrentItemsRaceTests.cs b/src/tests/ReactiveList.Tests/ReactiveListCurrentItemsRaceTests.cs new file mode 100644 index 00000000..1d945d5c --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListCurrentItemsRaceTests.cs @@ -0,0 +1,57 @@ +// 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. + +namespace ReactiveList.Tests; + +/// A CurrentItems subscriber must end up with the latest contents even when it attaches while a change is being delivered. +public sealed class ReactiveListCurrentItemsRaceTests +{ + /// The number of one-change-versus-one-subscribe rounds. + private const int Rounds = 20_000; + + /// The number of threads that start each round together. + private const int Participants = 2; + + /// A subscriber that attaches while the only change of the round is being delivered holds the contents after that change. + /// A task representing the asynchronous test. + [Test] + public async Task CurrentItems_SubscribeWhileAChangeIsDelivered_HoldsTheLatestContents() + { + using var list = new ReactiveList(); + + // The handler makes every change go through delivery even when CurrentItems has no observer. + list.CollectionChanged += static (_, _) => { }; + list.CurrentItems.Subscribe(static _ => { }).Dispose(); + + using var barrier = new Barrier(Participants); + var misses = 0; + var writer = Task.Run(() => + { + for (var round = 0; round < Rounds; round++) + { + barrier.SignalAndWait(); + list.Add(round); + barrier.SignalAndWait(); + } + }); + var subscriber = Task.Run(() => + { + for (var round = 0; round < Rounds; round++) + { + var recorder = new LiveQueryRecorder>(); + barrier.SignalAndWait(); + using var subscription = list.CurrentItems.Subscribe(recorder); + barrier.SignalAndWait(); + if (recorder.Last?.Count() != list.Count) + { + _ = Interlocked.Increment(ref misses); + } + } + }); + + await Task.WhenAll(writer, subscriber); + + await Assert.That(misses).IsEqualTo(0); + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListDeliveryTests.cs b/src/tests/ReactiveList.Tests/ReactiveListDeliveryTests.cs new file mode 100644 index 00000000..211366ba --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListDeliveryTests.cs @@ -0,0 +1,441 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Tests when and in what order delivers notifications to its observers. +public class ReactiveListDeliveryTests +{ + /// The message of the exception thrown by the failing handlers. + private const string HandlerFailure = "handler failed"; + + /// An item value used by single-step mutations. + private const int Probe = 10; + + /// The number of stream notifications that announce a rewrite: a clear and the new contents. + private const int RewriteNotifications = 2; + + /// The base of the values added in ranges. + private const int Batch = 20; + + /// The base of the values that replace the whole list. + private const int Replacement = 30; + + /// The total number of items added by all writers. + private const int TotalItems = WriterCount * ItemsPerWriter; + + /// The number of writer threads in the ordering test. + private const int WriterCount = 4; + + /// The number of items added by each writer. + private const int ItemsPerWriter = 250; + + /// The number of lists the handover test creates. + private const int HandoverRounds = 200; + + /// The number of items each writer adds in the handover test. + private const int HandoverItemsPerWriter = 50; + + /// The first item of the reentrancy tests. + private const int First = 1; + + /// The item added from inside a handler. + private const int Nested = 2; + + /// A list that has observers on every notification surface sees them all before each mutation returns. + /// A task representing the asynchronous test. + [Test] + public async Task SingleThread_DeliversEveryNotificationBeforeTheCallReturns() + { + using var list = new ReactiveList([First, Nested, Nested + 1]); + using var recorder = new Recorder(list); + + foreach (var (name, mutate) in CreateSteps()) + { + var before = recorder.Snapshot(); + mutate(list); + var after = recorder.Snapshot(); + + await Assert.That(after.Stream).IsGreaterThan(before.Stream).Because(name); + await Assert.That(after.Collection).IsGreaterThan(before.Collection).Because(name); + await Assert.That(after.Property).IsGreaterThan(before.Property).Because(name); + await Assert.That(after.Current).IsGreaterThan(before.Current).Because(name); + await Assert.That(after.Changed).IsGreaterThan(before.Changed).Because(name); + } + } + + /// Added and Removed observables fire for the matching mutations before the call returns. + /// A task representing the asynchronous test. + [Test] + public async Task SingleThread_AddedAndRemovedObservablesFireSynchronously() + { + using var list = new ReactiveList(); + using var recorder = new Recorder(list); + + list.Add(First); + await Assert.That(recorder.Snapshot().Added).IsEqualTo(1); + + _ = list.Remove(First); + await Assert.That(recorder.Snapshot().Removed).IsEqualTo(1); + } + + /// Concurrent writers are announced in the order their mutations were applied. + /// A task representing the asynchronous test. + [Test] + public async Task ConcurrentWriters_AreDeliveredInMutationOrder() + { + using var list = new ReactiveList(); + var streamed = new List(); + var indexes = new List(); + var propertyChanges = 0; + using var subscription = list.Stream.Subscribe(notification => streamed.Add(notification.Item)); + list.CollectionChanged += (sender, args) => indexes.Add(args.NewStartingIndex); + list.PropertyChanged += (sender, args) => propertyChanges++; + + var tasks = new Task[WriterCount]; + for (var writer = 0; writer < tasks.Length; writer++) + { + var offset = writer * ItemsPerWriter; + tasks[writer] = Task.Run(() => + { + for (var i = 0; i < ItemsPerWriter; i++) + { + list.Add(offset + i); + } + }); + } + + await Task.WhenAll(tasks); + + await Assert.That(streamed.Count).IsEqualTo(TotalItems); + await Assert.That(streamed).IsEquivalentTo(list.ToArray(), CollectionOrdering.Matching); + await Assert.That(indexes).IsEquivalentTo(Enumerable.Range(0, TotalItems), CollectionOrdering.Matching); + await Assert.That(propertyChanges).IsGreaterThanOrEqualTo(TotalItems); + } + + /// Writers that keep handing delivery to each other never leave a committed change undelivered. + /// A task representing the asynchronous test. + [Test] + public async Task ConcurrentWriters_HandingOverDelivery_LoseNoNotification() + { + for (var round = 0; round < HandoverRounds; round++) + { + using var list = new ReactiveList(); + var streamed = 0; + var lastVersion = 0L; + var inOrder = true; + using var subscription = list.VersionedStream.Subscribe(notification => + { + streamed++; + inOrder &= notification.Version > lastVersion; + lastVersion = notification.Version; + }); + + var tasks = new Task[WriterCount]; + for (var writer = 0; writer < tasks.Length; writer++) + { + tasks[writer] = Task.Run(() => + { + for (var i = 0; i < HandoverItemsPerWriter; i++) + { + list.Add(i); + } + }); + } + + await Task.WhenAll(tasks); + + await Assert.That(streamed).IsEqualTo(WriterCount * HandoverItemsPerWriter).Because($"round {round}"); + await Assert.That(inOrder).IsTrue().Because($"round {round}"); + } + } + + /// A handler that mutates the list has its nested notifications delivered after the current one, to every observer, in order. + /// A task representing the asynchronous test. + [Test] + public async Task ReentrantMutation_IsDeliveredAfterTheCurrentNotificationInOrder() + { + using var list = new ReactiveList(); + var mutator = new List(); + var bystander = new List(); + var collection = new List(); + var bystanderSawNestedInsideHandler = false; + var nestedCallReturned = false; + using var mutatorSubscription = list.Stream.Subscribe(notification => + { + mutator.Add(notification.Item); + if (notification.Item != First) + { + return; + } + + list.Add(Nested); + nestedCallReturned = true; + bystanderSawNestedInsideHandler = bystander.Contains(Nested); + }); + using var bystanderSubscription = list.Stream.Subscribe(notification => bystander.Add(notification.Item)); + list.CollectionChanged += (sender, args) => collection.Add((int)args.NewItems![0]!); + + list.Add(First); + + await Assert.That(nestedCallReturned).IsTrue(); + await Assert.That(bystanderSawNestedInsideHandler).IsFalse(); + await Assert.That(mutator).IsEquivalentTo([First, Nested], CollectionOrdering.Matching); + await Assert.That(bystander).IsEquivalentTo([First, Nested], CollectionOrdering.Matching); + await Assert.That(collection).IsEquivalentTo([First, Nested], CollectionOrdering.Matching); + await Assert.That(list.ToArray()).IsEquivalentTo([First, Nested], CollectionOrdering.Matching); + } + + /// A throwing handler reaches the caller, does not stop the other observers, and leaves delivery working. + /// A task representing the asynchronous test. + [Test] + public async Task ThrowingHandler_ReachesCallerAndDeliveryContinues() + { + using var list = new ReactiveList(); + var streamed = new List(); + var propertyChanges = 0; + var calls = 0; + using var subscription = list.Stream.Subscribe(notification => streamed.Add(notification.Item)); + list.PropertyChanged += (sender, args) => propertyChanges++; + list.CollectionChanged += (sender, args) => + { + calls++; + if (calls == 1) + { + throw new InvalidOperationException(HandlerFailure); + } + }; + + var thrown = Assert.Throws(() => list.Add(First)); + await Assert.That(thrown.Message).IsEqualTo(HandlerFailure); + await Assert.That(streamed).IsEquivalentTo([First], CollectionOrdering.Matching); + await Assert.That(propertyChanges).IsGreaterThan(0); + + list.Add(Nested); + await Assert.That(streamed).IsEquivalentTo([First, Nested], CollectionOrdering.Matching); + await Assert.That(calls).IsEqualTo(Nested); + } + + /// A handler that throws while a nested change is queued still gets the nested change delivered and the error reaches the original caller. + /// A task representing the asynchronous test. + [Test] + public async Task ThrowingHandler_WithQueuedNestedChange_DeliversNestedAndRethrowsToOuterCaller() + { + using var list = new ReactiveList(); + var streamed = new List(); + using var subscription = list.Stream.Subscribe(notification => streamed.Add(notification.Item)); + list.CollectionChanged += (sender, args) => + { + if ((int)args.NewItems![0]! != First) + { + return; + } + + list.Add(Nested); + throw new InvalidOperationException(HandlerFailure); + }; + + _ = Assert.Throws(() => list.Add(First)); + + await Assert.That(streamed).IsEquivalentTo([First, Nested], CollectionOrdering.Matching); + } + + /// After Dispose returns nothing more is delivered, even for changes that were queued behind the current notification. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_FromHandler_DropsQueuedChangesAndCompletesOnce() + { + var list = new ReactiveList(); + var streamed = new List(); + var completions = 0; + var disposedReturned = false; + var afterDispose = 0; + using var subscription = list.Stream.Subscribe( + notification => + { + streamed.Add(notification.Item); + if (disposedReturned) + { + afterDispose++; + } + }, + static _ => { }, + () => completions++); + list.CollectionChanged += (sender, args) => + { + list.Add(Nested); + list.Dispose(); + disposedReturned = true; + }; + + list.Add(First); + + await Assert.That(streamed.Count).IsEqualTo(0); + await Assert.That(afterDispose).IsEqualTo(0); + await Assert.That(completions).IsEqualTo(1); + await Assert.That(list.IsDisposed).IsTrue(); + } + + /// Disposing an idle list completes its observables once and later mutations throw without notifying. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_StopsAllDelivery() + { + var list = new ReactiveList(); + using var recorder = new Recorder(list); + list.Add(First); + var before = recorder.Snapshot(); + + list.Dispose(); + list.Dispose(); + + _ = Assert.Throws(() => list.Add(Nested)); + var after = recorder.Snapshot(); + await Assert.That(after.Stream).IsEqualTo(before.Stream); + await Assert.That(after.Collection).IsEqualTo(before.Collection); + await Assert.That(after.Property).IsEqualTo(before.Property); + await Assert.That(after.Completions).IsEqualTo(1); + } + + /// An edit whose changes cancel out announces nothing, while an edit with a net change announces the rewrite as a clear plus the new contents. + /// A task representing the asynchronous test. + [Test] + public async Task Edit_AnnouncesOnlyTheNetChange() + { + using var list = new ReactiveList([1, Nested]); + using var recorder = new Recorder(list); + var start = recorder.Snapshot(); + + list.Edit(static editor => + { + editor.Add(Probe); + _ = editor.Remove(Probe); + }); + var afterNetZero = recorder.Snapshot(); + await Assert.That(afterNetZero.Stream).IsEqualTo(start.Stream); + await Assert.That(afterNetZero.Collection).IsEqualTo(start.Collection); + + list.Edit(static editor => editor.Add(Nested + 1)); + var afterNetChange = recorder.Snapshot(); + await Assert.That(afterNetChange.Stream).IsEqualTo(start.Stream + RewriteNotifications); + await Assert.That(afterNetChange.Collection).IsEqualTo(start.Collection + 1); + } + + /// Creates one mutation for each way of changing a list. + /// The named mutations, which are valid to run in this order against a three-item list. + private static (string Name, Action> Mutate)[] CreateSteps() => + [ + ("Add", static l => l.Add(Probe)), + ("Insert", static l => l.Insert(0, Probe + 1)), + ("Remove", static l => _ = l.Remove(Probe)), + ("RemoveAt", static l => l.RemoveAt(0)), + ("Move", static l => l.Move(0, 1)), + ("Update", static l => l.Update(First, Probe + Nested)), + ("AddRange", static l => l.AddRange([Batch, Batch + 1])), + ("InsertRange", static l => l.InsertRange(0, [Batch + Nested, Batch + Nested + 1])), + ("RemoveRange", static l => l.RemoveRange(0, Nested)), + ("ReplaceAll", static l => l.ReplaceAll([Replacement, Replacement + 1, Replacement + Nested])), + ("Indexer", static l => l[0] = Replacement + Nested + 1), + ("RemoveMany", static l => _ = l.RemoveMany(static value => value > Replacement + 1)), + ("Edit", static l => l.Edit(static editor => editor.Add(Replacement + Batch))), + ("Clear", static l => l.Clear()), + ]; + + /// A snapshot of the recorder counters. + /// The stream notifications. + /// The collection-changed events. + /// The property-changed events. + /// The current-items snapshots. + /// The added batches. + /// The removed batches. + /// The changed batches. + /// The stream completions. + private readonly record struct Counts(int Stream, int Collection, int Property, int Current, int Added, int Removed, int Changed, int Completions); + + /// Counts the notifications received on every surface of a list. + private sealed class Recorder : IDisposable + { + /// The list being observed. + private readonly ReactiveList _list; + + /// The subscriptions to release. + private readonly List _subscriptions = []; + + /// The number of stream notifications. + private int _stream; + + /// The number of collection-changed events. + private int _collection; + + /// The number of property-changed events. + private int _property; + + /// The number of current-items snapshots. + private int _current; + + /// The number of added batches. + private int _added; + + /// The number of removed batches. + private int _removed; + + /// The number of changed batches. + private int _changed; + + /// The number of stream completions. + private int _completions; + + /// Initializes a new instance of the class. + /// The list to observe. + public Recorder(ReactiveList list) + { + _list = list; + _subscriptions.Add(list.Stream.Subscribe( + notification => _ = Interlocked.Increment(ref _stream), + static _ => { }, + () => Interlocked.Increment(ref _completions))); + _subscriptions.Add(list.CurrentItems.Subscribe(items => _ = Interlocked.Increment(ref _current))); + _subscriptions.Add(list.Added.Subscribe(items => _ = Interlocked.Increment(ref _added))); + _subscriptions.Add(list.Removed.Subscribe(items => _ = Interlocked.Increment(ref _removed))); + _subscriptions.Add(list.Changed.Subscribe(items => _ = Interlocked.Increment(ref _changed))); + list.CollectionChanged += OnCollectionChanged; + list.PropertyChanged += OnPropertyChanged; + } + + /// Takes a snapshot of every counter. + /// The counters. + public Counts Snapshot() => new( + Volatile.Read(ref _stream), + Volatile.Read(ref _collection), + Volatile.Read(ref _property), + Volatile.Read(ref _current), + Volatile.Read(ref _added), + Volatile.Read(ref _removed), + Volatile.Read(ref _changed), + Volatile.Read(ref _completions)); + + /// + public void Dispose() + { + _list.CollectionChanged -= OnCollectionChanged; + _list.PropertyChanged -= OnPropertyChanged; + foreach (var subscription in _subscriptions) + { + subscription.Dispose(); + } + } + + /// Counts a collection-changed event. + /// The list. + /// The event arguments. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs args) => Interlocked.Increment(ref _collection); + + /// Counts a property-changed event. + /// The list. + /// The event arguments. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void OnPropertyChanged(object? sender, PropertyChangedEventArgs args) => Interlocked.Increment(ref _property); + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListEditOrderTests.cs b/src/tests/ReactiveList.Tests/ReactiveListEditOrderTests.cs new file mode 100644 index 00000000..019487a1 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListEditOrderTests.cs @@ -0,0 +1,78 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks that announces edits that only change the order of the items. +public class ReactiveListEditOrderTests +{ + /// The value the edit both adds and removes. It fails the view filter. + private const int Cancelled = 3; + + /// Values divisible by this number fail the view filter. + private const int FilterDivisor = 3; + + /// The initial items. + private static readonly int[] Initial = [Cancelled, 2, 1, 4]; + + /// An edit that adds and removes the same value reorders the list and still reaches the views. + /// A task representing the asynchronous test. + [Test] + public async Task Edit_ReorderingWithoutNetChange_NotifiesViews() + { + using var list = new ReactiveList(); + list.AddRange(Initial); + using var view = list.CreateView(static value => value % FilterDivisor != 0, Sequencer.Immediate, 0); + + list.Edit(static edit => + { + edit.Add(Cancelled); + _ = edit.Remove(Cancelled); + }); + list.Move(1, 0); + list.Add(ViewFuzzSupport.Sentinel); + + await ViewFuzzSupport.SettleAsync(() => view.Items.Contains(ViewFuzzSupport.Sentinel)); + await Assert.That(view.Items.ToArray()).IsEquivalentTo(list.Where(static value => value % FilterDivisor != 0).ToArray(), CollectionOrdering.Matching); + } + + /// An edit that only reorders raises one reset on the list and a stream that rebuilds the order. + /// A task representing the asynchronous test. + [Test] + public async Task Edit_ReorderingWithoutNetChange_RaisesCollectionChangedAndStream() + { + using var list = new ReactiveList(Initial); + var resets = 0; + list.CollectionChanged += (_, _) => resets++; + var actions = new List(); + using var subscription = list.Stream.Subscribe(notification => actions.Add(notification.Action)); + + list.Edit(static edit => + { + edit.Add(Cancelled); + _ = edit.Remove(Cancelled); + }); + + await Assert.That(resets).IsEqualTo(1); + await Assert.That(actions.ToArray()).IsEquivalentTo([CacheAction.Cleared, CacheAction.BatchAdded], CollectionOrdering.Matching); + } + + /// An edit with no net effect announces nothing. + /// A task representing the asynchronous test. + [Test] + public async Task Edit_WithNoNetEffect_AnnouncesNothing() + { + using var list = new ReactiveList(Initial); + var notifications = 0; + using var subscription = list.Stream.Subscribe(_ => notifications++); + + list.Edit(static edit => + { + edit.Add(Cancelled); + edit.RemoveAt(edit.Count - 1); + }); + + await Assert.That(notifications).IsEqualTo(0); + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListFilterDynamicTests.cs b/src/tests/ReactiveList.Tests/ReactiveListFilterDynamicTests.cs new file mode 100644 index 00000000..c60cc372 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListFilterDynamicTests.cs @@ -0,0 +1,244 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Tests the lifecycle and filtering rules of FilterDynamic. +public class ReactiveListFilterDynamicTests +{ + /// The divisor of the even filter and the expected size of two-element results. + private const int Pair = 2; + + /// A value that the even filter rejects. + private const int Odd = 3; + + /// A value that the even filter accepts. + private const int Even = 4; + + /// Another value that the even filter accepts. + private const int OtherEven = 6; + + /// The number of notifications emitted by the concurrency test. + private const int EmitCount = 2000; + + /// The number of filter switches performed by the concurrency test. + private const int SwitchCount = 500; + + /// The default filter includes everything until the first predicate arrives. + /// A task representing the asynchronous test. + [Test] + public async Task DefaultFilter_IncludesEverythingUntilFirstPredicate() + { + using var stream = new Signal>(); + using var filters = new Signal>(); + var received = new List>(); + using var subscription = stream.FilterDynamic(filters).Subscribe(received.Add); + + stream.OnNext(new(CacheAction.Added, Odd)); + filters.OnNext(static value => value % Pair == 0); + stream.OnNext(new(CacheAction.Added, Odd)); + stream.OnNext(new(CacheAction.Added, Even)); + + await Assert.That(received.Count).IsEqualTo(Pair); + await Assert.That(received[0].Item).IsEqualTo(Odd); + await Assert.That(received[1].Item).IsEqualTo(Even); + } + + /// A new predicate replaces the old one for later notifications. + /// A task representing the asynchronous test. + [Test] + public async Task NewPredicate_ReplacesOldOne() + { + using var stream = new Signal>(); + using var filters = new Signal>(); + var received = new List>(); + using var subscription = stream.FilterDynamic(filters).Subscribe(received.Add); + + filters.OnNext(static value => value % Pair == 0); + stream.OnNext(new(CacheAction.Added, Odd)); + filters.OnNext(static value => value % Pair != 0); + stream.OnNext(new(CacheAction.Added, Odd)); + stream.OnNext(new(CacheAction.Added, Even)); + + await Assert.That(received.Count).IsEqualTo(1); + await Assert.That(received[0].Item).IsEqualTo(Odd); + } + + /// Removals and clears always pass so downstream collections can drop items. + /// A task representing the asynchronous test. + [Test] + public async Task RemovedAndCleared_AlwaysPass() + { + using var stream = new Signal>(); + using var filters = new Signal>(); + var received = new List>(); + using var subscription = stream.FilterDynamic(filters).Subscribe(received.Add); + + filters.OnNext(static value => value % Pair == 0); + stream.OnNext(new(CacheAction.Removed, Odd)); + stream.OnNext(new(CacheAction.Cleared, default)); + + await Assert.That(received.Count).IsEqualTo(Pair); + } + + /// An update becomes an update, an addition, a removal or nothing depending on which sides match. + /// A task representing the asynchronous test. + [Test] + public async Task Update_IsTranslatedByWhichSidesMatch() + { + using var stream = new Signal>(); + using var filters = new Signal>(); + var received = new List>(); + using var subscription = stream.FilterDynamic(filters).Subscribe(received.Add); + filters.OnNext(static value => value % Pair == 0); + + stream.OnNext(new(CacheAction.Updated, OtherEven, null, 0, 0, Even)); + stream.OnNext(new(CacheAction.Updated, OtherEven, null, 0, 0, Odd)); + stream.OnNext(new(CacheAction.Updated, Odd, null, 0, 0, Even)); + stream.OnNext(new(CacheAction.Updated, Odd, null, 0, 0, Odd)); + + await Assert.That(received.Count).IsEqualTo(Pair + 1); + await Assert.That(received[0].Action).IsEqualTo(CacheAction.Updated); + await Assert.That(received[1].Action).IsEqualTo(CacheAction.Added); + await Assert.That(received[1].Item).IsEqualTo(OtherEven); + await Assert.That(received[2].Action).IsEqualTo(CacheAction.Removed); + await Assert.That(received[2].Item).IsEqualTo(Even); + } + + /// Batches are narrowed to the matching items. + /// A task representing the asynchronous test. + [Test] + public async Task Batch_IsNarrowedToMatchingItems() + { + using var stream = new Signal>(); + using var filters = new Signal>(); + var received = new List(); + using var subscription = stream.FilterDynamic(filters).Subscribe(notification => + { + received.Add(notification.Batch!.Items.AsSpan(0, notification.Batch.Count).ToArray()); + }); + filters.OnNext(static value => value % Pair == 0); + + int[] items = [Odd, Even, OtherEven]; + stream.OnNext(new(CacheAction.BatchAdded, default, new PooledBatch(items, items.Length, ReturnToPool: false))); + + await Assert.That(received.Count).IsEqualTo(1); + await Assert.That(received[0]).IsEquivalentTo([Even, OtherEven], CollectionOrdering.Matching); + } + + /// When the filter source completes the last predicate stays in force. + /// A task representing the asynchronous test. + [Test] + public async Task FilterCompletion_KeepsLastPredicate() + { + using var stream = new Signal>(); + using var filters = new Signal>(); + var received = new List>(); + var completed = false; + using var subscription = stream.FilterDynamic(filters).Subscribe(received.Add, static _ => { }, () => completed = true); + + filters.OnNext(static value => value % Pair == 0); + filters.OnCompleted(); + stream.OnNext(new(CacheAction.Added, Odd)); + stream.OnNext(new(CacheAction.Added, Even)); + + await Assert.That(received.Count).IsEqualTo(1); + await Assert.That(completed).IsFalse(); + + stream.OnCompleted(); + await Assert.That(completed).IsTrue(); + } + + /// A filter error reaches the observer and releases the stream subscription. + /// A task representing the asynchronous test. + [Test] + public async Task FilterError_IsForwardedAndReleasesStream() + { + using var stream = new Signal>(); + using var filters = new Signal>(); + Exception? error = null; + using var subscription = stream.FilterDynamic(filters).Subscribe(static _ => { }, ex => error = ex, static () => { }); + var failure = new InvalidOperationException("filter failed"); + + filters.OnError(failure); + + await Assert.That(error).IsSameReferenceAs(failure); + await Assert.That(stream.HasObservers).IsFalse(); + await Assert.That(filters.HasObservers).IsFalse(); + } + + /// A stream error reaches the observer and releases the filter subscription. + /// A task representing the asynchronous test. + [Test] + public async Task StreamError_IsForwardedAndReleasesFilter() + { + using var stream = new Signal>(); + using var filters = new Signal>(); + Exception? error = null; + using var subscription = stream.FilterDynamic(filters).Subscribe(static _ => { }, ex => error = ex, static () => { }); + var failure = new InvalidOperationException("stream failed"); + + stream.OnError(failure); + + await Assert.That(error).IsSameReferenceAs(failure); + await Assert.That(filters.HasObservers).IsFalse(); + } + + /// Disposing the subscription releases both inputs. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_ReleasesBothInputs() + { + using var stream = new Signal>(); + using var filters = new Signal>(); + var subscription = stream.FilterDynamic(filters).Subscribe(static _ => { }); + filters.OnNext(static _ => true); + + subscription.Dispose(); + + await Assert.That(stream.HasObservers).IsFalse(); + await Assert.That(filters.HasObservers).IsFalse(); + } + + /// Switching between two accept-all predicates while notifications flow loses nothing and never overlaps deliveries. + /// A task representing the asynchronous test. + [Test] + public async Task ConcurrentSwitching_LosesNoNotifications() + { + using var stream = new Signal>(); + using var filters = new Signal>(); + var received = 0; + var inside = 0; + var overlaps = 0; + using var subscription = stream.FilterDynamic(filters).Subscribe(ignored => + { + if (Interlocked.Increment(ref inside) != 1) + { + _ = Interlocked.Increment(ref overlaps); + } + + _ = Interlocked.Increment(ref received); + _ = Interlocked.Decrement(ref inside); + }); + + var emitter = Task.Run(() => + { + for (var i = 0; i < EmitCount; i++) + { + stream.OnNext(new(CacheAction.Added, i)); + } + }); + var switcher = Task.Run(() => + { + for (var i = 0; i < SwitchCount; i++) + { + filters.OnNext(static _ => true); + } + }); + + await Task.WhenAll(emitter, switcher); + await Assert.That(overlaps).IsEqualTo(0); + await Assert.That(received).IsEqualTo(EmitCount); + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListFuzzTests.cs b/src/tests/ReactiveList.Tests/ReactiveListFuzzTests.cs new file mode 100644 index 00000000..0d34f87a --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListFuzzTests.cs @@ -0,0 +1,1119 @@ +// 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. + +using CsCheck; + +namespace ReactiveList.Tests; + +/// CsCheck model-based fuzz tests that compare with and replay its notifications. +public class ReactiveListFuzzTests +{ + /// The largest item value produced by the generators; a small range keeps duplicates frequent. + private const int MaxValue = 6; + + /// The largest index produced by the generators; it exceeds the list size so invalid indexes occur. + private const int MaxIndex = 12; + + /// The largest generated array length. + private const int MaxArrayLength = 6; + + /// The largest divisor used by the removal predicate. + private const int MaxDivisor = 3; + + /// The largest number of repeated disposals. + private const int MaxDisposals = 4; + + /// The number of random sequences checked by each test. + private const int Iterations = 250; + + /// The number of worker threads used by CsCheck; one keeps the sequences deterministic per seed. + private const int Threads = 1; + + /// The number of distinct edit script steps. + private const int EditStepCount = 8; + + /// The generator for item values. + private static readonly Gen Value = Gen.Int[0, MaxValue]; + + /// The generator for possibly invalid indexes. + private static readonly Gen Index = Gen.Int[-1, MaxIndex]; + + /// The generator for small item arrays. + private static readonly Gen Values = Value.Array[0, MaxArrayLength]; + + /// The generator for scripts executed inside . + private static readonly Gen EditScript = + Gen.Select(Gen.Int[0, EditStepCount - 1], Value, Value, static (kind, a, b) => new EditStep(kind, a, b)).Array[0, MaxArrayLength]; + + /// The edit step implementations indexed by . + private static readonly Action, int, int>[] EditActions = + [ + static (list, a, _) => list.Add(a), + static (list, a, b) => list.Insert(a % (list.Count + 1), b), + static (list, a, _) => + { + if (list.Count > 0) + { + list.RemoveAt(a % list.Count); + } + }, + static (list, a, ignored) => + { + _ = list.Remove(a); + }, + static (list, a, _) => + { + if (a < MaxDivisor) + { + list.Clear(); + } + }, + static (list, a, b) => + { + if (list.Count > 0) + { + list.Move(a % list.Count, b % list.Count); + } + }, + static (list, a, b) => list.AddRange([a, b]), + static (list, a, b) => + { + if (list.Count > 0) + { + list[a % list.Count] = b; + } + }, + ]; + + /// Applies every public mutation to a list and to and checks contents, history and notifications. + /// A completed task. + [Test] + public Task ModelBased_AllMutations_WithObservers_MatchListModel() + { + CreateInitial(observe: true).SampleModelBased( + CreateOperations(), + equal: static (subject, model) => subject.Matches(model), + iter: Iterations, + threads: Threads, + printActual: static subject => subject.Describe(), + printModel: static model => model.Describe()); + return Task.CompletedTask; + } + + /// Runs the same sequences without any observers so the zero-observer fast path and lazy mirrors are checked. + /// A completed task. + [Test] + public Task ModelBased_AllMutations_WithoutObservers_MatchListModel() + { + CreateInitial(observe: false).SampleModelBased( + CreateOperations(), + equal: static (subject, model) => subject.Matches(model), + iter: Iterations, + threads: Threads, + printActual: static subject => subject.Describe(), + printModel: static model => model.Describe()); + return Task.CompletedTask; + } + + /// Checks that disposing repeatedly completes the stream once, keeps reads working and makes mutations fail. + /// A completed task. + [Test] + public Task Dispose_Repeated_IsIdempotentAndKeepsReadsWorking() + { + Gen.Select(Values, Gen.Int[1, MaxDisposals]).Sample(static input => IsDisposeContractMet(input.Item1, input.Item2), iter: Iterations, threads: Threads); + return Task.CompletedTask; + } + + /// Checks that enumeration, copying, spans, memory and the indexer all agree with . + /// A completed task. + [Test] + public Task ReadApis_AgreeWithEachOther() + { + Values.Sample(AreReadsConsistent, iter: Iterations, threads: Threads); + return Task.CompletedTask; + } + + /// Checks the dispose contract for one list. + /// The initial items. + /// The number of times to dispose. + /// when the contract holds. + private static bool IsDisposeContractMet(int[] values, int disposals) + { + var list = new ReactiveList(values); + var completions = 0; + using var subscription = list.Stream.Subscribe(static _ => { }, static _ => { }, () => completions++); + + for (var i = 0; i < disposals; i++) + { + list.Dispose(); + } + + return list.IsDisposed + && completions == 1 + && list.ToArray().AsSpan().SequenceEqual(values) + && ThrowsObjectDisposed(list); + } + + /// Tests whether adding to a disposed list throws . + /// The disposed list. + /// when it throws. + private static bool ThrowsObjectDisposed(ReactiveList list) + { + try + { + list.Add(1); + return false; + } + catch (ObjectDisposedException) + { + return true; + } + } + + /// Checks that every read API of a list agrees. + /// The items. + /// when the reads agree. + private static bool AreReadsConsistent(int[] values) + { + using var list = new ReactiveList(values); + var copied = new int[values.Length]; + list.CopyTo(copied, 0); + var indexed = new int[values.Length]; + for (var i = 0; i < indexed.Length; i++) + { + indexed[i] = list[i]; + } + + return list.Count == values.Length + && new List(list).SequenceEqual(values) + && copied.SequenceEqual(values) + && indexed.SequenceEqual(values) + && list.AsSpan().SequenceEqual(values) + && list.AsMemory().Span.SequenceEqual(values) + && list.ToArray().SequenceEqual(values); + } + + /// Creates the generator for the initial subject and model pair. + /// Whether the subject subscribes to its own change notifications. + /// The initial pair generator. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Gen<(Subject Actual, Model Expected)> CreateInitial(bool observe) => + Gen.Select(Values, Gen.Bool, static (values, touch) => (values, touch)) + .Select(pair => + { + var subject = new Subject(pair.values, observe); + var model = new Model(pair.values); + if (pair.touch) + { + subject.TouchAll(); + model.TouchAll(); + } + + return (subject, model); + }); + + /// Creates every operation generator. + /// The operation generators. + private static GenOperation[] CreateOperations() => [.. CreateItemOperations(), .. CreateBulkOperations()]; + + /// Creates the operation generators that act on single items or indexes. + /// The operation generators. + private static GenOperation[] CreateItemOperations() => + [ + Value.Operation( + static v => $"Add({v})", + static (s, v) => s.Run(() => s.List.Add(v)), + static (m, v) => m.Run(() => m.Add(v))), + Gen.Select(Index, Value).Operation( + static t => $"Insert({t.Item1}, {t.Item2})", + static (s, t) => s.Run(() => s.List.Insert(t.Item1, t.Item2)), + static (m, t) => m.Run(() => m.Insert(t.Item1, t.Item2))), + Value.Operation( + static v => $"Remove({v})", + static (s, v) => s.Run(() => s.List.Remove(v).ToString()), + static (m, v) => m.Run(() => m.Remove(v).ToString())), + Index.Operation( + static i => $"RemoveAt({i})", + static (s, i) => s.Run(() => s.List.RemoveAt(i)), + static (m, i) => m.Run(() => m.RemoveAt(i))), + Gen.Select(Value, Value).Operation( + static t => $"Update({t.Item1}, {t.Item2})", + static (s, t) => s.Run(() => s.List.Update(t.Item1, t.Item2)), + static (m, t) => m.Run(() => m.Update(t.Item1, t.Item2))), + Gen.Select(Index, Value).Operation( + static t => $"this[{t.Item1}] = {t.Item2}", + static (s, t) => s.Run(() => SetIndexer(s.List, t.Item1, t.Item2)), + static (m, t) => m.Run(() => m.SetItem(t.Item1, t.Item2))), + Gen.Select(Index, Index).Operation( + static t => $"Move({t.Item1}, {t.Item2})", + static (s, t) => s.Run(() => s.List.Move(t.Item1, t.Item2)), + static (m, t) => m.Run(() => m.Move(t.Item1, t.Item2))), + Value.Operation( + static v => $"IList.Add({v})", + static (s, v) => s.Run(() => ((IList)s.List).Add(v).ToString()), + static (m, v) => m.Run(() => m.NonGenericAdd(v).ToString())), + Gen.Select(Index, Value).Operation( + static t => $"IList.Insert({t.Item1}, {t.Item2})", + static (s, t) => s.Run(() => ((IList)s.List).Insert(t.Item1, t.Item2)), + static (m, t) => m.Run(() => m.Insert(t.Item1, t.Item2))), + Gen.Operation( + "TouchAll()", + static s => s.TouchAll(), + static m => m.TouchAll()), + ]; + + /// Creates the operation generators that act on ranges, predicates, whole-list changes or edit scripts. + /// The operation generators. + private static GenOperation[] CreateBulkOperations() => + [ + Values.Operation( + static a => $"AddRange([{string.Join(",", a)}])", + static (s, a) => s.Run(() => s.List.AddRange(a)), + static (m, a) => m.Run(() => m.AddRange(a))), + Values.Operation( + static a => $"AddRange(span [{string.Join(",", a)}])", + static (s, a) => s.Run(() => s.List.AddRange(a.AsSpan())), + static (m, a) => m.Run(() => m.AddRange(a))), + Gen.Select(Index, Values).Operation( + static t => $"InsertRange({t.Item1}, [{string.Join(",", t.Item2)}])", + static (s, t) => s.Run(() => s.List.InsertRange(t.Item1, t.Item2)), + static (m, t) => m.Run(() => m.InsertRange(t.Item1, t.Item2))), + Gen.Select(Index, Index).Operation( + static t => $"RemoveRange({t.Item1}, {t.Item2})", + static (s, t) => s.Run(() => s.List.RemoveRange(t.Item1, t.Item2)), + static (m, t) => m.Run(() => m.RemoveRange(t.Item1, t.Item2))), + Values.Operation( + static a => $"Remove([{string.Join(",", a)}])", + static (s, a) => s.Run(() => s.List.Remove(a)), + static (m, a) => m.Run(() => m.RemoveEnumerable(a))), + Gen.Int[1, MaxDivisor].Operation( + static k => $"RemoveMany(v % {k} == 0)", + static (s, k) => s.Run(() => s.List.RemoveMany(v => v % k == 0).ToString()), + static (m, k) => m.Run(() => m.RemoveMany(k).ToString())), + Gen.Operation( + "Clear()", + static s => s.Run(() => s.List.Clear()), + static m => m.Run(m.Clear)), + Gen.Bool.Operation( + static notify => $"ClearWithoutDeallocation({notify})", + static (s, notify) => s.RunSilentClear(notify), + static (m, notify) => m.Run(() => m.ClearWithoutDeallocation(notify))), + Values.Operation( + static a => $"ReplaceAll([{string.Join(",", a)}])", + static (s, a) => s.Run(() => s.List.ReplaceAll(a)), + static (m, a) => m.Run(() => m.ReplaceAll(a))), + EditScript.Operation( + static script => $"Edit({script.Length} steps)", + static (s, script) => s.RunEdit(script), + static (m, script) => m.RunEdit(script)), + ]; + + /// Assigns through the indexer. + /// The list. + /// The index. + /// The value. + private static void SetIndexer(ReactiveList list, int index, int value) => list[index] = value; + + /// Maps an exception onto a comparable outcome label; every argument error is treated alike. + /// The action to run. + /// The outcome label. + private static string Execute(Func action) + { + try + { + var result = action(); + return result is null ? "ok" : $"ok:{result}"; + } + catch (ArgumentException) + { + return "argument"; + } + catch (ObjectDisposedException) + { + return "disposed"; + } + } + + /// Applies an edit script to an editable list. + /// The editable list. + /// The script steps. + private static void ApplyScript(IEditableList list, EditStep[] script) + { + foreach (var step in script) + { + EditActions[step.Kind](list, step.A, step.B); + } + } + + /// One step of an edit script. + /// The index of the action to run. + /// The first argument. + /// The second argument. + private readonly record struct EditStep(int Kind, int A, int B); + + /// Wraps the list under test and every observation made of it. + private sealed class Subject + { + /// The collection-changed replay of the list. + private readonly List _collectionShadow; + + /// The stream replay of the list. + private readonly List _streamShadow; + + /// The collection-changed replay of the mirror. + private readonly List _itemsShadow = []; + + /// Whether the list's own notifications are observed. + private readonly bool _observe; + + /// The materialised items mirror, if touched. + private ReadOnlyObservableCollection? _items; + + /// The materialised added history, if touched. + private ReadOnlyObservableCollection? _added; + + /// The materialised removed history, if touched. + private ReadOnlyObservableCollection? _removed; + + /// The materialised changed history, if touched. + private ReadOnlyObservableCollection? _changed; + + /// The latest snapshot received from . + private int[]? _current; + + /// The first contract violation found while running operations. + private string? _violation; + + /// Initializes a new instance of the class. + /// The initial items. + /// Whether to observe the list's notifications. + public Subject(int[] values, bool observe) + { + List = new(values); + _observe = observe; + _collectionShadow = [.. values]; + _streamShadow = [.. values]; + Outcome = "ok"; + if (!observe) + { + return; + } + + List.CollectionChanged += (_, args) => Replay(_collectionShadow, args, List.ToArray); + _ = List.Stream.Subscribe(OnStream); + } + + /// Gets the list under test. + public ReactiveList List { get; } + + /// Gets the outcome label of the last operation. + public string Outcome { get; private set; } + + /// Runs an operation, recording its outcome and checking version behaviour. + /// The operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Run(Action action) => Run(() => + { + action(); + return null; + }); + + /// Runs an operation that returns a value, recording its outcome and checking version behaviour. + /// The operation. + public void Run(Func action) + { + var before = List.ToArray(); + var versionBefore = List.Version; + Outcome = Execute(action); + var after = List.ToArray(); + var versionAfter = List.Version; + if (versionAfter < versionBefore) + { + _violation = "version went backwards"; + } + else if (versionAfter == versionBefore && !before.AsSpan().SequenceEqual(after)) + { + _violation = "contents changed without a version change"; + } + } + + /// Runs . + /// Whether observers are told. + public void RunSilentClear(bool notify) + { + Run(() => List.ClearWithoutDeallocation(notify)); + if (notify) + { + return; + } + + // A silent clear tells only the Items mirror, so the other replays are re-based on the real contents. + _collectionShadow.Clear(); + _streamShadow.Clear(); + } + + /// Runs an edit script through . + /// The script. + public void RunEdit(EditStep[] script) + { + Run(() => List.Edit(wrapper => ApplyScript(wrapper, script))); + var expected = List.ToArray(); + + // Edit reports membership only, so the position-based replay is re-based after checking the multiset. + if (_observe && !_streamShadow.Order().SequenceEqual(expected.Order())) + { + _violation = "stream replay disagrees with the list after Edit"; + } + + _streamShadow.Clear(); + _streamShadow.AddRange(expected); + } + + /// Materialises every lazily created observable view of the list. + public void TouchAll() + { + if (_items is null) + { + var mirror = List.Items; + _items = mirror; + _itemsShadow.Clear(); + _itemsShadow.AddRange(mirror); + ((INotifyCollectionChanged)mirror).CollectionChanged += (_, args) => Replay(_itemsShadow, args, () => [.. mirror]); + } + + _added ??= List.ItemsAdded; + _removed ??= List.ItemsRemoved; + _changed ??= List.ItemsChanged; + if (_current is not null) + { + return; + } + + _current = []; + _ = List.CurrentItems.Subscribe(items => _current = [.. items]); + } + + /// Checks this subject against the model. + /// The model. + /// when they agree. + public bool Matches(Model model) + { + _violation ??= CheckContents(model) + ?? CheckReplays() + ?? CheckMirror() + ?? CheckHistory(model) + ?? CheckCurrent(model); + return _violation is null; + } + + /// Describes the subject for failure output. + /// The description. + public string Describe() => + $"items [{string.Join(",", List.ToArray())}] outcome {Outcome} collection [{string.Join(",", _collectionShadow)}] stream [{string.Join(",", _streamShadow)}] violation {_violation}"; + + /// Compares two item collections, optionally ignoring order. + /// The actual items. + /// The expected items. + /// Whether only the multiset must match. + /// when they match. + private static bool SameItems(IEnumerable actual, IEnumerable expected, bool ignoreOrder) => + ignoreOrder ? actual.Order().SequenceEqual(expected.Order()) : actual.SequenceEqual(expected); + + /// Replays a collection-changed notification onto a shadow list. + /// The shadow list. + /// The notification arguments. + /// Reads the authoritative contents for a reset. + private static void Replay(List shadow, NotifyCollectionChangedEventArgs args, Func resync) + { + switch (args.Action) + { + case NotifyCollectionChangedAction.Add: + { + shadow.Insert(args.NewStartingIndex, (int)args.NewItems![0]!); + break; + } + + case NotifyCollectionChangedAction.Remove: + { + shadow.RemoveAt(args.OldStartingIndex); + break; + } + + case NotifyCollectionChangedAction.Replace: + { + shadow[args.NewStartingIndex] = (int)args.NewItems![0]!; + break; + } + + case NotifyCollectionChangedAction.Move: + { + var moved = shadow[args.OldStartingIndex]; + shadow.RemoveAt(args.OldStartingIndex); + shadow.Insert(args.NewStartingIndex, moved); + break; + } + + default: + { + shadow.Clear(); + shadow.AddRange(resync()); + break; + } + } + } + + /// Compares the contents, count and indexer with the model. + /// The model. + /// A description of the disagreement, or . + private string? CheckContents(Model model) + { + if (Outcome != model.Outcome) + { + return $"outcome {Outcome} vs {model.Outcome}"; + } + + var items = List.ToArray(); + if (!items.AsSpan().SequenceEqual(model.Items.ToArray()) || List.Count != model.Items.Count) + { + return "contents"; + } + + for (var i = 0; i < items.Length; i++) + { + if (List[i] != items[i]) + { + return "indexer"; + } + } + + return null; + } + + /// Compares the notification replays with the list. + /// A description of the disagreement, or . + private string? CheckReplays() + { + var items = List.ToArray(); + return _observe && !(_collectionShadow.SequenceEqual(items) && _streamShadow.SequenceEqual(items)) + ? $"notification replay: collection [{string.Join(",", _collectionShadow)}] stream [{string.Join(",", _streamShadow)}]" + : null; + } + + /// Compares the mirror and its replay with the list. + /// A description of the disagreement, or . + private string? CheckMirror() + { + var items = List.ToArray(); + return _items is not null && !(_items.SequenceEqual(items) && _itemsShadow.SequenceEqual(items)) + ? $"Items mirror [{string.Join(",", _items)}] replay [{string.Join(",", _itemsShadow)}]" + : null; + } + + /// Compares the added, removed and changed history collections with the model. + /// The model. + /// A description of the disagreement, or . + private string? CheckHistory(Model model) + { + if (_added is not null && !SameItems(_added, model.Added, model.HistoryOrderIsLoose)) + { + return $"ItemsAdded [{string.Join(",", _added)}] vs [{string.Join(",", model.Added)}]"; + } + + if (_removed is not null && !SameItems(_removed, model.Removed, model.HistoryOrderIsLoose)) + { + return $"ItemsRemoved [{string.Join(",", _removed)}] vs [{string.Join(",", model.Removed)}]"; + } + + return _changed is not null && !SameItems(_changed, model.Changed, model.HistoryOrderIsLoose) + ? $"ItemsChanged [{string.Join(",", _changed)}] vs [{string.Join(",", model.Changed)}]" + : null; + } + + /// Compares the latest current-items snapshot with the model. + /// The model. + /// A description of the disagreement, or . + private string? CheckCurrent(Model model) => + _current is not null && !model.CurrentIsIndeterminate && !_current.SequenceEqual(model.CurrentExpected) + ? $"CurrentItems [{string.Join(",", _current)}] vs [{string.Join(",", model.CurrentExpected)}]" + : null; + + /// Replays a stream notification onto the stream shadow. + /// The notification. + private void OnStream(CacheNotify notification) + { + if (notification.Batch is null) + { + OnSingleItem(notification); + return; + } + + OnBatch(notification, notification.Batch); + notification.Batch.Dispose(); + } + + /// Replays a single-item or clear notification. + /// The notification. + private void OnSingleItem(CacheNotify notification) + { + switch (notification.Action) + { + case CacheAction.Added: + { + _streamShadow.Insert(notification.CurrentIndex, notification.Item); + break; + } + + case CacheAction.Removed: + { + _streamShadow.RemoveAt(notification.CurrentIndex); + break; + } + + case CacheAction.Updated: + { + _streamShadow[notification.CurrentIndex] = notification.Item; + break; + } + + case CacheAction.Moved: + { + _streamShadow.RemoveAt(notification.PreviousIndex); + _streamShadow.Insert(notification.CurrentIndex, notification.Item); + break; + } + + case CacheAction.Cleared: + { + _streamShadow.Clear(); + break; + } + + default: + { + // Refresh and batch-only actions do not change positions. + break; + } + } + } + + /// Replays a batch notification. + /// The notification. + /// The batch. + private void OnBatch(CacheNotify notification, PooledBatch batch) + { + var items = new ArraySegment(batch.Items, 0, batch.Count); + switch (notification.Action) + { + case CacheAction.BatchAdded: + { + _streamShadow.InsertRange(notification.CurrentIndex >= 0 ? notification.CurrentIndex : _streamShadow.Count, items); + break; + } + + case CacheAction.BatchRemoved: + { + RemoveBatch(notification.CurrentIndex, items); + break; + } + + case CacheAction.Cleared: + { + _streamShadow.Clear(); + break; + } + + default: + { + // Other batch actions do not change positions. + break; + } + } + } + + /// Removes a batch either by position or by value. + /// The start position, or a negative value when unknown. + /// The removed items. + private void RemoveBatch(int index, ArraySegment items) + { + if (index >= 0) + { + _streamShadow.RemoveRange(index, items.Count); + return; + } + + foreach (var item in items) + { + _ = _streamShadow.Remove(item); + } + } + } + + /// The reference implementation built on . + private sealed class Model + { + /// Whether the last operation was a silent clear that raises no notification. + private bool _silent; + + /// Whether a silent clear left the current-items observable showing an older snapshot. + private bool _unsynced; + + /// Whether the current-items observable has been subscribed. + private int _currentTouched; + + /// Initializes a new instance of the class. + /// The initial items. + public Model(int[] values) + { + Items = [.. values]; + Added = []; + Removed = []; + Changed = []; + CurrentExpected = []; + Outcome = "ok"; + } + + /// Gets the model contents. + public List Items { get; } + + /// Gets the items expected in . + public List Added { get; private set; } + + /// Gets the items expected in . + public List Removed { get; private set; } + + /// Gets the items expected in . + public List Changed { get; private set; } + + /// Gets the snapshot the current-items observable should have delivered last. + public List CurrentExpected { get; private set; } + + /// Gets the outcome label of the last operation. + public string Outcome { get; private set; } + + /// Gets a value indicating whether the added and removed history came from an edit, where only the multiset is specified. + public bool HistoryOrderIsLoose { get; private set; } + + /// Gets a value indicating whether a silent clear makes the current-items snapshot depend on unspecified no-op behaviour. + public bool CurrentIsIndeterminate => _unsynced; + + /// Runs an operation, recording the outcome. + /// The operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Run(Action action) => Run(() => + { + action(); + return null; + }); + + /// Runs an operation that returns a value, recording the outcome. + /// The operation. + public void Run(Func action) + { + _silent = false; + var before = Items.ToArray(); + Outcome = Execute(action); + if (_silent) + { + _unsynced = true; + return; + } + + // After a silent clear the observable still shows the old snapshot until a real change is announced. + if (_unsynced && before.AsSpan().SequenceEqual(Items.ToArray())) + { + return; + } + + _unsynced = false; + RefreshCurrent(); + } + + /// Models TouchAll. + public void TouchAll() + { + if (Interlocked.Exchange(ref _currentTouched, 1) != 0) + { + return; + } + + RefreshCurrent(); + } + + /// Describes the model for failure output. + /// The description. + public string Describe() => $"items [{string.Join(",", Items)}] outcome {Outcome}"; + + /// Models Add. + /// The value. + public void Add(int value) + { + Items.Add(value); + SetHistory([value], [], [value]); + } + + /// Models Insert. + /// The index. + /// The value. + public void Insert(int index, int value) + { + Items.Insert(index, value); + SetHistory([value], [], [value]); + } + + /// Models AddRange. + /// The values. + public void AddRange(int[] values) + { + if (values.Length == 0) + { + return; + } + + Items.AddRange(values); + SetHistory(values, [], values); + } + + /// Models InsertRange. + /// The index. + /// The values. + public void InsertRange(int index, int[] values) + { + Items.InsertRange(index, values); + if (values.Length > 0) + { + SetHistory(values, [], values); + } + } + + /// Models Remove(item). + /// The value. + /// Whether an item was removed. + public bool Remove(int value) + { + var removed = Items.Remove(value); + if (removed) + { + SetHistory([], [value], [value]); + } + + return removed; + } + + /// Models RemoveAt. + /// The index. + public void RemoveAt(int index) + { + var item = Items[index]; + Items.RemoveAt(index); + SetHistory([], [item], [item]); + } + + /// Models RemoveRange. + /// The index. + /// The count. + public void RemoveRange(int index, int count) + { + var removed = Items.GetRange(index, count); + Items.RemoveRange(index, count); + if (count > 0) + { + SetHistory([], removed, removed); + } + } + + /// Models Remove(IEnumerable). + /// The values. + public void RemoveEnumerable(int[] values) + { + var pending = new List(values); + var removed = new List(); + var index = 0; + while (index < Items.Count) + { + var match = pending.IndexOf(Items[index]); + if (match < 0) + { + index++; + continue; + } + + pending.RemoveAt(match); + removed.Add(Items[index]); + Items.RemoveAt(index); + } + + if (removed.Count > 0) + { + SetHistory([], removed, removed); + } + } + + /// Models RemoveMany with a modulo predicate. + /// The divisor. + /// The number removed. + public int RemoveMany(int divisor) + { + var removed = Items.FindAll(v => v % divisor == 0); + if (removed.Count == 0) + { + return 0; + } + + _ = Items.RemoveAll(v => v % divisor == 0); + SetHistory([], removed, removed); + return removed.Count; + } + + /// Models Clear. + public void Clear() + { + var old = new List(Items); + Items.Clear(); + SetHistory([], old, old); + } + + /// Models ClearWithoutDeallocation. + /// Whether notifications are raised. + public void ClearWithoutDeallocation(bool notify) + { + if (notify) + { + Clear(); + return; + } + + _silent = true; + Items.Clear(); + } + + /// Models Update. + /// The value to find. + /// The replacement. + public void Update(int oldValue, int newValue) + { + var index = Items.IndexOf(oldValue); + if (index < 0) + { + return; + } + + Items[index] = newValue; + Changed = [newValue]; + } + + /// Models the indexer setter. + /// The index. + /// The value. + public void SetItem(int index, int value) + { + Items[index] = value; + Changed = [value]; + } + + /// Models Move. + /// The old index. + /// The new index. + /// Thrown when either index is outside the list. + public void Move(int oldIndex, int newIndex) + { + if (oldIndex < 0 || oldIndex >= Items.Count || newIndex < 0 || newIndex >= Items.Count) + { + throw new ArgumentOutOfRangeException(nameof(oldIndex)); + } + + if (oldIndex == newIndex) + { + return; + } + + var item = Items[oldIndex]; + Items.RemoveAt(oldIndex); + Items.Insert(newIndex, item); + Changed = [item]; + } + + /// Models ReplaceAll. + /// The new items. + public void ReplaceAll(int[] values) + { + var old = new List(Items); + Items.Clear(); + Items.AddRange(values); + SetHistory(values, old, old); + } + + /// Models Edit. + /// The script. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RunEdit(EditStep[] script) => Run(() => + { + var before = new List(Items); + ApplyScript(new EditableListWrapper(Items), script); + var added = MultisetDifference(Items, before); + var removed = MultisetDifference(before, Items); + + // A pure reorder still counts as a change, so it replaces the history with empty added and removed sets. + if (!before.SequenceEqual(Items)) + { + SetHistory(added, removed, [.. added, .. removed]); + HistoryOrderIsLoose = true; + } + }); + + /// Models the non-generic IList.Add. + /// The value. + /// The index of the new item. + public int NonGenericAdd(int value) + { + Add(value); + return Items.Count - 1; + } + + /// Returns the items of that are not matched one-for-one in . + /// The items to reduce. + /// The items to subtract. + /// The remaining items in source order. + private static int[] MultisetDifference(List source, List other) + { + var pool = new List(other); + var result = new List(); + foreach (var item in source) + { + var index = pool.IndexOf(item); + if (index < 0) + { + result.Add(item); + continue; + } + + pool.RemoveAt(index); + } + + return [.. result]; + } + + /// Records the history collections for an operation. + /// The added items. + /// The removed items. + /// The changed items. + private void SetHistory(IEnumerable added, IEnumerable removed, IEnumerable changed) + { + Added = [.. added]; + Removed = [.. removed]; + Changed = [.. changed]; + HistoryOrderIsLoose = false; + } + + /// Updates the snapshot the current-items observable should have seen. + private void RefreshCurrent() + { + if (Volatile.Read(ref _currentTouched) == 0) + { + return; + } + + CurrentExpected = [.. Items]; + } + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListNonGenericContractTests.cs b/src/tests/ReactiveList.Tests/ReactiveListNonGenericContractTests.cs new file mode 100644 index 00000000..e97b4f04 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListNonGenericContractTests.cs @@ -0,0 +1,69 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks the non-generic and option members of . +public class ReactiveListNonGenericContractTests +{ + /// The number of requested items that is larger than the small-removal threshold. + private const int LargeRequest = 12; + + /// The options set at initialization are the ones the list reports. + /// A task representing the asynchronous test. + [Test] + public async Task Options_Init_ReportsTheGivenOptions() + { + var options = ReactiveSourceOptions.Default; + using ReactiveList list = new() { Options = options }; + + await Assert.That(list.Options).IsSameReferenceAs(options); + await Assert.That(static () => new ReactiveList { Options = null! }).Throws(); + } + + /// Copying to a non-generic array of an unrelated element type is rejected. + /// A task representing the asynchronous test. + [Test] + public async Task CopyTo_UnrelatedArrayType_Throws() + { + using ReactiveList list = ["a"]; + + await Assert.That(() => list.CopyTo((Array)new int[1], 0)).Throws(); + } + + /// A null inserted through the non-generic list is accepted by a list of references. + /// A task representing the asynchronous test. + [Test] + public async Task Insert_NullThroughNonGenericList_AddsNullForReferenceTypes() + { + using ReactiveList list = []; + + list.Insert(0, (object?)null); + + await Assert.That(list.Count).IsEqualTo(1); + await Assert.That(list[0]).IsNull(); + } + + /// Removing many items that include a null still removes the matching occurrences. + /// A task representing the asynchronous test. + [Test] + public async Task Remove_ManyItemsIncludingNull_RemovesMatches() + { + using ReactiveList list = []; + var requested = new string[LargeRequest]; + for (var i = 0; i < LargeRequest; i++) + { + requested[i] = $"item{i}"; + list.Add(requested[i]); + } + + list.Add(null!); + requested[0] = null!; + + list.Remove(requested); + + await Assert.That(list.Count).IsEqualTo(1); + await Assert.That(list[0]).IsEqualTo("item0"); + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListNotificationComplianceTests.cs b/src/tests/ReactiveList.Tests/ReactiveListNotificationComplianceTests.cs index 7a4e530f..27a6a0ed 100644 --- a/src/tests/ReactiveList.Tests/ReactiveListNotificationComplianceTests.cs +++ b/src/tests/ReactiveList.Tests/ReactiveListNotificationComplianceTests.cs @@ -4,7 +4,7 @@ namespace ReactiveList.Tests; -/// Tests notification contracts used by UI binding and DynamicData-style pipelines. +/// Tests notification contracts used by UI binding and change-set pipelines. public class ReactiveListNotificationComplianceTests { /// Indexer replacement should be one replace notification and should not report a count change. diff --git a/src/tests/ReactiveList.Tests/ReactiveListObserverFailureTests.cs b/src/tests/ReactiveList.Tests/ReactiveListObserverFailureTests.cs new file mode 100644 index 00000000..d41fa4f8 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListObserverFailureTests.cs @@ -0,0 +1,186 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks that finishes delivery and rethrows when an observer or handler fails. +public class ReactiveListObserverFailureTests +{ + /// A throwing collection-changed handler fails the mutation after the change committed. + /// A task representing the asynchronous test. + [Test] + public async Task CollectionChangedHandler_Throws_MutationRethrows() + { + using ReactiveList list = []; + list.CollectionChanged += static (_, _) => throw new InvalidOperationException(); + + await Assert.That(() => list.Add(1)).Throws(); + await Assert.That(list.Count).IsEqualTo(1); + } + + /// A throwing property-changed handler fails the mutation after the change committed. + /// A task representing the asynchronous test. + [Test] + public async Task PropertyChangedHandler_Throws_MutationRethrows() + { + using ReactiveList list = []; + list.PropertyChanged += static (_, _) => throw new InvalidOperationException(); + + await Assert.That(() => list.Add(1)).Throws(); + await Assert.That(list.Count).IsEqualTo(1); + } + + /// A throwing handler on the items mirror fails the mutation. + /// A task representing the asynchronous test. + [Test] + public async Task ItemsMirrorHandler_Throws_MutationRethrows() + { + using ReactiveList list = []; + ((INotifyCollectionChanged)list.Items).CollectionChanged += static (_, _) => throw new InvalidOperationException(); + + await Assert.That(() => list.Add(1)).Throws(); + } + + /// A throwing stream observer fails the mutation. + /// A task representing the asynchronous test. + [Test] + public async Task StreamObserver_Throws_MutationRethrows() + { + using ReactiveList list = []; + using var subscription = list.Stream.Subscribe(new FailingObserver>(failOnNext: true, failOnCompleted: false)); + + await Assert.That(() => list.Add(1)).Throws(); + } + + /// A throwing versioned stream observer fails the mutation. + /// A task representing the asynchronous test. + [Test] + public async Task VersionedStreamObserver_Throws_MutationRethrows() + { + using ReactiveList list = []; + using var subscription = list.VersionedStream.Subscribe(new FailingObserver>(failOnNext: true, failOnCompleted: false)); + + await Assert.That(() => list.Add(1)).Throws(); + } + + /// A throwing current-items observer fails the mutation. + /// A task representing the asynchronous test. + [Test] + public async Task CurrentItemsObserver_Throws_MutationRethrows() + { + using ReactiveList list = []; + FailingObserver> observer = new(failOnNext: false, failOnCompleted: false); + using var subscription = list.CurrentItems.Subscribe(observer); + observer.FailOnNext = true; + + await Assert.That(() => list.Add(1)).Throws(); + } + + /// Observers that throw while completing make disposal rethrow after every stream was completed. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_ObserversThrowOnCompleted_DisposeRethrows() + { + ReactiveList list = []; + using var stream = list.Stream.Subscribe(new FailingObserver>(failOnNext: false, failOnCompleted: true)); + using var versioned = list.VersionedStream.Subscribe(new FailingObserver>(failOnNext: false, failOnCompleted: true)); + using var current = list.CurrentItems.Subscribe(new FailingObserver>(failOnNext: false, failOnCompleted: true)); + + await Assert.That(list.Dispose).Throws(); + await Assert.That(list.IsDisposed).IsTrue(); + } + + /// Disposing from inside a mirror handler skips the later delivery stages. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_InsideMirrorHandler_SkipsLaterStages() + { + ReactiveList list = []; + var collectionChanged = 0; + ((INotifyCollectionChanged)list.Items).CollectionChanged += (_, _) => list.Dispose(); + list.CollectionChanged += (_, _) => collectionChanged++; + + list.Add(1); + + await Assert.That(list.IsDisposed).IsTrue(); + await Assert.That(collectionChanged).IsEqualTo(0); + } + + /// Disposing from inside a current-items observer skips the later delivery stages. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_InsideCurrentItemsObserver_SkipsLaterStages() + { + ReactiveList list = []; + var collectionChanged = 0; + + // The observable replays the current contents on subscription, so only a non-empty snapshot disposes the list. + using var subscription = list.CurrentItems.Subscribe(items => + { + if (items.Any()) + { + list.Dispose(); + } + }); + list.CollectionChanged += (_, _) => collectionChanged++; + + list.Add(1); + + await Assert.That(list.IsDisposed).IsTrue(); + await Assert.That(collectionChanged).IsEqualTo(0); + } + + /// A current-items observable that nobody observes is marked stale by a mutation and refreshed on the next subscription. + /// A task representing the asynchronous test. + [Test] + public async Task CurrentItems_NoObservers_MutationMarksSnapshotStale() + { + using ReactiveList list = []; + using (list.CurrentItems.Subscribe(static _ => { })) + { + list.Add(1); + } + + list.Add(1); + IEnumerable latest = []; + using var subscription = list.CurrentItems.Subscribe(items => latest = items); + + await Assert.That(latest.Count()).IsEqualTo(1 + 1); + } + + /// An observer that throws from the callbacks selected at construction. + /// The value type. + /// Whether throws. + /// Whether throws. + private sealed class FailingObserver(bool failOnNext, bool failOnCompleted) : IObserver + { + /// Gets or sets a value indicating whether throws. + public bool FailOnNext { get; set; } = failOnNext; + + /// + /// Thrown when completion is configured to fail. + public void OnCompleted() + { + if (failOnCompleted) + { + throw new InvalidOperationException(); + } + } + + /// + public void OnError(Exception error) + { + } + + /// + /// Thrown when values are configured to fail. + public void OnNext(TValue value) + { + if (FailOnNext) + { + throw new InvalidOperationException(); + } + } + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListOperatorFuzzTests.cs b/src/tests/ReactiveList.Tests/ReactiveListOperatorFuzzTests.cs new file mode 100644 index 00000000..0fab1708 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListOperatorFuzzTests.cs @@ -0,0 +1,500 @@ +// 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. + +using CsCheck; + +namespace ReactiveList.Tests; + +/// CsCheck tests that compare the change-set and cache-notification operators with plain LINQ computations over the same input. +public class ReactiveListOperatorFuzzTests +{ + /// The largest item value; a small range keeps duplicates frequent. + private const int MaxValue = 9; + + /// The largest generated array length. + private const int MaxLength = 8; + + /// The number of random inputs per test. + private const int Iterations = 250; + + /// The number of CsCheck worker threads; one keeps runs repeatable per seed. + private const int Threads = 1; + + /// The number of reasons the generator can pick (add, remove, update, move and refresh). + private const int ReasonCount = 5; + + /// The divisor of the grouping key and of the even predicate. + private const int Divisor = 3; + + /// The operation kind that adds one item. + private const int AddOperation = 0; + + /// The operation kind that removes one item. + private const int RemoveOperation = 1; + + /// The operation kind that replaces one item. + private const int UpdateOperation = 2; + + /// The operation kind that adds two items. + private const int AddRangeOperation = 3; + + /// The operation kind that removes items by predicate. + private const int RemoveManyOperation = 4; + + /// The operation kind that replaces the whole contents. + private const int ReplaceAllOperation = 5; + + /// The divisor that defines even values. + private const int Even = 2; + + /// The number of list operations the generator can pick. + private const int OperationCount = 7; + + /// The generator for one change description. + private static readonly Gen Spec = + Gen.Select(Gen.Int[0, ReasonCount - 1], Gen.Int[0, MaxValue], Gen.Int[0, MaxValue], static (reason, value, other) => new ChangeSpec((ChangeReason)reason, value, other)); + + /// The generator for a stream of change sets. + private static readonly Gen Batches = Spec.Array[0, MaxLength].Array[0, MaxLength]; + + /// The generator for operations applied to a list. + private static readonly Gen Operations = + Gen.Select(Gen.Int[0, OperationCount - 1], Gen.Int[0, MaxValue], Gen.Int[0, MaxValue], static (kind, a, b) => new ListOperation(kind, a, b)).Array[0, MaxLength * 2]; + + /// The generator for initial list contents. + private static readonly Gen Initial = Gen.Int[0, MaxValue].Array[0, MaxLength]; + + /// Checks that WhereChanges keeps exactly the changes the predicate accepts, in order. + /// A completed task. + [Test] + public Task WhereChanges_MatchesLinq() + { + Batches.Sample( + static batches => Flatten(Run(batches, static source => source.WhereChanges(static change => change.Current % Divisor == 0))) + .SequenceEqual(Flatten(ToSets(batches)).Where(static change => change.Current % Divisor == 0)), + iter: Iterations, + threads: Threads); + return Task.CompletedTask; + } + + /// Checks that WhereReason keeps exactly the changes with that reason. + /// A completed task. + [Test] + public Task WhereReason_MatchesLinq() + { + Batches.Sample( + static batches => Flatten(Run(batches, static source => source.WhereReason(ChangeReason.Update))) + .SequenceEqual(Flatten(ToSets(batches)).Where(static change => change.Reason == ChangeReason.Update)), + iter: Iterations, + threads: Threads); + return Task.CompletedTask; + } + + /// Checks that the value-projecting SelectChanges maps current and previous items and keeps the metadata. + /// A completed task. + [Test] + public Task SelectChanges_Items_MatchesLinq() + { + Batches.Sample( + static batches => Flatten(Run(batches, static source => source.SelectChanges(static value => value * Divisor))) + .SequenceEqual(Flatten(ToSets(batches)).Select(static change => new Change( + change.Reason, + change.Current * Divisor, + change.Previous * Divisor, + change.CurrentIndex, + change.PreviousIndex))), + iter: Iterations, + threads: Threads); + return Task.CompletedTask; + } + + /// Checks that the change-projecting SelectChanges flattens to one result per change. + /// A completed task. + [Test] + public Task SelectChanges_Changes_MatchesLinq() + { + Batches.Sample( + static batches => + { + var results = new List(); + var source = new Signal>(); + using var subscription = source.SelectChanges(static change => change.Current + (int)change.Reason).Subscribe(results.Add); + foreach (var set in ToSets(batches)) + { + source.OnNext(set); + } + + return results.SequenceEqual(Flatten(ToSets(batches)).Select(static change => change.Current + (int)change.Reason)); + }, + iter: Iterations, + threads: Threads); + return Task.CompletedTask; + } + + /// Checks that OnAdd, OnRemove, OnUpdate and OnMove match LINQ filters of the same changes. + /// A completed task. + [Test] + public Task ReasonShortcuts_MatchLinq() + { + Batches.Sample(AreReasonShortcutsCorrect, iter: Iterations, threads: Threads); + return Task.CompletedTask; + } + + /// Checks that GroupingByChanges gives, for each change set, the same groups and members as LINQ. + /// A completed task. + [Test] + public Task GroupingByChanges_MatchesLinq() + { + Batches.Sample(AreGroupingsCorrect, iter: Iterations, threads: Threads); + return Task.CompletedTask; + } + + /// Checks that GroupByChanges routes every item to the group of its key in arrival order. + /// A completed task. + [Test] + public Task GroupByChanges_MatchesLinq() + { + Batches.Sample(AreGroupsCorrect, iter: Iterations, threads: Threads); + return Task.CompletedTask; + } + + /// Checks that SortBy stably orders each change set by key. + /// A completed task. + [Test] + public Task SortBy_MatchesStableLinqOrder() + { + Batches.Sample( + static batches => + { + var sets = Run(batches, static source => source.SortBy(static value => value % Divisor)); + var expected = ToSets(batches).Select(static set => set.OrderBy(static change => change.Current % Divisor).ToArray()).ToArray(); + return sets.Count == expected.Length && sets.Zip(expected, static (actual, order) => actual.SequenceEqual(order)).All(static same => same); + }, + iter: Iterations, + threads: Threads); + return Task.CompletedTask; + } + + /// Checks that replaying the filtered stream of a real list leaves exactly the matching items, whatever mutations ran. + /// A completed task. + [Test] + public Task FilterDynamic_ReplayMatchesLinqOverFinalContents() + { + Gen.Select(Initial, Operations).Sample( + static input => IsFilteredReplayCorrect(input.Item1, input.Item2), + iter: Iterations, + threads: Threads); + return Task.CompletedTask; + } + + /// Feeds the batches through an operator and collects its output. + /// The output item type. + /// The input batches. + /// Builds the operator under test from the source. + /// The emitted values. + private static List Run(ChangeSpec[][] batches, Func>, IObservable> operatorFactory) + { + var results = new List(); + using var source = new Signal>(); + using var subscription = operatorFactory(source).Subscribe(results.Add); + foreach (var set in ToSets(batches)) + { + source.OnNext(set); + } + + return results; + } + + /// Converts the generated descriptions to change sets, skipping empty ones as a real source never emits them. + /// The descriptions. + /// The change sets. + private static List> ToSets(ChangeSpec[][] batches) + { + var sets = new List>(); + foreach (var batch in batches) + { + if (batch.Length == 0) + { + continue; + } + + var changes = new Change[batch.Length]; + for (var i = 0; i < batch.Length; i++) + { + changes[i] = new(batch[i].Reason, batch[i].Value, batch[i].Other, i, i + 1); + } + + sets.Add(new(changes)); + } + + return sets; + } + + /// Flattens change sets to their changes. + /// The change sets. + /// All changes in order. + private static List> Flatten(IEnumerable> sets) + { + var all = new List>(); + foreach (var set in sets) + { + for (var i = 0; i < set.Count; i++) + { + all.Add(set[i]); + } + } + + return all; + } + + /// Checks the four reason shortcut operators against LINQ. + /// The input batches. + /// when all four agree. + private static bool AreReasonShortcutsCorrect(ChangeSpec[][] batches) + { + var all = Flatten(ToSets(batches)); + var adds = Run(batches, static source => source.OnAdd()); + var removes = Run(batches, static source => source.OnRemove()); + var updates = Run(batches, static source => source.OnUpdate()); + var moves = Run(batches, static source => source.OnMove()); + + return adds.SequenceEqual(all.Where(static c => c.Reason == ChangeReason.Add).Select(static c => c.Current)) + && removes.SequenceEqual(all.Where(static c => c.Reason == ChangeReason.Remove).Select(static c => c.Current)) + && updates.SequenceEqual(all.Where(static c => c.Reason == ChangeReason.Update).Select(static c => (c.Previous, c.Current))) + && moves.SequenceEqual(all.Where(static c => c.Reason == ChangeReason.Move).Select(static c => (c.Current, c.PreviousIndex, c.CurrentIndex))); + } + + /// Checks GroupingByChanges against LINQ for every change set. + /// The input batches. + /// when every change set is grouped as LINQ would. + private static bool AreGroupingsCorrect(ChangeSpec[][] batches) + { + var sets = ToSets(batches); + var actual = new List[] Members)>>(); + var source = new Signal>(); + using var subscription = source.GroupingByChanges(static value => value % Divisor).Subscribe(grouping => + { + actual[^1].Add((grouping.Key, [.. grouping])); + }); + + foreach (var set in sets) + { + actual.Add([]); + source.OnNext(set); + } + + for (var i = 0; i < sets.Count; i++) + { + var expected = Flatten([sets[i]]).GroupBy(static c => c.Current % Divisor).ToDictionary(static g => g.Key, static g => g.ToArray()); + if (actual[i].Count != expected.Count) + { + return false; + } + + foreach (var (key, members) in actual[i]) + { + if (!expected.TryGetValue(key, out var wanted) || !members.SequenceEqual(wanted)) + { + return false; + } + } + } + + return true; + } + + /// Checks GroupByChanges against LINQ over all emitted items. + /// The input batches. + /// when each group received exactly its key's items in order. + private static bool AreGroupsCorrect(ChangeSpec[][] batches) + { + var groups = new Dictionary>(); + var source = new Signal>(); + using var subscription = source.GroupByChanges(static value => value % Divisor).Subscribe(group => + { + var members = new List(); + groups[group.Key] = members; + _ = group.Subscribe(members.Add); + }); + + var sets = ToSets(batches); + foreach (var set in sets) + { + source.OnNext(set); + } + + var expected = Flatten(sets).GroupBy(static c => c.Current % Divisor).ToDictionary(static g => g.Key, static g => g.Select(static c => c.Current).ToArray()); + return groups.Count == expected.Count + && expected.All(pair => groups.TryGetValue(pair.Key, out var members) && members.SequenceEqual(pair.Value)); + } + + /// Applies operations to a list while its dynamically filtered stream is replayed onto a shadow collection, then compares with LINQ. + /// The initial list contents. + /// The operations to apply. + /// when the replay equals the matching items of the final contents. + private static bool IsFilteredReplayCorrect(int[] initial, ListOperation[] operations) + { + using var list = new ReactiveList(initial); + using var filters = new BehaviorSignal>(IsEven); + var shadow = initial.Where(IsEven).ToList(); + using var subscription = list.Stream.FilterDynamic(filters).Subscribe(notification => Replay(shadow, notification)); + + foreach (var operation in operations) + { + Apply(list, operation); + } + + return shadow.Order().SequenceEqual(list.ToArray().Where(IsEven).Order()); + } + + /// Tests whether a value is even. + /// The value. + /// when the value is even. + private static bool IsEven(int value) => value % Even == 0; + + /// Applies one operation to the list, ignoring invalid arguments. + /// The list. + /// The operation. + private static void Apply(ReactiveList list, ListOperation operation) + { + switch (operation.Kind) + { + case AddOperation: + { + list.Add(operation.A); + break; + } + + case RemoveOperation: + { + _ = list.Remove(operation.A); + break; + } + + case UpdateOperation: + { + list.Update(operation.A, operation.B); + break; + } + + case AddRangeOperation: + { + list.AddRange([operation.A, operation.B]); + break; + } + + case RemoveManyOperation: + { + _ = list.RemoveMany(value => value % Divisor == operation.A % Divisor); + break; + } + + case ReplaceAllOperation: + { + list.ReplaceAll([operation.A, operation.B, operation.A]); + break; + } + + default: + { + list.Clear(); + break; + } + } + } + + /// Replays one notification onto a shadow collection that tracks membership only. + /// The shadow collection. + /// The notification. + private static void Replay(List shadow, CacheNotify notification) + { + switch (notification.Action) + { + case CacheAction.Added: + { + shadow.Add(notification.Item); + break; + } + + case CacheAction.Removed: + { + RemoveOne(shadow, notification.Item); + break; + } + + case CacheAction.Updated: + { + RemoveOne(shadow, notification.Previous); + shadow.Add(notification.Item); + break; + } + + case CacheAction.Cleared: + { + shadow.Clear(); + break; + } + + case CacheAction.BatchAdded: + { + ReplayBatch(shadow, notification.Batch!, add: true); + break; + } + + case CacheAction.BatchRemoved: + { + ReplayBatch(shadow, notification.Batch!, add: false); + break; + } + + default: + { + break; + } + } + } + + /// Replays the items of a batch. + /// The shadow collection. + /// The batch. + /// Whether the items are added or removed. + private static void ReplayBatch(List shadow, PooledBatch batch, bool add) + { + for (var i = 0; i < batch.Count; i++) + { + if (add) + { + shadow.Add(batch.Items[i]); + } + else + { + RemoveOne(shadow, batch.Items[i]); + } + } + } + + /// Removes one occurrence of a value when present. + /// The shadow collection. + /// The value. + private static void RemoveOne(List shadow, int value) + { + var index = shadow.IndexOf(value); + if (index >= 0) + { + shadow.RemoveAt(index); + } + } + + /// Describes one generated change. + /// The change reason. + /// The current item. + /// The previous item. + private readonly record struct ChangeSpec(ChangeReason Reason, int Value, int Other); + + /// Describes one generated list operation. + /// The operation kind. + /// The first argument. + /// The second argument. + private readonly record struct ListOperation(int Kind, int A, int B); +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListOperatorLifecycleTests.cs b/src/tests/ReactiveList.Tests/ReactiveListOperatorLifecycleTests.cs new file mode 100644 index 00000000..4cf76e42 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListOperatorLifecycleTests.cs @@ -0,0 +1,92 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks that every change-set operator releases its source on dispose and passes completion and errors through. +public class ReactiveListOperatorLifecycleTests +{ + /// Subscribes to an operator's output, ignoring values. + /// The operator input. + /// Called with the error. + /// Called on completion. + /// The subscription. + private delegate IDisposable OperatorSubscriber(IObservable> source, Action onError, Action onCompleted); + + /// Gets the operators under test. + private static (string Name, OperatorSubscriber Subscribe)[] Operators => + [ + ("WhereChanges", static (source, onError, onCompleted) => source.WhereChanges(static _ => true).Subscribe(static _ => { }, onError, onCompleted)), + ("WhereReason", static (source, onError, onCompleted) => source.WhereReason(ChangeReason.Add).Subscribe(static _ => { }, onError, onCompleted)), + ("SelectChanges", static (source, onError, onCompleted) => source.SelectChanges((Func)Increment).Subscribe(static _ => { }, onError, onCompleted)), + ("SelectChangesProjection", static (source, onError, onCompleted) => source.SelectChanges((Func, int>)CurrentOf).Subscribe(static _ => { }, onError, onCompleted)), + ("OnAdd", static (source, onError, onCompleted) => source.OnAdd().Subscribe(static _ => { }, onError, onCompleted)), + ("OnRemove", static (source, onError, onCompleted) => source.OnRemove().Subscribe(static _ => { }, onError, onCompleted)), + ("OnUpdate", static (source, onError, onCompleted) => source.OnUpdate().Subscribe(static _ => { }, onError, onCompleted)), + ("OnMove", static (source, onError, onCompleted) => source.OnMove().Subscribe(static _ => { }, onError, onCompleted)), + ("GroupByChanges", static (source, onError, onCompleted) => source.GroupByChanges(static value => value).Subscribe(static _ => { }, onError, onCompleted)), + ("GroupingByChanges", static (source, onError, onCompleted) => source.GroupingByChanges(static value => value).Subscribe(static _ => { }, onError, onCompleted)), + ("SortBy", static (source, onError, onCompleted) => source.SortBy(static value => value).Subscribe(static _ => { }, onError, onCompleted)), + ]; + + /// Disposing the subscription releases the source subscription of every operator. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_ReleasesSource() + { + foreach (var (name, subscribe) in Operators) + { + using var source = new Signal>(); + var subscription = subscribe(source, static _ => { }, static () => { }); + await Assert.That(source.HasObservers).IsTrue().Because(name); + + subscription.Dispose(); + await Assert.That(source.HasObservers).IsFalse().Because(name); + } + } + + /// Source completion reaches the observer of every operator. + /// A task representing the asynchronous test. + [Test] + public async Task SourceCompletion_Completes() + { + foreach (var (name, subscribe) in Operators) + { + using var source = new Signal>(); + var completed = false; + using var subscription = subscribe(source, static _ => { }, () => completed = true); + + source.OnCompleted(); + await Assert.That(completed).IsTrue().Because(name); + } + } + + /// A source error reaches the observer of every operator. + /// A task representing the asynchronous test. + [Test] + public async Task SourceError_IsForwarded() + { + var failure = new InvalidOperationException("source failed"); + foreach (var (name, subscribe) in Operators) + { + using var source = new Signal>(); + Exception? received = null; + using var subscription = subscribe(source, error => received = error, static () => { }); + + source.OnError(failure); + await Assert.That(received).IsSameReferenceAs(failure).Because(name); + } + } + + /// Adds one to a value. + /// The value. + /// The incremented value. + private static int Increment(int value) => value + 1; + + /// Gets the current item of a change. + /// The change. + /// The current item. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int CurrentOf(Change change) => change.Current; +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListRemoveTests.cs b/src/tests/ReactiveList.Tests/ReactiveListRemoveTests.cs index 86cb0548..bdf4d66e 100644 --- a/src/tests/ReactiveList.Tests/ReactiveListRemoveTests.cs +++ b/src/tests/ReactiveList.Tests/ReactiveListRemoveTests.cs @@ -378,6 +378,22 @@ public async Task RemoveMany_ShouldReturnZeroWhenNoMatch() await Assert.That(fixture.Count).IsEqualTo(TestData.TestValueThree); } + /// A bulk removal leaves a null item in place when it was not requested. + /// A task representing the asynchronous test. + [Test] + public async Task RemoveItems_WithLargeRequest_SkipsUnrequestedNull() + { + const int RequestCount = 9; + var requested = Enumerable.Repeat("remove", RequestCount); + using ReactiveList fixture = ["remove", null!, "keep"]; + + fixture.Remove(requested); + + await Assert.That(fixture.Count).IsEqualTo(TestData.TestValueTwo); + await Assert.That(fixture[0]).IsNull(); + await Assert.That(fixture[1]).IsEqualTo("keep"); + } + /// RemoveMany should throw ArgumentNullException for null predicate. /// A task representing the asynchronous test. [Test] diff --git a/src/tests/ReactiveList.Tests/ReactiveListRetentionTests.cs b/src/tests/ReactiveList.Tests/ReactiveListRetentionTests.cs new file mode 100644 index 00000000..b234aba9 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListRetentionTests.cs @@ -0,0 +1,245 @@ +// 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. + +using System.Collections.Specialized; +using System.ComponentModel; + +namespace ReactiveList.Tests; + +/// Checks with weak references that a does not keep items, observers or mirrors alive after they are released. +public class ReactiveListRetentionTests +{ + /// The number of collection rounds that give the runtime a fair chance to free unreachable objects. + private const int CollectionRounds = 3; + + /// Removed items are released once the next change replaces the history that shows them. + /// A task representing the asynchronous test. + [Test] + public async Task ClearedItems_AreReleased_OnceTheHistoryMovesOn() + { + using ReactiveList list = new(); + var weak = Fill(list); + using var subscription = list.Stream.Subscribe(static _ => { }); + _ = list.Items; + + list.Clear(); + list.Add(new()); + + await Assert.That(IsAnyAlive(weak)).IsFalse(); + } + + /// An edit keeps the contents it saw for the stream only while delivering, not as history. + /// A task representing the asynchronous test. + [Test] + public async Task Edit_DoesNotRetainItsBeforeOrAfterContents() + { + using ReactiveList list = new(); + var weak = Fill(list); + using var subscription = list.Stream.Subscribe(static _ => { }); + _ = list.Items; + + list.Edit(static editor => editor.Add(new())); + list.RemoveRange(0, weak.Length); + list.Add(new()); + + await Assert.That(IsAnyAlive(weak)).IsFalse(); + } + + /// Replacing all contents releases the old items once the next change replaces the history. + /// A task representing the asynchronous test. + [Test] + public async Task ReplacedItems_AreReleased_OnceTheHistoryMovesOn() + { + using ReactiveList list = new(); + var weak = Fill(list); + _ = list.Items; + + list.ReplaceAll([new()]); + list.Add(new()); + + await Assert.That(IsAnyAlive(weak)).IsFalse(); + } + + /// A stream observer that unsubscribed is no longer referenced by the list. + /// A task representing the asynchronous test. + [Test] + public async Task UnsubscribedStreamObserver_IsReleased() + { + using ReactiveList list = new(); + var weak = SubscribeAndUnsubscribe(list); + + list.Add(new()); + + await Assert.That(IsAnyAlive([weak])).IsFalse(); + } + + /// A handler removed from is no longer referenced by the list. + /// A task representing the asynchronous test. + [Test] + public async Task RemovedCollectionChangedHandler_IsReleased() + { + using ReactiveList list = new(); + var weak = AttachAndDetachHandler(list); + + list.Add(new()); + + await Assert.That(IsAnyAlive([weak])).IsFalse(); + } + + /// A disposed list, its mirrors and its observers can all be collected. + /// A task representing the asynchronous test. + [Test] + public async Task DisposedList_WithMirrorsAndObservers_IsCollectible() + { + var weak = CreateDisposedList(); + + await Assert.That(IsAnyAlive(weak)).IsFalse(); + } + + /// Auto refresh stops watching an item when it is removed, cleared or the subscription ends. + /// A task representing the asynchronous test. + [Test] + public async Task AutoRefresh_DetachesHandlers_OnRemovalClearAndDispose() + { + using var list = new ReactiveList(); + var removed = new Notifier(); + var cleared = new Notifier(); + var kept = new Notifier(); + var subscription = list.Connect().AutoRefresh().Subscribe(static _ => { }); + + list.Add(removed); + list.Add(kept); + await Assert.That(removed.HandlerCount).IsEqualTo(1); + await Assert.That(kept.HandlerCount).IsEqualTo(1); + + _ = list.Remove(removed); + await Assert.That(removed.HandlerCount).IsEqualTo(0); + + list.Clear(); + await Assert.That(kept.HandlerCount).IsEqualTo(0); + + list.Add(cleared); + await Assert.That(cleared.HandlerCount).IsEqualTo(1); + subscription.Dispose(); + await Assert.That(cleared.HandlerCount).IsEqualTo(0); + } + + /// Collects garbage until the given weak references are dead or the rounds run out. + /// The weak references. + /// when any target is still alive. + private static bool IsAnyAlive(WeakReference[] weak) + { + // GetTotalMemory with forceFullCollection runs a blocking collection, which is what the weak references need. + for (var round = 0; round < CollectionRounds; round++) + { + _ = GC.GetTotalMemory(forceFullCollection: true); + } + + return Array.Exists(weak, static reference => reference.IsAlive); + } + + /// Fills a list with items and returns weak references to them. + /// The list. + /// Weak references to the items. + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference[] Fill(ReactiveList list) + { + Payload[] items = [new(), new(), new()]; + list.AddRange(items); + return [.. items.Select(static item => new WeakReference(item))]; + } + + /// Subscribes an observer to the stream and unsubscribes it again. + /// The list. + /// A weak reference to the observer. + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference SubscribeAndUnsubscribe(ReactiveList list) + { + CountingObserver observer = new(); + list.Stream.Subscribe(observer).Dispose(); + return new(observer); + } + + /// Adds a collection-changed handler and removes it again. + /// The list. + /// A weak reference to the handler target. + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference AttachAndDetachHandler(ReactiveList list) + { + CountingObserver target = new(); + list.CollectionChanged += target.OnChanged; + list.Add(new()); + list.CollectionChanged -= target.OnChanged; + return new(target); + } + + /// Creates a list with every kind of observer, uses it, disposes it and drops it. + /// Weak references to the list, a mirror and the observers. + [MethodImpl(MethodImplOptions.NoInlining)] + private static WeakReference[] CreateDisposedList() + { + ReactiveList list = new(); + CountingObserver observer = new(); + _ = list.Stream.Subscribe(observer); + list.CollectionChanged += observer.OnChanged; + var mirror = list.Items; + _ = list.ItemsAdded; + _ = list.ItemsRemoved; + _ = list.ItemsChanged; + list.Add(new()); + list.AddRange([new(), new()]); + list.Clear(); + list.Dispose(); + return [new(list), new(observer), new(mirror)]; + } + + /// An item that can be told apart by reference. + private sealed class Payload + { + /// Gets a value that makes each item a distinct object. + public Guid Identity { get; } = Guid.NewGuid(); + } + + /// An observer that counts what it receives. + private sealed class CountingObserver : IObserver> + { + /// The number of notifications received. + private int _count; + + /// + public void OnCompleted() + { + } + + /// + public void OnError(Exception error) + { + } + + /// + public void OnNext(CacheNotify value) => _count++; + + /// Counts a collection change. + /// The sender. + /// The arguments. + public void OnChanged(object? sender, NotifyCollectionChangedEventArgs args) => _count++; + } + + /// An item that reports how many handlers are attached to its property-changed event. + private sealed class Notifier : INotifyPropertyChanged + { + /// The attached handlers. + private PropertyChangedEventHandler? _handlers; + + /// + public event PropertyChangedEventHandler? PropertyChanged + { + add => _handlers += value; + remove => _handlers -= value; + } + + /// Gets the number of attached handlers. + public int HandlerCount => _handlers?.GetInvocationList().Length ?? 0; + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListSerializationTests.cs b/src/tests/ReactiveList.Tests/ReactiveListSerializationTests.cs index 60e78dae..eb70343c 100644 --- a/src/tests/ReactiveList.Tests/ReactiveListSerializationTests.cs +++ b/src/tests/ReactiveList.Tests/ReactiveListSerializationTests.cs @@ -10,6 +10,15 @@ namespace ReactiveList.Tests; /// Tests for ReactiveList serialization. public class ReactiveListSerializationTests { + /// The number of writer threads in the lock test. + private const int WriterCount = 4; + + /// The number of items added by each writer. + private const int ItemsPerWriter = 200; + + /// The number of indexer reads that earns a snapshot. + private const int SnapshotReads = 5; + /// ReactiveList should be serializable. /// A task representing the asynchronous test. [Test] @@ -110,6 +119,103 @@ public async Task ReactiveListWithComplexTypes_ShouldBeSerializable() await Assert.That(deserialized[1].Age).IsEqualTo(TestValueTwentyFive); } + /// A deserialized list has a working lock, so concurrent writers lose no items. + /// A task representing the asynchronous test. + [Test] + public async Task DeserializedReactiveList_LockSerializesConcurrentWriters() + { + var deserialized = RoundTrip(CreateSource(TestValueThree)); + + var tasks = new Task[WriterCount]; + for (var writer = 0; writer < tasks.Length; writer++) + { + tasks[writer] = Task.Run(() => + { + for (var i = 0; i < ItemsPerWriter; i++) + { + deserialized.Add(i); + } + }); + } + + await Task.WhenAll(tasks); + + await Assert.That(deserialized.Count).IsEqualTo(TestValueThree + (WriterCount * ItemsPerWriter)); + await Assert.That(deserialized.ToArray().Length).IsEqualTo(deserialized.Count); + } + + /// A deserialized list is not disposed, even when the source list was disposed before serialization. + /// A task representing the asynchronous test. + [Test] + public async Task DeserializedReactiveList_IsNotDisposed() + { + var source = CreateSource(TestValueThree); + source.Dispose(); + + var deserialized = RoundTrip(source); + + await Assert.That(deserialized.IsDisposed).IsFalse(); + deserialized.Add(TestValueFour); + await Assert.That(deserialized.Count).IsEqualTo(TestValueFour); + deserialized.Dispose(); + _ = Assert.Throws(() => deserialized.Add(TestValueFive)); + } + + /// The lazily created mirror collections of a deserialized list are built from its contents and follow later changes. + /// A task representing the asynchronous test. + [Test] + public async Task DeserializedReactiveList_MirrorsReflectContentsAndFollowChanges() + { + var source = CreateSource(TestValueThree); + _ = source.Items; + + var deserialized = RoundTrip(source); + + await Assert.That(deserialized.Items).IsEquivalentTo([1, TestValueTwo, TestValueThree], CollectionOrdering.Matching); + deserialized.Add(TestValueFour); + await Assert.That(deserialized.Items).IsEquivalentTo([1, TestValueTwo, TestValueThree, TestValueFour], CollectionOrdering.Matching); + await Assert.That(deserialized.Added).IsNotNull(); + await Assert.That(deserialized.CurrentItems).IsNotNull(); + } + + /// The snapshot used by lock-free reads of a deserialized list is valid and is replaced after each mutation. + /// A task representing the asynchronous test. + [Test] + public async Task DeserializedReactiveList_SnapshotIsValidAndRefreshes() + { + var deserialized = RoundTrip(CreateSource(TestValueThree)); + + // Repeated reads build the snapshot that lock-free reads use. + for (var i = 0; i < SnapshotReads; i++) + { + await Assert.That(deserialized[0]).IsEqualTo(1); + } + + var before = deserialized.AsMemory(); + await Assert.That(before.ToArray()).IsEquivalentTo([1, TestValueTwo, TestValueThree], CollectionOrdering.Matching); + await Assert.That(deserialized.ToArray()).IsEquivalentTo([1, TestValueTwo, TestValueThree], CollectionOrdering.Matching); + + deserialized.Add(TestValueFour); + + await Assert.That(before.ToArray()).IsEquivalentTo([1, TestValueTwo, TestValueThree], CollectionOrdering.Matching); + await Assert.That(deserialized.AsMemory().ToArray()).IsEquivalentTo([1, TestValueTwo, TestValueThree, TestValueFour], CollectionOrdering.Matching); + await Assert.That(deserialized.Count).IsEqualTo(TestValueFour); + } + + /// Creates a list of the first positive integers. + /// The number of items. + /// The list. + private static ReactiveList CreateSource(int count) + { + var list = new ReactiveList(); + for (var i = 1; i <= count; i++) + { + list.Add(i); + } + + return list; + } + /// Round-trips a value through the .NET Framework serializer. /// The value type. /// The value to round-trip. diff --git a/src/tests/ReactiveList.Tests/ReactiveListSilentClearTests.cs b/src/tests/ReactiveList.Tests/ReactiveListSilentClearTests.cs new file mode 100644 index 00000000..a20acb7a --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListSilentClearTests.cs @@ -0,0 +1,57 @@ +// 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. + +namespace ReactiveList.Tests; + +/// A clear that does not notify must still keep versioned observers equal to the list. +public sealed class ReactiveListSilentClearTests +{ + /// A versioned subscriber that copied the list before a silent clear hears a payloadless reset. + /// A task representing the asynchronous test. + [Test] + public async Task VersionedStream_AfterSilentClear_ReplicaIsEmpty() + { + using var list = new ReactiveList([1, TestData.TestValueTwo]); + using var replica = new VersionedListReplica(list); + + list.ClearWithoutDeallocation(notifyChange: false); + + await Assert.That(replica.Snapshot()).IsEmpty(); + } + + /// The silent clear announces exactly one reset, with the version of the clear and no payload. + /// A task representing the asynchronous test. + [Test] + public async Task VersionedStream_AfterSilentClear_CarriesOneVersionedReset() + { + using var list = new ReactiveList([1, TestData.TestValueTwo]); + var received = new List>(); + using var subscription = list.VersionedStream.Subscribe(received.Add); + + list.ClearWithoutDeallocation(notifyChange: false); + + await Assert.That(received.Count).IsEqualTo(1); + await Assert.That(received[0].Notification.Action).IsEqualTo(CacheAction.Reset); + await Assert.That(received[0].Notification.Batch).IsNull(); + await Assert.That(received[0].Version).IsEqualTo(list.Version); + } + + /// The legacy stream and collection-changed event stay silent, as documented. + /// A task representing the asynchronous test. + [Test] + public async Task LegacyNotifications_AfterSilentClear_StayQuiet() + { + using var list = new ReactiveList([1, TestData.TestValueTwo]); + var streamed = new List>(); + var raised = 0; + using var subscription = list.Stream.Subscribe(streamed.Add); + list.CollectionChanged += (_, _) => raised++; + + list.ClearWithoutDeallocation(notifyChange: false); + + await Assert.That(streamed).IsEmpty(); + await Assert.That(raised).IsEqualTo(0); + await Assert.That(list.Count).IsEqualTo(0); + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListSnapshotContractTests.cs b/src/tests/ReactiveList.Tests/ReactiveListSnapshotContractTests.cs new file mode 100644 index 00000000..0c354e9a --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListSnapshotContractTests.cs @@ -0,0 +1,132 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Pins what and return while the list is mutated. +public class ReactiveListSnapshotContractTests +{ + /// The first value. + private const int One = 1; + + /// The second value. + private const int Two = 2; + + /// The third value. + private const int Three = 3; + + /// The number of writer threads in the concurrency test. + private const int WriterCount = 4; + + /// The number of operations each writer performs. + private const int WriterOperations = 500; + + /// A memory region taken before a mutation keeps showing the old contents. + /// A task representing the asynchronous test. + [Test] + public async Task AsMemory_IsNotAffectedByLaterMutation() + { + using var list = new ReactiveList([One, Two]); + var before = list.AsMemory(); + + list.Add(Three); + _ = list.Remove(One); + list.Clear(); + + await Assert.That(before.ToArray()).IsEquivalentTo([One, Two], CollectionOrdering.Matching); + await Assert.That(list.AsMemory().Length).IsEqualTo(0); + } + + /// A span copied before a mutation keeps the old contents, and a new call sees the new contents. + /// A task representing the asynchronous test. + [Test] + public async Task AsSpan_ReflectsTheListOnlyAtTheTimeOfTheCall() + { + using var list = new ReactiveList([One, Two]); + + var first = CopySpan(list); + list.Add(Three); + var second = CopySpan(list); + + await Assert.That(first).IsEquivalentTo([One, Two], CollectionOrdering.Matching); + await Assert.That(second).IsEquivalentTo([One, Two, Three], CollectionOrdering.Matching); + } + + /// Calls with no mutation in between share one snapshot, and a mutation replaces it. + /// A task representing the asynchronous test. + [Test] + public async Task RepeatedCalls_ShareOneSnapshotUntilTheNextMutation() + { + using var list = new ReactiveList([One, Two]); + + var first = list.AsMemory(); + var second = list.AsMemory(); + await Assert.That(first.Equals(second)).IsTrue(); + + list.Add(Three); + var third = list.AsMemory(); + await Assert.That(first.Equals(third)).IsFalse(); + await Assert.That(third.Length).IsEqualTo(Three); + } + + /// A memory region stays readable after the list is disposed. + /// A task representing the asynchronous test. + [Test] + public async Task AsMemory_StaysReadableAfterDispose() + { + var list = new ReactiveList([One, Two]); + var before = list.AsMemory(); + + list.Dispose(); + + await Assert.That(before.ToArray()).IsEquivalentTo([One, Two], CollectionOrdering.Matching); + await Assert.That(list.AsMemory().ToArray()).IsEquivalentTo([One, Two], CollectionOrdering.Matching); + } + + /// Under concurrent writers every region read is a state the list really held, never a torn one. + /// A task representing the asynchronous test. + [Test] + public async Task AsMemory_UnderConcurrentWriters_NeverShowsATornState() + { + using var list = new ReactiveList(); + var torn = 0; + var stop = false; + var reader = Task.Run(() => + { + while (!Volatile.Read(ref stop)) + { + var region = list.AsMemory().ToArray(); + if (region.Length % Two != 0) + { + _ = Interlocked.Increment(ref torn); + } + } + }); + + var writers = new Task[WriterCount]; + for (var writer = 0; writer < writers.Length; writer++) + { + writers[writer] = Task.Run(() => + { + for (var i = 0; i < WriterOperations; i++) + { + list.AddRange([i, i]); + } + }); + } + + await Task.WhenAll(writers); + Volatile.Write(ref stop, true); + await reader; + + await Assert.That(torn).IsEqualTo(0); + await Assert.That(list.AsMemory().Length).IsEqualTo(WriterCount * WriterOperations * Two); + } + + /// Copies the current span so it can cross an await. + /// The list. + /// The copy. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int[] CopySpan(ReactiveList list) => list.AsSpan().ToArray(); +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListStreamReplayFuzzTests.cs b/src/tests/ReactiveList.Tests/ReactiveListStreamReplayFuzzTests.cs new file mode 100644 index 00000000..9ff93915 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListStreamReplayFuzzTests.cs @@ -0,0 +1,296 @@ +// 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. + +using CsCheck; + +namespace ReactiveList.Tests; + +/// CsCheck tests that replay onto a copy of the list and expect the copy to end equal to the list. +public class ReactiveListStreamReplayFuzzTests +{ + /// The largest item value; a small range keeps duplicates frequent. + private const int MaxValue = 7; + + /// The number of random inputs per test. + private const int Iterations = 400; + + /// The number of CsCheck worker threads; one keeps runs repeatable per seed. + private const int Threads = 1; + + /// The largest generated operation count. + private const int MaxOperations = 24; + + /// The largest generated initial length. + private const int MaxInitial = 8; + + /// The divisor used by predicate-based operations. + private const int Divisor = 3; + + /// The index in of the edit that adds, removes and reorders. + private const int EditOperation = 10; + + /// The index in of the whole-list replacement. + private const int ReplaceAllOperation = 9; + + /// The operations the generator picks from; operations that do not fit the current contents do nothing. + private static readonly Action, Operation>[] Operations = + [ + static (list, op) => list.Add(op.A), + static (list, op) => list.Insert(list.Count == 0 ? 0 : op.B % (list.Count + 1), op.A), + static (list, op) => _ = list.Remove(op.A), + static (list, op) => + { + if (list.Count > 0) + { + list.RemoveAt(op.A % list.Count); + } + }, + static (list, op) => + { + if (list.Count > 1) + { + list.Move(op.A % list.Count, op.B % list.Count); + } + }, + static (list, op) => + { + if (list.Count > 0) + { + list[op.A % list.Count] = op.B; + } + }, + static (list, op) => list.AddRange([op.A, op.B, op.A]), + static (list, op) => _ = list.RemoveMany(value => value % Divisor == op.A % Divisor), + static (list, op) => list.Remove([op.A, op.B]), + static (list, op) => list.ReplaceAll([op.B, op.A, op.B]), + static (list, op) => list.Edit(editor => + { + editor.Add(op.A); + _ = editor.Remove(op.B); + if (editor.Count > 1) + { + editor.Move(0, editor.Count - 1); + } + }), + static (list, _) => list.Clear(), + ]; + + /// The generator for one operation. + private static readonly Gen Op = Gen.Select( + Gen.Int[0, Operations.Length - 1], + Gen.Int[0, MaxValue], + Gen.Int[0, MaxValue], + static (kind, a, b) => new Operation(kind, a, b)); + + /// The generator for a whole scenario: initial contents, operations and the point at which the replica copies the list. + private static readonly Gen Scenarios = Gen.Select( + Gen.Int[0, MaxValue].Array[0, MaxInitial], + Op.Array[0, MaxOperations], + Gen.Int[0, MaxOperations], + static (initial, operations, copyAt) => new Scenario(initial, operations, copyAt)); + + /// A replica copied from the list at any point and then fed the stream ends equal to the list. + /// Whether the changes are deferred. + /// A completed task. + [Test] + [Arguments(false)] + [Arguments(true)] + public Task Replay_FromAnySnapshot_EndsEqualToTheList(bool defer) + { + Scenarios.Sample( + scenario => + { + using var list = new ReactiveList(scenario.Initial); + var replica = new Replica(); + IDisposable? subscription = null; + try + { + using (defer ? list.DeferNotifications() : default) + { + for (var i = 0; i < scenario.Operations.Length; i++) + { + if (i == scenario.CopyAt) + { + subscription = Attach(list, replica); + } + + Apply(list, scenario.Operations[i]); + } + + subscription ??= Attach(list, replica); + } + + return replica.Items.SequenceEqual(list.ToArray()); + } + finally + { + subscription?.Dispose(); + } + }, + iter: Iterations, + threads: Threads); + return Task.CompletedTask; + } + + /// Replaying the notifications of rewriting changes onto a copy that already includes them leaves the copy equal to the list. + /// A completed task. + [Test] + public Task Replay_OfRewritesOntoTheirOwnResult_EndsEqualToTheList() + { + Scenarios.Sample( + static scenario => + { + using var list = new ReactiveList(scenario.Initial); + for (var i = 0; i < scenario.Operations.Length; i++) + { + Apply(list, scenario.Operations[i]); + } + + var recorded = new List>(); + using var recording = list.Stream.Subscribe(recorded.Add); + Apply(list, new(EditOperation, scenario.CopyAt, scenario.Initial.Length)); + Apply(list, new(ReplaceAllOperation, scenario.Initial.Length, scenario.CopyAt)); + + var replica = new Replica(); + replica.Items.AddRange(list.ToArray()); + for (var i = 0; i < recorded.Count; i++) + { + replica.Apply(recorded[i]); + } + + return replica.Items.SequenceEqual(list.ToArray()); + }, + iter: Iterations, + threads: Threads); + return Task.CompletedTask; + } + + /// Copies the list into a replica and starts feeding it from the stream. + /// The list. + /// The replica. + /// The subscription. + private static IDisposable Attach(ReactiveList list, Replica replica) + { + replica.Items.Clear(); + replica.Items.AddRange(list.ToArray()); + return list.Stream.Subscribe(replica.Apply); + } + + /// Applies one generated operation to the list. + /// The list. + /// The operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Apply(ReactiveList list, Operation op) => Operations[op.Kind](list, op); + + /// One generated list operation. + /// The index of the operation in . + /// The first argument. + /// The second argument. + private readonly record struct Operation(int Kind, int A, int B); + + /// A copy of a list that is kept up to date from its stream. + private sealed class Replica + { + /// Gets the copied items. + public List Items { get; } = []; + + /// Applies one notification. + /// The notification. + public void Apply(CacheNotify notification) + { + switch (notification.Action) + { + case CacheAction.Added: + { + Items.Insert(notification.CurrentIndex, notification.Item); + break; + } + + case CacheAction.Removed: + { + Items.RemoveAt(notification.CurrentIndex); + break; + } + + case CacheAction.Updated: + { + Items[notification.CurrentIndex] = notification.Item; + break; + } + + case CacheAction.Moved: + { + Items.RemoveAt(notification.PreviousIndex); + Items.Insert(notification.CurrentIndex, notification.Item); + break; + } + + case CacheAction.Cleared: + { + Items.Clear(); + break; + } + + case CacheAction.BatchAdded: + { + InsertBatch(notification); + break; + } + + case CacheAction.BatchRemoved: + { + RemoveBatch(notification); + break; + } + + case CacheAction.Reset: + { + Items.Clear(); + InsertBatch(notification); + break; + } + + case CacheAction.Refreshed or CacheAction.BatchOperation: + { + break; + } + } + } + + /// Inserts a batch at its index, or at the end when it has none. + /// The notification. + private void InsertBatch(CacheNotify notification) + { + var batch = notification.Batch!; + var index = notification.CurrentIndex < 0 ? Items.Count : notification.CurrentIndex; + for (var i = 0; i < batch.Count; i++) + { + Items.Insert(index + i, batch.Items[i]); + } + } + + /// Removes a batch by position, or by value when it has no position. + /// The notification. + private void RemoveBatch(CacheNotify notification) + { + var batch = notification.Batch!; + if (notification.CurrentIndex >= 0) + { + Items.RemoveRange(notification.CurrentIndex, batch.Count); + return; + } + + for (var i = 0; i < batch.Count; i++) + { + _ = Items.Remove(batch.Items[i]); + } + } + } + + /// One generated scenario. + /// The initial contents. + /// The operations. + /// The operation index before which the replica copies the list. + private sealed record Scenario(int[] Initial, Operation[] Operations, int CopyAt); +} diff --git a/src/tests/ReactiveList.Tests/ReactiveListThrowingUserCodeTests.cs b/src/tests/ReactiveList.Tests/ReactiveListThrowingUserCodeTests.cs new file mode 100644 index 00000000..43849436 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveListThrowingUserCodeTests.cs @@ -0,0 +1,127 @@ +// 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. + +namespace ReactiveList.Tests; + +/// User equality code that throws in the middle of an operation must neither corrupt the list nor leave a change unannounced. +public sealed class ReactiveListThrowingUserCodeTests +{ + /// The number of requested items that selects the hashing removal path. + private const int HashedRemovalSize = 12; + + /// The first item name. + private const string Alpha = "alpha"; + + /// The second item name. + private const string Beta = "beta"; + + /// The third item name. + private const string Gamma = "gamma"; + + /// The name of the item that replaces the second one. + private const string Replacement = "replacement"; + + /// The name of the item that a removal asks for. + private const string Wanted = "wanted"; + + /// An edit whose difference calculation throws is still committed and announced, and the exception reaches the caller. + /// A task representing the asynchronous test. + [Test] + public async Task Edit_WhenEqualityThrowsWhileComparing_CommitsAndAnnouncesTheEdit() + { + var (first, second, third, other) = Create(Alpha, Beta, Gamma, Replacement); + using var list = new ReactiveList([first, second, third]); + using var replica = new VersionedListReplica(list); + var versionBefore = list.Version; + other.Failure.OnHash = true; + + Action edit = () => list.Edit(editor => editor[1] = other); + + await Assert.That(edit).Throws(); + await Assert.That(Names(list.ToArray())).IsEquivalentTo([Alpha, Replacement, Gamma], CollectionOrdering.Matching); + await Assert.That(list.Count).IsEqualTo(TestData.TestValueThree); + await Assert.That(list.Version).IsGreaterThan(versionBefore); + await Assert.That(Names(replica.Snapshot())).IsEquivalentTo([Alpha, Replacement, Gamma], CollectionOrdering.Matching); + } + + /// Releasing a deferral whose difference calculation throws still announces the scope and leaves the list usable. + /// A task representing the asynchronous test. + [Test] + public async Task DeferralRelease_WhenEqualityThrowsWhileComparing_AnnouncesTheScope() + { + var (first, second, third, other) = Create(Alpha, Beta, Gamma, Replacement); + using var list = new ReactiveList([first, second, third]); + using var replica = new VersionedListReplica(list); + var deferral = list.DeferNotifications(); + list[1] = other; + other.Failure.OnHash = true; + + Action release = deferral.Dispose; + + await Assert.That(release).Throws(); + await Assert.That(Names(replica.Snapshot())).IsEquivalentTo([Alpha, Replacement, Gamma], CollectionOrdering.Matching); + + other.Failure.OnHash = false; + list.Add(new("delta")); + await Assert.That(Names(replica.Snapshot())).IsEquivalentTo([Alpha, Replacement, Gamma, "delta"], CollectionOrdering.Matching); + } + + /// A hash code that throws part-way through a hashed removal leaves the list exactly as it was. + /// A task representing the asynchronous test. + [Test] + public async Task RemoveRange_WhenHashingThrowsPartWay_LeavesTheListUnchanged() + { + var (first, wanted, third, last) = Create(Alpha, Wanted, Beta, Gamma); + using var list = new ReactiveList([first, wanted, third, last]); + using var replica = new VersionedListReplica(list); + var versionBefore = list.Version; + var requested = new List { new(Wanted) }; + for (var i = 0; i < HashedRemovalSize; i++) + { + requested.Add(new($"missing{i}")); + } + + last.Failure.OnHash = true; + Action remove = () => list.Remove(requested); + + await Assert.That(remove).Throws(); + await Assert.That(Names(list.ToArray())).IsEquivalentTo([Alpha, Wanted, Beta, Gamma], CollectionOrdering.Matching); + await Assert.That(list.Count).IsEqualTo(list.ToArray().Length); + await Assert.That(list.Version).IsEqualTo(versionBefore); + await Assert.That(Names(replica.Snapshot())).IsEquivalentTo([Alpha, Wanted, Beta, Gamma], CollectionOrdering.Matching); + } + + /// An equality check that throws part-way through a short removal leaves the list exactly as it was. + /// A task representing the asynchronous test. + [Test] + public async Task RemoveRange_WhenEqualsThrowsPartWayOnTheScanPath_LeavesTheListUnchanged() + { + var (first, wanted, third, last) = Create(Alpha, Wanted, Beta, Gamma); + using var list = new ReactiveList([first, wanted, third, last]); + last.Failure.OnEquals = true; + + Action remove = () => list.Remove([new ThrowingEqualityItem(Wanted), new ThrowingEqualityItem("never")]); + + await Assert.That(remove).Throws(); + await Assert.That(Names(list.ToArray())).IsEquivalentTo([Alpha, Wanted, Beta, Gamma], CollectionOrdering.Matching); + await Assert.That(list.Count).IsEqualTo(list.ToArray().Length); + } + + /// Creates four items with the given names. + /// The first name. + /// The second name. + /// The third name. + /// The fourth name. + /// The items. + private static (ThrowingEqualityItem First, ThrowingEqualityItem Second, ThrowingEqualityItem Third, ThrowingEqualityItem Fourth) Create( + string first, + string second, + string third, + string fourth) => (new(first), new(second), new(third), new(fourth)); + + /// Projects the names of items. + /// The items. + /// The names. + private static string[] Names(ThrowingEqualityItem[] items) => [.. items.Select(static item => item.Name)]; +} diff --git a/src/tests/ReactiveList.Tests/ReactiveViewFuzzTests.cs b/src/tests/ReactiveList.Tests/ReactiveViewFuzzTests.cs new file mode 100644 index 00000000..e2fe62ea --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveViewFuzzTests.cs @@ -0,0 +1,185 @@ +// 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. + +using CsCheck; + +namespace ReactiveList.Tests; + +/// Model-based fuzz tests for the filtered views over reactive and quaternary lists. +public class ReactiveViewFuzzTests +{ + /// The number of generated cases per property. + private const int Iterations = 150; + + /// The number of generated cases per throttled property. + private const int ThrottledIterations = 25; + + /// The coalescing window for throttled cases, in milliseconds. + private const int ThrottleMilliseconds = 5; + + /// The longest generated mutation sequence. + private const int MaxOps = 25; + + /// A view over a reactive list holds exactly the matching source items. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task ReactiveView_OverReactiveList_ConvergesToFilteredSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static async (initial, ops) => + { + using var list = new ReactiveList(); + list.AddRange(initial); + using var view = new ReactiveView(list, ViewFuzzSupport.Passes, TimeSpan.Zero, Sequencer.Immediate); + + foreach (var op in ops) + { + ViewFuzzSupport.Apply(list, op); + } + + list.Add(ViewFuzzSupport.Sentinel); + await ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Holds(view.Items, ViewFuzzSupport.Sentinel)); + + var expected = ViewFuzzSupport.Sorted(list.Where(ViewFuzzSupport.Passes)); + await Assert.That(ViewFuzzSupport.Sorted(view.Items)).IsEquivalentTo(expected, CollectionOrdering.Matching); + }, + iter: Iterations, + threads: 1); + + /// A view over a quaternary list holds exactly the matching source items. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task ReactiveView_OverQuaternaryList_ConvergesToFilteredSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static async (initial, ops) => + { + using var list = new QuaternaryList(); + list.AddRange(initial); + using var view = new ReactiveView(list, ViewFuzzSupport.Passes, TimeSpan.Zero, Sequencer.Immediate); + + foreach (var op in ops) + { + ViewFuzzSupport.Apply(list, op); + } + + await AssertAfterDrainAsync(list, view); + }, + iter: Iterations, + threads: 1); + + /// A throttled view on a background scheduler over a quaternary list converges to the filtered source. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task ReactiveView_OverQuaternaryList_Throttled_ConvergesToFilteredSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static async (initial, ops) => + { + using var list = new QuaternaryList(); + list.AddRange(initial); + using var view = new ReactiveView(list, ViewFuzzSupport.Passes, TimeSpan.FromMilliseconds(ThrottleMilliseconds), ReactiveListScheduler.Default); + + foreach (var op in ops) + { + ViewFuzzSupport.Apply(list, op); + } + + await AssertAfterDrainAsync(list, view); + }, + iter: ThrottledIterations, + threads: 1); + + /// The public factory over a quaternary list yields a view that converges to the filtered source. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task PublicFactory_OverQuaternaryList_ConvergesToFilteredSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static async (initial, ops) => + { + using var list = new QuaternaryList(); + list.AddRange(initial); + using var view = ((IReactiveSource)list).CreateView(ViewFuzzSupport.Passes, Sequencer.Immediate, 0); + + foreach (var op in ops) + { + ViewFuzzSupport.Apply(list, op); + } + + await AssertAfterDrainAsync(list, view); + }, + iter: Iterations, + threads: 1); + + /// The public factory over a reactive list yields a view that converges to the filtered source. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task PublicFactory_OverReactiveListSource_Throttled_ConvergesToFilteredSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static async (initial, ops) => + { + using var list = new ReactiveList(); + list.AddRange(initial); + using var view = ((IReactiveSource)list).CreateView(ViewFuzzSupport.Passes, ReactiveListScheduler.Default, ThrottleMilliseconds); + + foreach (var op in ops) + { + ViewFuzzSupport.Apply(list, op); + } + + list.Add(ViewFuzzSupport.Sentinel); + await ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Holds(view.Items, ViewFuzzSupport.Sentinel)); + + var expected = ViewFuzzSupport.Sorted(list.Where(ViewFuzzSupport.Passes)); + await Assert.That(ViewFuzzSupport.Sorted(view.Items)).IsEquivalentTo(expected, CollectionOrdering.Matching); + }, + iter: ThrottledIterations, + threads: 1); + + /// A filtered view over a reactive list matches the source in source order. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task FilteredReactiveView_OverReactiveList_ConvergesToFilteredSourceInOrder() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static async (initial, ops) => + { + using var list = new ReactiveList(); + list.AddRange(initial); + using var view = list.CreateView(ViewFuzzSupport.Passes, Sequencer.Immediate, 0); + + foreach (var op in ops) + { + ViewFuzzSupport.Apply(list, op); + } + + list.Add(ViewFuzzSupport.Sentinel); + await ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Holds(view.Items, ViewFuzzSupport.Sentinel)); + + var expected = list.Where(ViewFuzzSupport.Passes).ToArray(); + await Assert.That(ViewFuzzSupport.Copy(view.Items)).IsEquivalentTo(expected, CollectionOrdering.Matching); + }, + iter: Iterations, + threads: 1); + + /// Compares the view and its source after every mutation through the sentinel. + /// The source. + /// The view. + /// A task representing the asynchronous assertion. + private static async Task AssertAfterDrainAsync(QuaternaryList list, ReactiveView view) + { + var snapshot = await ViewFuzzSupport.CaptureAfterDrainAsync(view, view.Items, ViewFuzzSupport.Sentinel, () => list.Add(ViewFuzzSupport.Sentinel)); + Array.Sort(snapshot); + var expected = ViewFuzzSupport.Sorted(list.Where(ViewFuzzSupport.Passes)); + await Assert.That(snapshot).IsEquivalentTo(expected, CollectionOrdering.Matching); + } +} diff --git a/src/tests/ReactiveList.Tests/ReactiveViewHelpersTests.cs b/src/tests/ReactiveList.Tests/ReactiveViewHelpersTests.cs new file mode 100644 index 00000000..11b6e1fe --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReactiveViewHelpersTests.cs @@ -0,0 +1,107 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies how delivers a change while a view is being disposed. +public sealed class ReactiveViewHelpersTests +{ + /// The change every test publishes. + private static readonly PropertyChangedEventArgs _changeArgs = new("Count"); + + /// Verifies a slot that another thread already filled keeps its signal. + /// A task representing the asynchronous test. + [Test] + public async Task CreateSignal_SlotAlreadyFilled_ReturnsTheExistingSignal() + { + Signal? slot = new(); + var existing = slot; + var disposed = 0; + + var result = ReactiveViewHelpers.CreateSignal(ref slot, ref disposed); + + await Assert.That(result).IsSameReferenceAs(existing); + existing.Dispose(); + } + + /// Verifies a signal created for a disposed view rejects subscribers. + /// A task representing the asynchronous test. + [Test] + public async Task CreateSignal_ViewDisposed_ReturnsADisposedSignal() + { + Signal? slot = null; + var disposed = 1; + + var result = ReactiveViewHelpers.CreateSignal(ref slot, ref disposed); + + await Assert.That(() => result.Subscribe(static _ => { })).Throws(); + } + + /// Verifies an open gate delivers the change and leaves the gate idle. + /// A task representing the asynchronous test. + [Test] + public async Task PublishChange_OpenGate_DeliversTheChange() + { + using var signal = new Signal(); + var gate = new DisposalGate(); + var received = 0; + using var subscription = signal.Subscribe(_ => received++); + var disposed = 0; + + ReactiveViewHelpers.PublishChange(signal, gate, _changeArgs, ref disposed); + + await Assert.That(received).IsEqualTo(1); + await Assert.That(gate.IsIdle).IsTrue(); + } + + /// Verifies a closed gate delivers nothing. + /// A task representing the asynchronous test. + [Test] + public async Task PublishChange_ClosedGate_DeliversNothing() + { + using var signal = new Signal(); + var gate = new DisposalGate(); + var received = 0; + using var subscription = signal.Subscribe(_ => received++); + var disposed = 0; + gate.Close(); + + ReactiveViewHelpers.PublishChange(signal, gate, _changeArgs, ref disposed); + + await Assert.That(received).IsEqualTo(0); + } + + /// Verifies an observer that finds the view disposed does not fail the publication. + /// A task representing the asynchronous test. + [Test] + public async Task PublishChange_ObserverFindsViewDisposed_IsTolerated() + { + using var signal = new Signal(); + var gate = new DisposalGate(); + using var subscription = signal.Subscribe(static _ => throw new ObjectDisposedException("view")); + var disposed = 1; + + ReactiveViewHelpers.PublishChange(signal, gate, _changeArgs, ref disposed); + + await Assert.That(gate.IsIdle).IsTrue(); + } + + /// Verifies the same failure is surfaced when the view was not disposed. + /// A task representing the asynchronous test. + [Test] + public async Task PublishChange_ObserverFailsWhileViewIsLive_Surfaces() + { + using var signal = new Signal(); + var gate = new DisposalGate(); + using var subscription = signal.Subscribe(static _ => throw new ObjectDisposedException("other")); + + await Assert.That(() => + { + var disposed = 0; + ReactiveViewHelpers.PublishChange(signal, gate, _changeArgs, ref disposed); + }).Throws(); + + await Assert.That(gate.IsIdle).IsTrue(); + } +} diff --git a/src/tests/ReactiveList.Tests/RecordingMirrorSink.cs b/src/tests/ReactiveList.Tests/RecordingMirrorSink.cs new file mode 100644 index 00000000..b3ce4fc5 --- /dev/null +++ b/src/tests/ReactiveList.Tests/RecordingMirrorSink.cs @@ -0,0 +1,60 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Records the structural changes a reports. +/// The item type. +internal sealed class RecordingMirrorSink : IViewMirrorSink + where T : notnull +{ + /// Gets the recorded events in order. + internal List Events { get; } = []; + + /// Gets or sets an action that runs while a rebuild is reported. + internal Action? OnReset { get; set; } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void BatchStarted(int size) + { + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void BatchEnded() + { + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ItemsInserted(int index, int count) => Events.Add($"insert:{index}:{count}"); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ItemRemoved(int index, T item) => Events.Add($"remove:{index}"); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ItemReplaced(int index, T previous, T current) => Events.Add($"replace:{index}"); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ItemMoved(int oldIndex, int newIndex, T item) => Events.Add($"move:{oldIndex}:{newIndex}"); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ItemRefreshed(int index, T item) => Events.Add($"refresh:{index}"); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void MirrorCleared() => Events.Add("clear"); + + /// + public void MirrorReset() + { + Events.Add("reset"); + OnReset?.Invoke(); + } +} diff --git a/src/tests/ReactiveList.Tests/ReplayGate.cs b/src/tests/ReactiveList.Tests/ReplayGate.cs new file mode 100644 index 00000000..3b325795 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ReplayGate.cs @@ -0,0 +1,78 @@ +// 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. + +namespace ReactiveList.Tests; + +/// +/// Holds versioned notifications back until a snapshot is applied, then replays only those newer than the snapshot. +/// A late delivery of a change older than the snapshot would otherwise overwrite the snapshot's newer state before a +/// version filter is armed. +/// +/// The item type carried by the notifications. +/// The value type of the replayed map. +/// The replayed map. +internal sealed class ReplayGate(System.Collections.Concurrent.ConcurrentDictionary replay) +{ + /// Serialises delivery against the snapshot. + private readonly Lock _gate = new(); + + /// The notifications that arrived before the snapshot, or once it is applied. + private List<(CacheNotify Notification, long Version)>? _held = []; + + /// The version of the applied snapshot. + private long _snapshotVersion; + + /// Handles one notification from the stream. + /// The notification. + /// The version it was published with. + /// Applies a notification to the map. + internal void Receive( + CacheNotify notification, + long version, + Action, CacheNotify> apply) + { + lock (_gate) + { + if (_held is not null) + { + _held.Add((notification, version)); + } + else if (version > _snapshotVersion) + { + apply(replay, notification); + } + } + } + + /// Applies the snapshot and then the held notifications newer than it. + /// The snapshot version. + /// The snapshot items. + /// Writes one snapshot item into the map. + /// Applies a notification to the map. + internal void Complete( + long version, + TItem[] snapshot, + Action, TItem> seed, + Action, CacheNotify> apply) + { + lock (_gate) + { + foreach (var item in snapshot) + { + seed(replay, item); + } + + foreach (var (notification, held) in _held!) + { + if (held > version) + { + apply(replay, notification); + } + } + + _snapshotVersion = version; + _held = null; + } + } +} diff --git a/src/tests/ReactiveList.Tests/ScriptedViewSource.cs b/src/tests/ReactiveList.Tests/ScriptedViewSource.cs new file mode 100644 index 00000000..9ddb3a36 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ScriptedViewSource.cs @@ -0,0 +1,75 @@ +// 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. + +namespace ReactiveList.Tests; + +/// A source without version snapshots whose reads can be scripted to change or fail mid-read and whose notifications the test sends by hand. +/// The item type. +internal sealed class ScriptedViewSource : IReactiveSource, IReadOnlyList + where T : notnull +{ + /// The list that holds the items and the revision. + private readonly ReactiveList _inner = []; + + /// + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add => _inner.CollectionChanged += value; + remove => _inner.CollectionChanged -= value; + } + + /// + public int Count => _inner.Count; + + /// + public bool IsReadOnly => _inner.IsReadOnly; + + /// + public bool IsDisposed => _inner.IsDisposed; + + /// + public long Version => _inner.Version; + + /// + public IObservable> Stream => Notifications; + + /// Gets the stream of notifications, which carries only what the test sends. + internal ManualObservable> Notifications { get; } = new(); + + /// Gets or sets an action that runs once while the items are being copied. + internal Action? OnCopy { get; set; } + + /// Gets or sets a value indicating whether reading an item by index fails as if the source shrank. + internal bool IndexerShrinks { get; set; } + + /// + public T this[int index] => IndexerShrinks ? throw new ArgumentOutOfRangeException(nameof(index)) : _inner[index]; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator GetEnumerator() => ((IEnumerable)_inner.ToArray()).GetEnumerator(); + + /// + public T[] ToArray() + { + var snapshot = _inner.ToArray(); + var action = OnCopy; + OnCopy = null; + action?.Invoke(); + return snapshot; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _inner.Dispose(); + + /// Appends an item. + /// The item to append. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void Add(T item) => _inner.Add(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} diff --git a/src/tests/ReactiveList.Tests/SecondaryIndexFuzzTests.cs b/src/tests/ReactiveList.Tests/SecondaryIndexFuzzTests.cs new file mode 100644 index 00000000..6906d89e --- /dev/null +++ b/src/tests/ReactiveList.Tests/SecondaryIndexFuzzTests.cs @@ -0,0 +1,73 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks against a multiset model using generated operation sequences. +public sealed class SecondaryIndexFuzzTests +{ + /// The key modulus of the direct index tests. + private const int KeyModulus = IndexModelRun.KeyModulus; + + /// The key of the first holder. + private const int OriginalKey = 1; + + /// The key a holder changes to. + private const int ChangedKey = 2; + + /// Verifies int items, which collide heavily on both key and value. + /// A task representing the asynchronous test. + [Test] + public Task IntItems_FollowMultisetModel() + { + var run = new IndexModelRun(static i => i, static i => i % KeyModulus); + Check.Sample(FuzzSupport.Operations(), run.Execute, iter: FuzzSupport.DefaultIterations, print: FuzzSupport.Describe); + return Task.CompletedTask; + } + + /// Verifies items with colliding hash codes. + /// A task representing the asynchronous test. + [Test] + public Task CollidingItems_FollowMultisetModel() + { + var run = new IndexModelRun(static i => new CollidingItem(i, i % KeyModulus), static c => c.Group); + Check.Sample(FuzzSupport.Operations(), run.Execute, iter: FuzzSupport.DefaultIterations, print: FuzzSupport.Describe); + return Task.CompletedTask; + } + + /// Verifies that adding an item twice and removing it once leaves one indexed copy. + /// A task representing the asynchronous test. + [Test] + public async Task Remove_OneOfTwoEqualItems_KeepsTheOther() + { + var index = new SecondaryIndex(static i => i % KeyModulus); + index.OnAdded(OriginalKey); + index.OnAdded(OriginalKey); + index.OnRemoved(OriginalKey); + + await Assert.That(index.Lookup(OriginalKey).ToArray()).IsEquivalentTo([OriginalKey]); + } + + /// Verifies that removing an item whose key changed since it was added still cleans the index. + /// A task representing the asynchronous test. + [Test] + public async Task Remove_AfterKeyChanged_RemovesTheStaleEntry() + { + var holder = new KeyHolder { Key = OriginalKey }; + var index = new SecondaryIndex(static h => h.Key); + index.OnAdded(holder); + holder.Key = ChangedKey; + index.OnRemoved(holder); + + await Assert.That(index.Lookup(OriginalKey).ToArray()).IsEmpty(); + await Assert.That(index.Lookup(ChangedKey).ToArray()).IsEmpty(); + } + + /// A mutable item that uses reference equality while exposing a changeable key. + private sealed class KeyHolder + { + /// Gets or sets the indexed key. + internal int Key { get; set; } + } +} diff --git a/src/tests/ReactiveList.Tests/SecondaryIndexTests.cs b/src/tests/ReactiveList.Tests/SecondaryIndexTests.cs index de7d0889..dc65a2a2 100644 --- a/src/tests/ReactiveList.Tests/SecondaryIndexTests.cs +++ b/src/tests/ReactiveList.Tests/SecondaryIndexTests.cs @@ -7,7 +7,7 @@ namespace ReactiveList.Tests; /// Tests for SecondaryIndex. -public class SecondaryIndexTests +public sealed class SecondaryIndexTests { /// OnAdded should add item to index. /// A task representing the asynchronous test. diff --git a/src/tests/ReactiveList.Tests/SecondaryIndexUpsertTests.cs b/src/tests/ReactiveList.Tests/SecondaryIndexUpsertTests.cs new file mode 100644 index 00000000..133a682d --- /dev/null +++ b/src/tests/ReactiveList.Tests/SecondaryIndexUpsertTests.cs @@ -0,0 +1,138 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies a secondary index view applies a dictionary upsert incrementally instead of rebuilding itself. +public sealed class SecondaryIndexUpsertTests +{ + /// The name of the parity index. + private const string IndexName = "parity"; + + /// The index key the views select. + private const int OddKey = 1; + + /// The number of changes raised once the second upsert was applied. + private const int AfterRemove = 2; + + /// An odd value that replaces another odd value. + private const int OtherOdd = 5; + + /// An even value that removes an entry from the odd view. + private const int Even = 4; + + /// An odd value that returns an entry to the odd view. + private const int OddAgain = 7; + + /// The number of divisions of the value space by the index. + private const int IndexKeyCount = 2; + + /// The number of generated cases. + private const int Iterations = 200; + + /// The longest generated sequence of upserts. + private const int MaxUpserts = 40; + + /// The exclusive upper bound of generated keys. + private const int KeyRange = 6; + + /// The exclusive upper bound of generated values. + private const int ValueRange = 20; + + /// The entries the dictionary starts with, two values under the odd key. + private static readonly KeyValuePair[] Initial = [new(1, 1), new(2, 3)]; + + /// The actions expected from an odd value replaced by another odd value, an odd value replaced by an even one and the reverse. + private static readonly NotifyCollectionChangedAction[] ExpectedActions = + [ + NotifyCollectionChangedAction.Replace, + NotifyCollectionChangedAction.Remove, + NotifyCollectionChangedAction.Add, + ]; + + /// Upserts that keep, drop and regain a value raise a replace, a remove and an add, never a reset. + /// A task representing the asynchronous test. + [Test] + public async Task Upsert_ChangingMembership_RaisesIncrementalChanges() + { + using var dictionary = CreateDictionary(); + using var view = dictionary.CreateViewBySecondaryIndex(IndexName, OddKey, Sequencer.Immediate, 0); + var actions = new List(); + var count = 0; + ((INotifyCollectionChanged)view.Items).CollectionChanged += (_, args) => + { + lock (actions) + { + actions.Add(args.Action); + } + + _ = Interlocked.Increment(ref count); + }; + + // The source delivers on its own thread, so each change is awaited before the next one is made. + dictionary.AddOrUpdate(1, OtherOdd); + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref count) == 1); + dictionary.AddOrUpdate(1, Even); + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref count) == AfterRemove); + dictionary.AddOrUpdate(1, OddAgain); + await TestWaitHelpers.WaitUntilAsync(() => Volatile.Read(ref count) == ExpectedActions.Length); + + await Assert.That(actions).IsEquivalentTo(ExpectedActions, CollectionOrdering.Matching); + await Assert.That(ViewFuzzSupport.Sorted(view.Items)).IsEquivalentTo(ViewFuzzSupport.Sorted(Model(dictionary)), CollectionOrdering.Matching); + } + + /// A view follows any sequence of upserts and never raises a reset. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task Upserts_Fuzz_ConvergeWithoutReset() => + Check.SampleAsync( + Gen.Select(Gen.Int[0, KeyRange - 1], Gen.Int[0, ValueRange - 1]).Array[0, MaxUpserts], + RunAsync, + iter: Iterations, + threads: 1); + + /// Applies the upserts to a dictionary watched by a view and checks the view. + /// The key and value pairs to write. + /// A task representing the asynchronous check. + private static async Task RunAsync((int Key, int Value)[] upserts) + { + using var dictionary = CreateDictionary(); + using var view = dictionary.CreateViewBySecondaryIndex(IndexName, OddKey, Sequencer.Immediate, 0); + var resets = 0; + ((INotifyCollectionChanged)view.Items).CollectionChanged += (_, args) => + { + if (args.Action == NotifyCollectionChangedAction.Reset) + { + _ = Interlocked.Increment(ref resets); + } + }; + + foreach (var (key, value) in upserts) + { + dictionary.AddOrUpdate(key, value); + } + + var expected = ViewFuzzSupport.Sorted(Model(dictionary)); + await TestWaitHelpers.WaitUntilAsync(() => ViewFuzzSupport.Sorted(view.Items).AsSpan().SequenceEqual(expected)); + + await Assert.That(Volatile.Read(ref resets)).IsEqualTo(0); + } + + /// Creates a dictionary indexed by value parity. + /// The dictionary. + private static QuaternaryDictionary CreateDictionary() + { + var dictionary = new QuaternaryDictionary(); + dictionary.AddValueIndex(IndexName, static value => value % IndexKeyCount); + dictionary.AddRange(Initial); + return dictionary; + } + + /// Gets the values whose index key is the odd key. + /// The dictionary. + /// The matching values. + private static int[] Model(QuaternaryDictionary dictionary) => + [.. dictionary.ToArray().Where(static entry => entry.Value % IndexKeyCount != 0).Select(static entry => entry.Value)]; +} diff --git a/src/tests/ReactiveList.Tests/SecondaryIndexViewFuzzTests.cs b/src/tests/ReactiveList.Tests/SecondaryIndexViewFuzzTests.cs new file mode 100644 index 00000000..495bc291 --- /dev/null +++ b/src/tests/ReactiveList.Tests/SecondaryIndexViewFuzzTests.cs @@ -0,0 +1,360 @@ +// 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. + +using CsCheck; + +namespace ReactiveList.Tests; + +/// Model-based fuzz tests for the secondary index views, including the public factory methods. +public sealed class SecondaryIndexViewFuzzTests +{ + /// The number of generated cases per immediate property. + private const int Iterations = 120; + + /// The number of generated cases per throttled property. + private const int ThrottledIterations = 25; + + /// The longest generated mutation sequence. + private const int MaxOps = 25; + + /// The coalescing window for throttled cases, in milliseconds. + private const int ThrottleMilliseconds = 5; + + /// The number of distinct secondary index keys. + private const int IndexKeyCount = 3; + + /// The name of the secondary index. + private const string IndexName = "bucket"; + + /// The index key the single key views follow. + private const int SingleKey = 1; + + /// The index key set of the multi key views. + private static readonly int[] KeySet = [0, 2]; + + /// A dynamic list view follows both source mutations and key changes when applied immediately. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task DynamicSecondaryIndexListView_Immediate_ConvergesToIndexedSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static (initial, ops) => DynamicListAsync(initial, ops, TimeSpan.Zero, Sequencer.Immediate), + iter: Iterations, + threads: 1); + + /// A dynamic list view converges when a throttle window coalesces changes on a background scheduler. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task DynamicSecondaryIndexListView_Throttled_ConvergesToIndexedSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static (initial, ops) => DynamicListAsync(initial, ops, TimeSpan.FromMilliseconds(ThrottleMilliseconds), ReactiveListScheduler.Default), + iter: ThrottledIterations, + threads: 1); + + /// The public single key list factory yields a view that matches the indexed source. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task ListFactory_SingleKey_ConvergesToIndexedSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static async (initial, ops) => + { + using var list = CreateList(initial); + using var view = list.CreateViewBySecondaryIndex(IndexName, SingleKey, Sequencer.Immediate, 0); + ApplyAll(list, ops); + await ViewFuzzSupport.SettleAsync(() => SameItems(view.Items, Model(list, [SingleKey]))); + }, + iter: Iterations, + threads: 1); + + /// The public multi key list factory yields a view that matches the indexed source. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task ListFactory_MultiKey_ConvergesToIndexedSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static async (initial, ops) => + { + using var list = CreateList(initial); + using var view = list.CreateViewBySecondaryIndex(IndexName, KeySet, Sequencer.Immediate, 0); + ApplyAll(list, ops); + await ViewFuzzSupport.SettleAsync(() => SameItems(view.Items, Model(list, KeySet))); + }, + iter: Iterations, + threads: 1); + + /// A dictionary single key view holds the values the index lists, when applied immediately. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task SecondaryIndexDictionaryView_Immediate_ConvergesToIndexedSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static (initial, ops) => DictionaryValuesAsync(initial, ops, TimeSpan.Zero, Sequencer.Immediate), + iter: Iterations, + threads: 1); + + /// A dictionary single key view converges when a throttle window coalesces changes on a background scheduler. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task SecondaryIndexDictionaryView_Throttled_ConvergesToIndexedSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static (initial, ops) => DictionaryValuesAsync(initial, ops, TimeSpan.FromMilliseconds(ThrottleMilliseconds), ReactiveListScheduler.Default), + iter: ThrottledIterations, + threads: 1); + + /// A dynamic dictionary view follows both source mutations and key changes when applied immediately. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task DynamicSecondaryIndexDictionaryView_Immediate_ConvergesToIndexedSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static (initial, ops) => DynamicDictionaryAsync(initial, ops, TimeSpan.Zero, Sequencer.Immediate), + iter: Iterations, + threads: 1); + + /// A dynamic dictionary view converges when a throttle window coalesces changes on a background scheduler. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task DynamicSecondaryIndexDictionaryView_Throttled_ConvergesToIndexedSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static (initial, ops) => DynamicDictionaryAsync(initial, ops, TimeSpan.FromMilliseconds(ThrottleMilliseconds), ReactiveListScheduler.Default), + iter: ThrottledIterations, + threads: 1); + + /// The public dictionary factory yields entries that match the indexed source. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task DictionaryFactory_ConvergesToIndexedSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static async (initial, ops) => + { + using var dictionary = CreateDictionary(initial); + using var view = QuaternaryExtensions.CreateViewBySecondaryIndex(dictionary, IndexName, SingleKey, Sequencer.Immediate, 0); + ApplyAll(dictionary, ops); + await ViewFuzzSupport.SettleAsync(() => SameEntries(view.Items, EntryModel(dictionary, [SingleKey]))); + }, + iter: Iterations, + threads: 1); + + /// Creates an indexed list holding the initial items. + /// The initial items. + /// The list. + private static QuaternaryList CreateList(int[] initial) + { + var list = new QuaternaryList(); + list.AddIndex(IndexName, static item => item % IndexKeyCount); + list.AddRange(initial); + return list; + } + + /// Creates an indexed dictionary holding the initial items under their own keys. + /// The initial items. + /// The dictionary. + private static QuaternaryDictionary CreateDictionary(int[] initial) + { + var dictionary = new QuaternaryDictionary(); + dictionary.AddValueIndex(IndexName, static value => value % IndexKeyCount); + foreach (var item in initial) + { + dictionary.AddOrUpdate(item % ViewFuzzSupport.KeyRange, item); + } + + return dictionary; + } + + /// Applies every mutation to a list. + /// The list. + /// The mutations. + private static void ApplyAll(QuaternaryList list, ViewFuzzOp[] ops) + { + foreach (var op in ops) + { + ViewFuzzSupport.Apply(list, op); + } + } + + /// Applies every mutation to a dictionary. + /// The dictionary. + /// The mutations. + private static void ApplyAll(QuaternaryDictionary dictionary, ViewFuzzOp[] ops) + { + foreach (var op in ops) + { + ViewFuzzSupport.Apply(dictionary, op); + } + } + + /// Gets the key set a key change operation selects. + /// The operation. + /// Zero to two keys. + private static int[] KeysFor(ViewFuzzOp op) + { + var first = op.A % IndexKeyCount; + return (op.B % IndexKeyCount) switch + { + 0 => [], + 1 => [first], + _ => [first, (first + 1) % IndexKeyCount], + }; + } + + /// Gets the list items whose index key is in the key set. + /// The list. + /// The key set. + /// The matching items. + private static int[] Model(QuaternaryList list, int[] keys) => + [.. list.ToArray().Where(item => Array.IndexOf(keys, item % IndexKeyCount) >= 0)]; + + /// Gets the dictionary values whose index key is in the key set. + /// The dictionary. + /// The key set. + /// The matching values. + private static int[] ValueModel(QuaternaryDictionary dictionary, int[] keys) => + [.. dictionary.ToArray().Where(entry => Array.IndexOf(keys, entry.Value % IndexKeyCount) >= 0).Select(static entry => entry.Value)]; + + /// Gets the dictionary entries whose value's index key is in the key set. + /// The dictionary. + /// The key set. + /// The matching entries. + private static KeyValuePair[] EntryModel(QuaternaryDictionary dictionary, int[] keys) => + [.. dictionary.ToArray().Where(entry => Array.IndexOf(keys, entry.Value % IndexKeyCount) >= 0)]; + + /// Compares a view collection with the expected items, ignoring order. + /// The view collection. + /// The expected items. + /// when they hold the same items. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool SameItems(IReadOnlyList view, int[] expected) => + ViewFuzzSupport.Sorted(view).AsSpan().SequenceEqual(ViewFuzzSupport.Sorted(expected)); + + /// Compares view entries with the expected entries, ignoring order. + /// The view collection. + /// The expected entries. + /// when they hold the same entries. + private static bool SameEntries(IReadOnlyList> view, KeyValuePair[] expected) + { + var actual = CopyEntries(view); + Array.Sort(actual, CompareEntries); + Array.Sort(expected, CompareEntries); + return actual.AsSpan().SequenceEqual(expected); + } + + /// Copies a view collection of entries that a scheduler thread may still be changing. + /// The view collection. + /// The copy. + private static KeyValuePair[] CopyEntries(IReadOnlyList> view) + { + for (var attempt = 0; attempt < ViewFuzzSupport.CopyAttempts; attempt++) + { + try + { + var copy = new KeyValuePair[view.Count]; + for (var i = 0; i < copy.Length; i++) + { + copy[i] = view[i]; + } + + return copy; + } + catch (ArgumentOutOfRangeException) + { + // The collection shrank during the copy. + } + } + + return []; + } + + /// Orders entries by key and then value. + /// The first entry. + /// The second entry. + /// The comparison result. + private static int CompareEntries(KeyValuePair left, KeyValuePair right) => + left.Key != right.Key ? left.Key.CompareTo(right.Key) : left.Value.CompareTo(right.Value); + + /// Runs a dynamic list view case. + /// The initial items. + /// The mutations. + /// The coalescing window. + /// The scheduler that applies view changes. + /// A task representing the asynchronous check. + private static async Task DynamicListAsync(int[] initial, ViewFuzzOp[] ops, TimeSpan throttle, ISequencer scheduler) + { + using var list = CreateList(initial); + var keys = new[] { SingleKey }; + using var keySignal = new BehaviorSignal(keys); + using var view = new DynamicSecondaryIndexReactiveView(list, IndexName, keySignal, scheduler, throttle); + + foreach (var op in ops) + { + ViewFuzzSupport.Apply(list, op); + if (op.B % IndexKeyCount != 0) + { + continue; + } + + keys = KeysFor(op); + keySignal.OnNext(keys); + } + + var finalKeys = keys; + await ViewFuzzSupport.SettleAsync(() => SameItems(view.Items, Model(list, finalKeys))); + } + + /// Runs a dictionary single key view case. + /// The initial items. + /// The mutations. + /// The coalescing window. + /// The scheduler that applies view changes. + /// A task representing the asynchronous check. + private static async Task DictionaryValuesAsync(int[] initial, ViewFuzzOp[] ops, TimeSpan throttle, ISequencer scheduler) + { + using var dictionary = CreateDictionary(initial); + using var view = SecondaryIndexReactiveView.Create(dictionary, IndexName, SingleKey, scheduler, throttle); + ApplyAll(dictionary, ops); + await ViewFuzzSupport.SettleAsync(() => SameItems(view.Items, ValueModel(dictionary, [SingleKey]))); + } + + /// Runs a dynamic dictionary view case. + /// The initial items. + /// The mutations. + /// The coalescing window. + /// The scheduler that applies view changes. + /// A task representing the asynchronous check. + private static async Task DynamicDictionaryAsync(int[] initial, ViewFuzzOp[] ops, TimeSpan throttle, ISequencer scheduler) + { + using var dictionary = CreateDictionary(initial); + var keys = new[] { SingleKey }; + using var keySignal = new BehaviorSignal(keys); + using var view = DynamicSecondaryIndexDictionaryReactiveView.Create(dictionary, IndexName, keySignal, scheduler, throttle); + + foreach (var op in ops) + { + ViewFuzzSupport.Apply(dictionary, op); + if (op.B % IndexKeyCount != 0) + { + continue; + } + + keys = KeysFor(op); + keySignal.OnNext(keys); + } + + var finalKeys = keys; + await ViewFuzzSupport.SettleAsync(() => SameEntries(view.Items, EntryModel(dictionary, finalKeys))); + } +} diff --git a/src/tests/ReactiveList.Tests/SerializedObserverTests.cs b/src/tests/ReactiveList.Tests/SerializedObserverTests.cs new file mode 100644 index 00000000..cfdba82b --- /dev/null +++ b/src/tests/ReactiveList.Tests/SerializedObserverTests.cs @@ -0,0 +1,121 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks that serializes, orders and ends notifications. +public class SerializedObserverTests +{ + /// A second value sent while another is delivered. + private const int Second = 2; + + /// A notification sent from inside a delivery is delivered after the current one, in order. + /// A task representing the asynchronous test. + [Test] + public async Task OnNext_FromInsideDelivery_IsQueuedBehindTheCurrentOne() + { + List seen = []; + SerializedObserver? serialized = null; + ActionObserver inner = new( + value => + { + seen.Add(value); + if (value == 1) + { + serialized!.OnNext(Second); + seen.Add(-1); + } + }); + serialized = new(inner); + + serialized.OnNext(1); + + await Assert.That(seen).IsEquivalentTo([1, -1, Second], CollectionOrdering.Matching); + } + + /// Notifications after a terminal one or after a stop are ignored. + /// A task representing the asynchronous test. + [Test] + public async Task Notifications_AfterTerminalOrStop_AreIgnored() + { + List seen = []; + var completed = 0; + SerializedObserver completing = new(new ActionObserver(seen.Add, onCompleted: () => completed++)); + completing.OnCompleted(); + completing.OnNext(1); + completing.OnCompleted(); + + SerializedObserver stopped = new(new ActionObserver(seen.Add)); + stopped.Stop(); + stopped.OnNext(1); + + await Assert.That(completed).IsEqualTo(1); + await Assert.That(seen).IsEmpty(); + } + + /// An error is delivered once and ends the sequence. + /// A task representing the asynchronous test. + [Test] + public async Task OnError_IsDeliveredOnce() + { + Exception? received = null; + var errors = 0; + SerializedObserver serialized = new(new ActionObserver(static _ => { }, onError: error => + { + received = error; + errors++; + })); + InvalidOperationException failure = new(); + + serialized.OnError(failure); + serialized.OnError(failure); + + await Assert.That(received).IsSameReferenceAs(failure); + await Assert.That(errors).IsEqualTo(1); + } + + /// An observer that throws releases delivery so later notifications are still delivered. + /// A task representing the asynchronous test. + [Test] + public async Task OnNext_ObserverThrows_RethrowsAndKeepsDelivering() + { + List seen = []; + var fail = true; + SerializedObserver serialized = new(new ActionObserver( + value => + { + if (fail) + { + throw new InvalidOperationException(); + } + + seen.Add(value); + })); + + await Assert.That(() => serialized.OnNext(1)).Throws(); + fail = false; + serialized.OnNext(Second); + + await Assert.That(seen).IsEquivalentTo([Second], CollectionOrdering.Matching); + } + + /// An observer built from delegates. + /// The value handler. + /// The error handler. + /// The completion handler. + private sealed class ActionObserver(Action onNext, Action? onError = null, Action? onCompleted = null) : IObserver + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted() => onCompleted?.Invoke(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnError(Exception error) => onError?.Invoke(error); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnNext(int value) => onNext(value); + } +} diff --git a/src/tests/ReactiveList.Tests/SnapshotEnumeratorTests.cs b/src/tests/ReactiveList.Tests/SnapshotEnumeratorTests.cs new file mode 100644 index 00000000..3c3e5427 --- /dev/null +++ b/src/tests/ReactiveList.Tests/SnapshotEnumeratorTests.cs @@ -0,0 +1,63 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks and . +public class SnapshotEnumeratorTests +{ + /// The value stored in the snapshots. + private const int Stored = 7; + + /// Resetting a pooled enumerator starts it over, and disposing twice is harmless. + /// A task representing the asynchronous test. + [Test] + public async Task PooledEnumerator_ResetAndDoubleDispose_Work() + { + var buffer = ArrayPool.Shared.Rent(1); + buffer[0] = Stored; + PooledSnapshotEnumerator enumerator = new(buffer, 1); + + var first = enumerator.MoveNext(); + var boxed = ((IEnumerator)enumerator).Current; + var finished = enumerator.MoveNext(); + enumerator.Reset(); + var again = enumerator.MoveNext(); + enumerator.Dispose(); + enumerator.Dispose(); + + using (Assert.Multiple()) + { + await Assert.That(first).IsTrue(); + await Assert.That(boxed).IsEqualTo(Stored); + await Assert.That(finished).IsFalse(); + await Assert.That(again).IsTrue(); + await Assert.That(enumerator.Current).IsEqualTo(0); + } + } + + /// Resetting an array enumerator starts it over, and reading outside the elements throws. + /// A task representing the asynchronous test. + [Test] + public async Task ArrayEnumerator_ResetAndOutOfPositionRead_Work() + { + SnapshotArrayEnumerator enumerator = new([Stored]); + + await Assert.That(() => enumerator.Current).Throws(); + var first = enumerator.MoveNext(); + var boxed = ((IEnumerator)enumerator).Current; + var finished = enumerator.MoveNext(); + enumerator.Reset(); + var again = enumerator.MoveNext(); + enumerator.Dispose(); + + using (Assert.Multiple()) + { + await Assert.That(first).IsTrue(); + await Assert.That(boxed).IsEqualTo(Stored); + await Assert.That(finished).IsFalse(); + await Assert.That(again).IsTrue(); + } + } +} diff --git a/src/tests/ReactiveList.Tests/SortedReactiveViewFuzzTests.cs b/src/tests/ReactiveList.Tests/SortedReactiveViewFuzzTests.cs new file mode 100644 index 00000000..78393c23 --- /dev/null +++ b/src/tests/ReactiveList.Tests/SortedReactiveViewFuzzTests.cs @@ -0,0 +1,79 @@ +// 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. + +using CsCheck; + +namespace ReactiveList.Tests; + +/// Model-based fuzz tests for the sorted view. +public class SortedReactiveViewFuzzTests +{ + /// The number of generated cases per immediate property. + private const int Iterations = 150; + + /// The number of generated cases per throttled property. + private const int ThrottledIterations = 25; + + /// The longest generated mutation sequence. + private const int MaxOps = 25; + + /// The coalescing window for throttled cases, in milliseconds. + private const int ThrottleMilliseconds = 5; + + /// The number of distinct sort keys, so distinct items often compare equal. + private const int KeyCount = 4; + + /// Sorts by a coarse key so distinct items can compare as equal. + private static readonly Comparer CoarseComparer = Comparer.Create(static (x, y) => (x % KeyCount).CompareTo(y % KeyCount)); + + /// The view is ordered by the comparer and holds exactly the source items when notifications are applied immediately. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task SortedView_Immediate_ConvergesToSortedSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static (initial, ops) => RunAsync(initial, ops, TimeSpan.Zero, Sequencer.Immediate), + iter: Iterations, + threads: 1); + + /// The view converges when a throttle window coalesces changes on a background scheduler. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task SortedView_Throttled_ConvergesToSortedSource() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps)), + static (initial, ops) => RunAsync(initial, ops, TimeSpan.FromMilliseconds(ThrottleMilliseconds), ReactiveListScheduler.Default), + iter: ThrottledIterations, + threads: 1); + + /// Applies the mutations and checks the view against the source. + /// The initial items. + /// The mutations. + /// The coalescing window. + /// The scheduler that applies view changes. + /// A task representing the asynchronous check. + private static async Task RunAsync(int[] initial, ViewFuzzOp[] ops, TimeSpan throttle, ISequencer scheduler) + { + using var list = new ReactiveList(); + list.AddRange(initial); + using var view = new SortedReactiveView(list, CoarseComparer, scheduler, throttle); + + foreach (var op in ops) + { + ViewFuzzSupport.Apply(list, op); + } + + list.Add(ViewFuzzSupport.Sentinel); + await ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Holds(view.Items, ViewFuzzSupport.Sentinel)); + + var items = ViewFuzzSupport.Copy(view.Items); + await Assert.That(ViewFuzzSupport.Sorted(items)).IsEquivalentTo(ViewFuzzSupport.Sorted(list), CollectionOrdering.Matching); + for (var i = 1; i < items.Length; i++) + { + await Assert.That(CoarseComparer.Compare(items[i - 1], items[i])).IsLessThanOrEqualTo(0); + } + } +} diff --git a/src/tests/ReactiveList.Tests/SortedViewEngineTests.cs b/src/tests/ReactiveList.Tests/SortedViewEngineTests.cs new file mode 100644 index 00000000..18af0b14 --- /dev/null +++ b/src/tests/ReactiveList.Tests/SortedViewEngineTests.cs @@ -0,0 +1,104 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies how keeps its order when items are refreshed in place. +public sealed class SortedViewEngineTests +{ + /// The smallest value the source starts with. + private const int Low = 1; + + /// A value between the first two items. + private const int BetweenValue = 2; + + /// The middle value the source starts with. + private const int Middle = 3; + + /// The largest value the source starts with. + private const int High = 5; + + /// A value that sorts after every other item. + private const int LastValue = 10; + + /// The values the source starts with. + private static readonly int[] _initialValues = [Low, Middle, High]; + + /// Verifies a refreshed item that the view does not hold is inserted in order. + /// A task representing the asynchronous test. + [Test] + public async Task ItemRefreshed_ItemNotInView_InsertsInOrder() + { + var (list, engine) = Create(); + using (list) + using (engine) + { + engine.ItemRefreshed(0, new(BetweenValue)); + + await Assert.That(MutableValue.Values(engine.Sorted)).IsEquivalentTo([Low, BetweenValue, Middle, High], CollectionOrdering.Matching); + } + } + + /// Verifies a refreshed item that still fits its place stays where it is. + /// A task representing the asynchronous test. + [Test] + public async Task ItemRefreshed_OrderStillHolds_KeepsThePosition() + { + var (list, engine) = Create(); + using (list) + using (engine) + { + engine.ItemRefreshed(1, list[1]); + engine.ItemRefreshed(0, list[0]); + engine.ItemRefreshed(list.Count - 1, list[^1]); + + await Assert.That(MutableValue.Values(engine.Sorted)).IsEquivalentTo(_initialValues, CollectionOrdering.Matching); + } + } + + /// Verifies a refreshed item whose value now breaks the order moves to its new place. + /// A task representing the asynchronous test. + [Test] + public async Task ItemRefreshed_OrderBroken_MovesTheItem() + { + var (list, engine) = Create(); + using (list) + using (engine) + { + list[0].Value = LastValue; + + engine.ItemRefreshed(0, list[0]); + + await Assert.That(MutableValue.Values(engine.Sorted)).IsEquivalentTo([Middle, High, LastValue], CollectionOrdering.Matching); + } + } + + /// Verifies a removal of an item the view does not hold changes nothing. + /// A task representing the asynchronous test. + [Test] + public async Task ItemRemoved_ItemNotInView_ChangesNothing() + { + var (list, engine) = Create(); + using (list) + using (engine) + { + engine.ItemRemoved(0, new(BetweenValue)); + + await Assert.That(MutableValue.Values(engine.Sorted)).IsEquivalentTo(_initialValues, CollectionOrdering.Matching); + } + } + + /// Creates a list of the initial values and an engine that sorts it by value. + /// The list and the engine. + private static (ReactiveList List, SortedViewEngine Engine) Create() + { + ReactiveList list = []; + foreach (var value in _initialValues) + { + list.Add(new(value)); + } + + return (list, new(list, MutableValue.ByValue())); + } +} diff --git a/src/tests/ReactiveList.Tests/SortedViewReplaceTests.cs b/src/tests/ReactiveList.Tests/SortedViewReplaceTests.cs new file mode 100644 index 00000000..892ca71f --- /dev/null +++ b/src/tests/ReactiveList.Tests/SortedViewReplaceTests.cs @@ -0,0 +1,57 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies a sorted view re-sorts an item that is written back after its ordering value changed. +public sealed class SortedViewReplaceTests +{ + /// The value an item is changed to. + private const int Changed = 99; + + /// The value inserted after the change. + private const int Later = 50; + + /// The initial values. + private static readonly int[] Initial = [1, 2, 3, 4, 5]; + + /// The values expected after the first item moved to the end and a later value was added. + private static readonly int[] AfterSetIndex = [2, 3, 4, 5, Later, Changed]; + + /// The values expected after the second item moved to the end. + private static readonly int[] AfterUpdate = [1, 3, 4, 5, Changed]; + + /// Writing the same mutated instance back moves it to its new sorted position. + /// A task representing the asynchronous test. + [Test] + public async Task SetIndex_SameInstanceWithChangedValue_Resorts() + { + using var list = new ReactiveList(); + var items = Initial.Select(static value => new MutableValue(value)).ToArray(); + list.AddRange(items); + using var view = new SortedReactiveView(list, MutableValue.ByValue(), Sequencer.Immediate, TimeSpan.Zero); + + items[0].Value = Changed; + list[0] = items[0]; + list.Add(new(Later)); + + await Assert.That(MutableValue.Values(view)).IsEquivalentTo(AfterSetIndex, CollectionOrdering.Matching); + } + + /// Updating an item with itself moves it to its new sorted position. + /// A task representing the asynchronous test. + [Test] + public async Task Update_SameInstanceWithChangedValue_Resorts() + { + using var list = new ReactiveList(); + var items = Initial.Select(static value => new MutableValue(value)).ToArray(); + list.AddRange(items); + using var view = new SortedReactiveView(list, MutableValue.ByValue(), Sequencer.Immediate, TimeSpan.Zero); + + items[1].Value = Changed; + list.Update(items[1], items[1]); + + await Assert.That(MutableValue.Values(view)).IsEquivalentTo(AfterUpdate, CollectionOrdering.Matching); + } +} diff --git a/src/tests/ReactiveList.Tests/StreamProjectionLifecycleTests.cs b/src/tests/ReactiveList.Tests/StreamProjectionLifecycleTests.cs new file mode 100644 index 00000000..3464b866 --- /dev/null +++ b/src/tests/ReactiveList.Tests/StreamProjectionLifecycleTests.cs @@ -0,0 +1,272 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks how reacts to failures, disposal and notifications it cannot apply exactly. +public class StreamProjectionLifecycleTests +{ + /// The changed-property name that projections announce by default. + private const string ItemsProperty = "Items"; + + /// A value carried by the test items. + private const int Value = 7; + + /// A value that no test filter accepts. + private const string Rejected = "rejected"; + + /// A value that every test filter accepts. + private const string Accepted = "a"; + + /// A custom changed-property name is the one raised after a drain. + /// A task representing the asynchronous test. + [Test] + public async Task Constructor_CustomChangedProperty_IsRaisedAfterADrain() + { + using ReactiveList source = []; + using var projection = CreateProjection(source, "Custom"); + projection.StartFromSource(TimeSpan.Zero, ReactiveListScheduler.Immediate); + List names = []; + using var subscription = projection.PropertyChanges.Subscribe(new CountingObserver(args => names.Add(args.PropertyName!))); + + source.Add(Value); + + await Assert.That(names).IsEquivalentTo(["Custom"], CollectionOrdering.Matching); + } + + /// A stream failure is rethrown when no handler was given. + /// A task representing the asynchronous test. + [Test] + public async Task OnError_WithoutHandler_Rethrows() + { + using ReactiveList source = []; + using var projection = CreateProjection(source); + + await Assert.That(() => projection.OnError(new InvalidOperationException())).Throws(); + } + + /// A stream failure is passed to the handler that was given. + /// A task representing the asynchronous test. + [Test] + public async Task OnError_WithHandler_ForwardsTheFailure() + { + using ReactiveList source = []; + using var projection = CreateProjection(source); + Exception? received = null; + projection.StartFromSource(TimeSpan.Zero, ReactiveListScheduler.Immediate, onError: error => received = error); + InvalidOperationException failure = new(); + + projection.OnError(failure); + + await Assert.That(received).IsSameReferenceAs(failure); + } + + /// Starting a projection that was already disposed releases the source subscription at once. + /// A task representing the asynchronous test. + [Test] + public async Task StartFromSource_AfterDispose_ReleasesTheSubscription() + { + QuaternaryList list = []; + using VersionedCountingSource source = new(list); + var projection = CreateProjection(source); + projection.Dispose(); + + projection.StartFromSource(TimeSpan.Zero, ReactiveListScheduler.Immediate); + + await Assert.That(source.ActiveSubscriptions).IsEqualTo(0); + } + + /// Property changes requested after disposal come from a signal that is already disposed. + /// A task representing the asynchronous test. + [Test] + public async Task PropertyChanges_AfterDispose_ReturnsADisposedSignal() + { + using ReactiveList source = []; + var projection = CreateProjection(source); + projection.Dispose(); + + await Assert.That(projection.PropertyChanges).IsNotNull(); + } + + /// A property-change signal another thread created first is returned. + /// A task representing the asynchronous test. + [Test] + public async Task CreatePropertyChanges_AlreadyCreated_ReturnsTheExistingSignal() + { + using ReactiveList source = []; + using var projection = CreateProjection(source); + var first = projection.PropertyChanges; + + var second = projection.CreatePropertyChanges(); + + await Assert.That(second).IsSameReferenceAs(first); + } + + /// A change is not announced once the gate of the projection is closed. + /// A task representing the asynchronous test. + [Test] + public async Task NotifyChanged_GateClosed_AnnouncesNothing() + { + using ReactiveList source = [Value]; + using var projection = CreateProjection(source); + projection.StartFromSource(TimeSpan.Zero, ReactiveListScheduler.Immediate); + var observer = new CountingObserver(static _ => { }); + using var subscription = projection.PropertyChanges.Subscribe(observer); + projection.Target.Gate!.Close(); + + projection.Refresh(); + + await Assert.That(observer.Received).IsEqualTo(0); + } + + /// A listener that disposes the projection while it is announced does not break the drain. + /// A task representing the asynchronous test. + [Test] + public async Task NotifyChanged_ListenerDisposesTheProjection_IsDropped() + { + using ReactiveList source = [Value]; + var projection = CreateProjection(source); + projection.StartFromSource(TimeSpan.Zero, ReactiveListScheduler.Immediate); + var observer = new CountingObserver( + _ => + { + projection.Dispose(); + throw new ObjectDisposedException(nameof(projection)); + }); + using var subscription = projection.PropertyChanges.Subscribe(observer); + + projection.Refresh(); + + await Assert.That(observer.Received).IsEqualTo(1); + } + + /// A rebuild request for a projection whose rules cannot copy the source changes nothing. + /// A task representing the asynchronous test. + [Test] + public async Task Refresh_RulesWithoutSnapshot_ChangesNothing() + { + using StreamProjection projection = new(null, static item => item, new(static _ => true, null, null), ItemsProperty); + + projection.Refresh(); + + await Assert.That(projection.Target.Count).IsEqualTo(0); + } + + /// An update that names no previous element cannot be applied exactly and rebuilds the projection. + /// A task representing the asynchronous test. + [Test] + public async Task Drain_UpdateWithoutPrevious_RebuildsFromTheSource() + { + using ReactiveList source = [Accepted]; + using var projection = CreateProjection(source); + var before = projection.ResyncCount; + + projection.OnNext(new CacheNotify(CacheAction.Updated, Accepted)); + projection.Drain(); + + await Assert.That(projection.ResyncCount).IsGreaterThan(before); + } + + /// A batch removal of an item that belongs in the projection but was not found rebuilds it. + /// A task representing the asynchronous test. + [Test] + public async Task Drain_BatchRemovalOfMissingMatchingItem_RebuildsFromTheSource() + { + using ReactiveList source = [Accepted]; + using var projection = CreateProjection(source); + var before = projection.ResyncCount; + + projection.OnNext(RemovalOf("missing")); + projection.Drain(); + + await Assert.That(projection.ResyncCount).IsGreaterThan(before); + } + + /// A batch removal of an item that was never part of the projection leaves it alone. + /// A task representing the asynchronous test. + [Test] + public async Task Drain_BatchRemovalOfMissingRejectedItem_KeepsTheProjection() + { + using ReactiveList source = [Accepted]; + using StreamProjection projection = new( + source, + static item => item, + ViewSourceRules.Create(source, static item => item == Accepted), + ItemsProperty); + projection.Refresh(); + var before = projection.ResyncCount; + + projection.OnNext(RemovalOf(Rejected)); + projection.Drain(); + + await Assert.That(projection.ResyncCount).IsEqualTo(before); + } + + /// Only unconsumed leftovers that the rules still accept count as missing items. + /// A task representing the asynchronous test. + [Test] + public async Task AnyLeftoverMatches_ReportsOnlyUnconsumedMatchingItems() + { + using ReactiveList source = []; + using StreamProjection projection = new( + source, + static item => item, + ViewSourceRules.Create(source, static item => item == Accepted), + ItemsProperty); + var comparer = ItemComparison.SameItemComparer(); + Dictionary, int> accepted = new(comparer) { [new(Accepted)] = 1 }; + Dictionary, int> consumed = new(comparer) { [new(Accepted)] = 0 }; + Dictionary, int> rejected = new(comparer) { [new(Rejected)] = 1 }; + + using (Assert.Multiple()) + { + await Assert.That(projection.AnyLeftoverMatches(accepted)).IsTrue(); + await Assert.That(projection.AnyLeftoverMatches(consumed)).IsFalse(); + await Assert.That(projection.AnyLeftoverMatches(rejected)).IsFalse(); + } + } + + /// Creates a projection that accepts every item of a source. + /// The item type. + /// The source. + /// The property raised after a drain. + /// The projection. + private static StreamProjection CreateProjection(IReactiveSource source, string changedProperty = ItemsProperty) + where T : notnull => + new(source, static item => item, ViewSourceRules.Create(source, static _ => true), changedProperty); + + /// Creates a batch removal of one item. + /// The item removed. + /// The notification. + private static CacheNotify RemovalOf(string item) => + new(CacheAction.BatchRemoved, default, new PooledBatch([item], 1, ReturnToPool: false)); + + /// An observer that counts its notifications and runs a callback for each. + /// The notification type. + /// The callback run for each notification. + private sealed class CountingObserver(Action onNext) : IObserver + { + /// Gets the number of notifications received. + public int Received { get; private set; } + + /// + public void OnNext(TValue value) + { + Received++; + onNext(value); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnError(Exception error) + { + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted() + { + } + } +} diff --git a/src/tests/ReactiveList.Tests/StreamProjectionTests.cs b/src/tests/ReactiveList.Tests/StreamProjectionTests.cs new file mode 100644 index 00000000..d6f23577 --- /dev/null +++ b/src/tests/ReactiveList.Tests/StreamProjectionTests.cs @@ -0,0 +1,172 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies the start, failure, disposal and repair paths of . +public sealed class StreamProjectionTests +{ + /// The name of a property that is neither of the two the projection caches. + private const string CustomProperty = "Custom"; + + /// The name of the property the projection caches for counts. + private const string CountProperty = "Count"; + + /// The text the string source starts with. + private const string FirstText = "first"; + + /// A replacement text that names no previous value. + private const string SecondText = "second"; + + /// An item that is never in the source. + private const int AbsentItem = 99; + + /// The limit above which the largest values are filtered out. + private const int FilterLimit = 50; + + /// The items the source starts with. + private static readonly int[] _initialItems = [1, 2, 3]; + + /// Verifies a custom property name is the one that is published. + /// A task representing the asynchronous test. + [Test] + public async Task Drain_CustomChangedProperty_PublishesThatName() + { + using var source = CreateSource(); + using var projection = Create(source, static _ => true, CustomProperty); + projection.StartFromSource(TimeSpan.Zero, ReactiveListScheduler.Immediate); + string? published = null; + using var subscription = projection.PropertyChanges.Subscribe(args => published = args.PropertyName); + + source.Notifications.Emit(new(CacheAction.Added, AbsentItem)); + + await Assert.That(published).IsEqualTo(CustomProperty); + } + + /// Verifies a failure without a handler is rethrown and a failure with a handler reaches it. + /// A task representing the asynchronous test. + [Test] + public async Task OnError_WithAndWithoutHandler_RethrowsOrForwards() + { + using var source = CreateSource(); + using var projection = Create(source, static _ => true, CountProperty); + await Assert.That(() => projection.OnError(new InvalidOperationException())).Throws(); + + Exception? received = null; + var completed = 0; + projection.StartFromSource(TimeSpan.Zero, ReactiveListScheduler.Immediate, onError: error => received = error, onCompleted: () => completed++); + + projection.OnError(new ArgumentException()); + projection.OnCompleted(); + + await Assert.That(received).IsTypeOf(); + await Assert.That(completed).IsEqualTo(1); + } + + /// Verifies a projection disposed before it started releases the subscription and exposes a disposed property stream. + /// A task representing the asynchronous test. + [Test] + public async Task StartFromSource_AfterDispose_ReleasesTheSubscription() + { + using var source = CreateSource(); + var projection = Create(source, static _ => true, CountProperty); + projection.Dispose(); + + projection.StartFromSource(TimeSpan.Zero, ReactiveListScheduler.Immediate); + + await Assert.That(source.Notifications.HasObserver).IsFalse(); + await Assert.That(projection.Target.Count).IsEqualTo(0); + await Assert.That(() => projection.PropertyChanges.Subscribe(static _ => { })).Throws(); + } + + /// Verifies a rebuild with rules that have no snapshot leaves the projection alone. + /// A task representing the asynchronous test. + [Test] + public async Task Refresh_RulesWithoutSnapshot_LeavesTheProjectionAlone() + { + using var projection = new StreamProjection(null, static item => item, new(static _ => true, null, null), CountProperty); + + projection.Refresh(); + + await Assert.That(projection.ResyncCount).IsEqualTo(0); + } + + /// Verifies an update that does not name the replaced item forces a rebuild from the source. + /// A task representing the asynchronous test. + [Test] + public async Task OnNext_UpdateWithoutPrevious_RebuildsFromTheSource() + { + // Only a reference item can lack a previous value. + using var source = new ScriptedViewSource(); + source.Add(FirstText); + using var projection = new StreamProjection(source, static item => item, ViewSourceRules.Create(source, static _ => true), CountProperty); + projection.StartFromSource(TimeSpan.Zero, ReactiveListScheduler.Immediate); + var copiesBefore = projection.ResyncCount; + + projection.OnNext(new CacheNotify(CacheAction.Updated, SecondText)); + + await Assert.That(projection.ResyncCount).IsGreaterThan(copiesBefore); + await Assert.That(projection.Target).IsEquivalentTo([FirstText], CollectionOrdering.Matching); + } + + /// Verifies a notification that the last copy of the source already includes is dropped instead of applied twice. + /// A task representing the asynchronous test. + [Test] + public async Task StartFromSource_NotificationCoveredByTheCopy_IsNotAppliedTwice() + { + using var source = CreateSource(); + using var projection = Create(source, static _ => true, CountProperty); + + // The change lands while the first copy is being read, so the copy already includes it. + source.OnCopy = () => + { + source.Add(AbsentItem); + source.Notifications.Emit(new(CacheAction.Added, AbsentItem)); + }; + + projection.StartFromSource(TimeSpan.Zero, ReactiveListScheduler.Immediate); + + await Assert.That(projection.Target).IsEquivalentTo([.. _initialItems, AbsentItem], CollectionOrdering.Matching); + } + + /// Verifies a large batch removal of an item the projection lacks leaves the projection matching the source, whether or not the item belongs in it. + /// The exclusive upper bound the rules accept. + /// A task representing the asynchronous test. + [Test] + [Arguments(int.MaxValue)] + [Arguments(FilterLimit)] + public async Task OnNext_BatchRemovalOfMissingItem_KeepsTheProjectionInStep(int filterLimit) + { + using var source = CreateSource(); + using var projection = Create(source, item => item < filterLimit, CountProperty); + projection.StartFromSource(TimeSpan.Zero, ReactiveListScheduler.Immediate); + projection.Target.ResetLimit = 0; + int[] removed = [AbsentItem]; + + projection.OnNext(new CacheNotify(CacheAction.BatchRemoved, default, new PooledBatch(removed, removed.Length, ReturnToPool: false))); + + await Assert.That(projection.Target).IsEquivalentTo(_initialItems, CollectionOrdering.Matching); + } + + /// Creates a source that holds the initial items. + /// The source. + private static ScriptedViewSource CreateSource() + { + var source = new ScriptedViewSource(); + foreach (var item in _initialItems) + { + source.Add(item); + } + + return source; + } + + /// Creates a projection of every source item that the filter accepts. + /// The source. + /// The membership predicate. + /// The property the projection publishes. + /// The projection. + private static StreamProjection Create(ScriptedViewSource source, Func filter, string changedProperty) => + new(source, static item => item, ViewSourceRules.Create(source, filter), changedProperty); +} diff --git a/src/tests/ReactiveList.Tests/StressRandom.cs b/src/tests/ReactiveList.Tests/StressRandom.cs new file mode 100644 index 00000000..a65bb5f1 --- /dev/null +++ b/src/tests/ReactiveList.Tests/StressRandom.cs @@ -0,0 +1,46 @@ +// 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. + +namespace ReactiveList.Tests; + +/// A small deterministic random source, so a stress seed reproduces the same operation sequence. +internal sealed class StressRandom +{ + /// The multiplier that spreads small seeds across the state space. + private const uint SeedMultiplier = 2_654_435_761; + + /// The first xorshift shift amount. + private const int FirstShift = 13; + + /// The second xorshift shift amount. + private const int SecondShift = 17; + + /// The third xorshift shift amount. + private const int ThirdShift = 5; + + /// The generator state, which is never zero. + private uint _state; + + /// Initializes a new instance of the class. + /// The seed that selects the sequence. + internal StressRandom(int seed) => _state = (unchecked((uint)seed) * SeedMultiplier) | 1U; + + /// Returns on roughly one call in . + /// The odds against, which must be positive. + /// Whether the rare event happens. + internal bool OneIn(int odds) => Next(odds) == 0; + + /// Returns the next value in the sequence. + /// The exclusive upper bound, which must be positive. + /// A value from zero up to but not including . + internal int Next(int maxExclusive) + { + var x = _state; + x ^= x << FirstShift; + x ^= x >> SecondShift; + x ^= x << ThirdShift; + _state = x; + return (int)(x % (uint)maxExclusive); + } +} diff --git a/src/tests/ReactiveList.Tests/StressSettings.cs b/src/tests/ReactiveList.Tests/StressSettings.cs new file mode 100644 index 00000000..09bfb4b1 --- /dev/null +++ b/src/tests/ReactiveList.Tests/StressSettings.cs @@ -0,0 +1,33 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Holds the sizes shared by the multi-threaded collection workloads. +internal static class StressSettings +{ + /// The number of worker threads in a stress run. + internal const int WorkerCount = 6; + + /// The number of operations each worker performs. + internal const int OperationsPerWorker = 1500; + + /// The number of distinct item identities used by the stress workers. + internal const int Universe = 16; + + /// The modulus of the predicate used by RemoveMany in the workloads. + internal const int RemoveModulus = 7; + + /// The upper bound of dictionary values in the workloads. + internal const int ValueRange = 100; + + /// The odds against a rare operation in the workloads. + internal const int RareOdds = 8; + + /// The spare slots added to arrays that receive a copy. + internal const int CopySpare = 8; + + /// The maximum time a stress run may take before it is treated as a deadlock. + internal static readonly TimeSpan Timeout = TimeSpan.FromSeconds(60); +} diff --git a/src/tests/ReactiveList.Tests/ThrowingEqualityItem.cs b/src/tests/ReactiveList.Tests/ThrowingEqualityItem.cs new file mode 100644 index 00000000..4cce7aae --- /dev/null +++ b/src/tests/ReactiveList.Tests/ThrowingEqualityItem.cs @@ -0,0 +1,91 @@ +// 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. + +namespace ReactiveList.Tests; + +/// An item whose equality or hash code fails once armed, to model user code that throws in the middle of a collection operation. +internal sealed class ThrowingEqualityItem : IEquatable +{ + /// The hash code shared by every item that asks for one, which puts them in the same shard. + private readonly int? _sharedHash; + + /// Initializes a new instance of the class. + /// The identity of the item. + /// A hash code to use instead of the name's, or . + internal ThrowingEqualityItem(string name, int? sharedHash = null) + { + Name = name; + _sharedHash = sharedHash; + Failure = new(name); + } + + /// Gets the identity of the item. + internal string Name { get; } + + /// Gets the switch that makes this item's equality and hash code fail. + internal FailureSwitch Failure { get; } + + /// + public bool Equals(ThrowingEqualityItem? other) + { + if (other is null) + { + return false; + } + + Failure.CheckEquals(); + other.Failure.CheckEquals(); + return Name == other.Name; + } + + /// + public override bool Equals(object? obj) => obj is ThrowingEqualityItem other && Equals(other); + + /// + public override int GetHashCode() + { + Failure.CheckHash(); + return _sharedHash ?? StringComparer.Ordinal.GetHashCode(Name); + } + + /// + public override string ToString() => Name; + + /// Holds the armed state of one item, away from the members the hash code depends on. + internal sealed class FailureSwitch + { + /// The name of the item that owns this switch. + private readonly string _owner; + + /// Initializes a new instance of the class. + /// The name of the item that owns the switch. + internal FailureSwitch(string owner) => _owner = owner; + + /// Gets or sets a value indicating whether the hash code fails. + internal bool OnHash { get; set; } + + /// Gets or sets a value indicating whether equality fails when the item takes part. + internal bool OnEquals { get; set; } + + /// Fails when the hash code is armed. + /// The hash code was armed to fail. + internal void CheckHash() + { + if (OnHash) + { + throw new InvalidOperationException($"GetHashCode failed for {_owner}."); + } + } + + /// Fails when equality is armed. + /// Equality was armed to fail. + internal void CheckEquals() + { + if (OnEquals) + { + throw new InvalidOperationException($"Equals failed for {_owner}."); + } + } + } +} diff --git a/src/tests/ReactiveList.Tests/VersionedCountingSource.cs b/src/tests/ReactiveList.Tests/VersionedCountingSource.cs new file mode 100644 index 00000000..0764b1f2 --- /dev/null +++ b/src/tests/ReactiveList.Tests/VersionedCountingSource.cs @@ -0,0 +1,95 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Wraps a sharded list as a versioned source and counts the subscriptions made to its versioned stream. +/// The item type. +internal sealed class VersionedCountingSource : IReactiveSource, IVersionedSnapshotSource + where T : notnull +{ + /// The wrapped list. + private readonly QuaternaryList _inner; + + /// The number of subscriptions made so far. + private int _subscriptions; + + /// The number of subscriptions that were disposed. + private int _disposedSubscriptions; + + /// Initializes a new instance of the class. + /// The list to wrap. + internal VersionedCountingSource(QuaternaryList inner) + { + _inner = inner; + VersionedStream = Signal.Create>(Subscribe); + } + + /// + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add => ((INotifyCollectionChanged)_inner).CollectionChanged += value; + remove => ((INotifyCollectionChanged)_inner).CollectionChanged -= value; + } + + /// + public int Count => _inner.Count; + + /// + public bool IsReadOnly => _inner.IsReadOnly; + + /// + public bool IsDisposed => _inner.IsDisposed; + + /// + public long Version => _inner.Version; + + /// + public IObservable> Stream => _inner.Stream; + + /// + public IObservable> VersionedStream { get; } + + /// Gets or sets a value indicating whether copying the source fails. + internal bool FailCopies { get; set; } + + /// Gets the number of subscriptions that are still active. + internal int ActiveSubscriptions => Volatile.Read(ref _subscriptions) - Volatile.Read(ref _disposedSubscriptions); + + /// + public T[] CopyVersioned(out long version) => + FailCopies ? throw new InvalidOperationException("The copy was told to fail.") : _inner.CopyVersioned(out version); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T[] ToArray() => _inner.ToArray(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _inner.Dispose(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator GetEnumerator() => _inner.GetEnumerator(); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// Subscribes to the wrapped versioned stream and counts the subscription. + /// The observer. + /// The subscription. + private IDisposable Subscribe(IObserver> observer) + { + _ = Interlocked.Increment(ref _subscriptions); + var inner = _inner.VersionedStream.Subscribe(observer); + return Scope.Create( + (inner, this), + static state => + { + state.inner.Dispose(); + _ = Interlocked.Increment(ref state.Item2._disposedSubscriptions); + }); + } +} diff --git a/src/tests/ReactiveList.Tests/VersionedDictionaryReplica.cs b/src/tests/ReactiveList.Tests/VersionedDictionaryReplica.cs new file mode 100644 index 00000000..232b0a4d --- /dev/null +++ b/src/tests/ReactiveList.Tests/VersionedDictionaryReplica.cs @@ -0,0 +1,149 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Keeps a copy of an integer dictionary up to date from its versioned snapshot and versioned stream. +internal sealed class VersionedDictionaryReplica : IDisposable +{ + /// The guard for the copy. + private readonly Lock _gate = new(); + + /// The dictionary being followed. + private readonly IVersionedSnapshotSource> _source; + + /// The copied entries. + private readonly Dictionary _entries = []; + + /// The subscription to the versioned stream. + private readonly IDisposable _subscription; + + /// The version up to which the copy is current. + private long _covered; + + /// Initializes a new instance of the class. + /// The dictionary to follow. + internal VersionedDictionaryReplica(IVersionedSnapshotSource> source) + { + _source = source; + _subscription = source.VersionedStream.Subscribe(OnNext); + lock (_gate) + { + Resync(); + } + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _subscription.Dispose(); + + /// Gets a copy of the replicated entries ordered by key. + /// The entries. + internal KeyValuePair[] Snapshot() + { + lock (_gate) + { + var copy = _entries.ToArray(); + Array.Sort(copy, static (left, right) => left.Key.CompareTo(right.Key)); + return copy; + } + } + + /// Applies one versioned notification. + /// The notification. + private void OnNext(VersionedNotification> versioned) + { + lock (_gate) + { + if (versioned.Version <= _covered) + { + return; + } + + _covered = versioned.Version; + Apply(versioned.Notification); + } + } + + /// Replaces the copy with a fresh versioned snapshot; call with the gate held. + private void Resync() + { + var copy = _source.CopyVersioned(out var version); + _entries.Clear(); + for (var i = 0; i < copy.Length; i++) + { + _entries[copy[i].Key] = copy[i].Value; + } + + _covered = Math.Max(_covered, version); + } + + /// Applies a notification to the copy; call with the gate held. + /// The notification. + private void Apply(CacheNotify> notification) + { + switch (notification.Action) + { + case CacheAction.Added or CacheAction.Updated: + { + _entries[notification.Item.Key] = notification.Item.Value; + break; + } + + case CacheAction.Removed: + { + _ = _entries.Remove(notification.Item.Key); + break; + } + + case CacheAction.Cleared: + { + _entries.Clear(); + break; + } + + case CacheAction.BatchAdded: + { + for (var i = 0; i < notification.Batch!.Count; i++) + { + _entries[notification.Batch.Items[i].Key] = notification.Batch.Items[i].Value; + } + + break; + } + + case CacheAction.BatchRemoved: + { + for (var i = 0; i < notification.Batch!.Count; i++) + { + _ = _entries.Remove(notification.Batch.Items[i].Key); + } + + break; + } + + case CacheAction.Reset when notification.Batch is not null: + { + _entries.Clear(); + for (var i = 0; i < notification.Batch.Count; i++) + { + _entries[notification.Batch.Items[i].Key] = notification.Batch.Items[i].Value; + } + + break; + } + + case CacheAction.Reset or CacheAction.BatchOperation: + { + Resync(); + break; + } + + default: + { + break; + } + } + } +} diff --git a/src/tests/ReactiveList.Tests/VersionedListReplica.cs b/src/tests/ReactiveList.Tests/VersionedListReplica.cs new file mode 100644 index 00000000..2e23655f --- /dev/null +++ b/src/tests/ReactiveList.Tests/VersionedListReplica.cs @@ -0,0 +1,194 @@ +// 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. + +namespace ReactiveList.Tests; + +/// +/// Keeps a copy of a collection up to date the way a view does: subscribe to the versioned stream, take a versioned snapshot, +/// ignore notifications the snapshot already reflects, apply the rest, and take a new snapshot when a notification has no payload. +/// +/// The item type. +internal sealed class VersionedListReplica : IDisposable + where T : notnull +{ + /// The guard for the copy. + private readonly Lock _gate = new(); + + /// The collection being followed. + private readonly IVersionedSnapshotSource _source; + + /// The copied items. + private readonly List _items = []; + + /// The subscription to the versioned stream. + private readonly IDisposable _subscription; + + /// The version up to which the copy is current. + private long _covered; + + /// Initializes a new instance of the class. + /// The collection to follow. + internal VersionedListReplica(IVersionedSnapshotSource source) + { + _source = source; + _subscription = source.VersionedStream.Subscribe(OnNext); + Resync(); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _subscription.Dispose(); + + /// Gets a copy of the replicated items. + /// The items in replica order. + internal T[] Snapshot() + { + lock (_gate) + { + return [.. _items]; + } + } + + /// Applies one versioned notification. + /// The notification. + private void OnNext(VersionedNotification versioned) + { + lock (_gate) + { + if (versioned.Version <= _covered) + { + return; + } + + _covered = versioned.Version; + Apply(versioned.Notification); + } + } + + /// Replaces the copy with a fresh versioned snapshot. + private void Resync() + { + lock (_gate) + { + var copy = _source.CopyVersioned(out var version); + _items.Clear(); + _items.AddRange(copy); + _covered = version; + } + } + + /// Applies a notification to the copy. + /// The notification. + private void Apply(CacheNotify notification) + { + switch (notification.Action) + { + case CacheAction.Added: + { + _items.Insert(notification.CurrentIndex < 0 ? _items.Count : notification.CurrentIndex, notification.Item!); + break; + } + + case CacheAction.Removed: + { + RemoveOne(notification); + break; + } + + case CacheAction.Updated: + { + _items[notification.CurrentIndex] = notification.Item!; + break; + } + + case CacheAction.Moved: + { + _items.RemoveAt(notification.PreviousIndex); + _items.Insert(notification.CurrentIndex, notification.Item!); + break; + } + + case CacheAction.Cleared: + { + _items.Clear(); + break; + } + + case CacheAction.BatchAdded: + { + InsertBatch(notification); + break; + } + + case CacheAction.BatchRemoved: + { + RemoveBatch(notification); + break; + } + + case CacheAction.Reset when notification.Batch is not null: + { + _items.Clear(); + InsertBatch(notification); + break; + } + + case CacheAction.Reset or CacheAction.BatchOperation: + { + var copy = _source.CopyVersioned(out var version); + _items.Clear(); + _items.AddRange(copy); + _covered = Math.Max(_covered, version); + break; + } + + default: + { + break; + } + } + } + + /// Removes one item by position when it has one, otherwise by value. + /// The notification. + private void RemoveOne(CacheNotify notification) + { + if (notification.CurrentIndex >= 0) + { + _items.RemoveAt(notification.CurrentIndex); + return; + } + + _ = _items.Remove(notification.Item!); + } + + /// Inserts a batch at its index, or at the end when it has none. + /// The notification. + private void InsertBatch(CacheNotify notification) + { + var batch = notification.Batch!; + var index = notification.CurrentIndex < 0 ? _items.Count : notification.CurrentIndex; + for (var i = 0; i < batch.Count; i++) + { + _items.Insert(index + i, batch.Items[i]); + } + } + + /// Removes a batch by position, or by value when it has no position. + /// The notification. + private void RemoveBatch(CacheNotify notification) + { + var batch = notification.Batch!; + if (notification.CurrentIndex >= 0) + { + _items.RemoveRange(notification.CurrentIndex, batch.Count); + return; + } + + for (var i = 0; i < batch.Count; i++) + { + _ = _items.Remove(batch.Items[i]); + } + } +} diff --git a/src/tests/ReactiveList.Tests/VersionedReplicaFuzzTests.cs b/src/tests/ReactiveList.Tests/VersionedReplicaFuzzTests.cs new file mode 100644 index 00000000..057a2df6 --- /dev/null +++ b/src/tests/ReactiveList.Tests/VersionedReplicaFuzzTests.cs @@ -0,0 +1,342 @@ +// 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. + +namespace ReactiveList.Tests; + +/// +/// After any random sequence of public mutators, a replica built from CopyVersioned plus VersionedStream must equal the collection. +/// +public sealed class VersionedReplicaFuzzTests +{ + /// The number of random scenarios per collection. + private const int Scenarios = 250; + + /// The number of operations in each scenario. + private const int Steps = 45; + + /// The range of generated values; a small range keeps duplicates frequent. + private const int Values = 9; + + /// The divisor used by predicate-based operations and index keys. + private const int Divisor = 3; + + /// The name of the index maintained by the quaternary scenarios. + private const string IndexName = "mod"; + + /// The operations on a reactive list; operations that do not fit the current contents do nothing. + private static readonly Action>, Step>[] ListOperations = + [ + static (s, p) => s.Collection.Add(p.A), + static (s, p) => s.Collection.Insert(p.C % (s.Collection.Count + 1), p.A), + static (s, p) => s.Collection.InsertRange(p.C % (s.Collection.Count + 1), [p.A, p.B, p.A]), + static (s, p) => _ = s.Collection.Remove(p.A), + static (s, p) => s.Collection.Remove([p.A, p.B, p.A]), + static (s, p) => + { + if (s.Collection.Count > 0) + { + s.Collection.RemoveAt(p.C % s.Collection.Count); + } + }, + static (s, p) => + { + if (s.Collection.Count > 1) + { + s.Collection.RemoveRange(p.C % (s.Collection.Count - 1), 1); + } + }, + static (s, p) => _ = s.Collection.RemoveMany(value => value % Divisor == p.A % Divisor), + static (s, p) => s.Collection.ReplaceAll([p.B, p.A, p.B]), + static (s, p) => s.Collection.Update(p.A, p.B), + static (s, p) => + { + if (s.Collection.Count > 0) + { + s.Collection[p.C % s.Collection.Count] = p.B; + } + }, + static (s, p) => + { + if (s.Collection.Count > 1) + { + s.Collection.Move(p.C % s.Collection.Count, p.A % s.Collection.Count); + } + }, + static (s, _) => s.Collection.Clear(), + static (s, _) => s.Collection.ClearWithoutDeallocation(notifyChange: false), + static (s, _) => s.Collection.ClearWithoutDeallocation(notifyChange: true), + static (s, p) => s.Collection.Edit(editor => + { + editor.Add(p.A); + _ = editor.Remove(p.B); + if (editor.Count > 1) + { + editor.Move(0, editor.Count - 1); + } + }), + static (s, p) => s.Collection.AddRange([p.A, p.B]), + static (s, p) => s.Collection.AddRange(new ReadOnlySpan([p.A, p.B, p.B])), + static (s, p) => _ = ((IList)s.Collection).Add(p.A), + static (s, p) => ToggleDeferral(s, s.Collection.DeferNotifications, p), + static (s, p) => ToggleDeferral(s, s.Collection.DeferNotifications, p), + ]; + + /// The operations on a quaternary list. + private static readonly Action>, Step>[] QuaternaryListOperations = + [ + static (s, p) => s.Collection.Add(p.A), + static (s, p) => s.Collection.Add(p.B), + static (s, p) => _ = s.Collection.Remove(p.A), + static (s, _) => s.Collection.Clear(), + static (s, p) => s.Collection.AddRange([p.A, p.B, p.A]), + static (s, p) => s.Collection.RemoveRange([p.A, p.B, p.A]), + static (s, p) => _ = s.Collection.RemoveMany(value => value % Divisor == p.A % Divisor), + static (s, p) => s.Collection.ReplaceAll([p.B, p.A, p.B]), + static (s, p) => s.Collection.Edit(editor => + { + editor.Add(p.A); + _ = editor.Remove(p.B); + }), + static (s, _) => s.Collection.Edit(static editor => editor.Clear()), + static (s, _) => + { + s.Collection.AddIndex(IndexName, static value => value % Divisor); + s.Indexed.Value = true; + }, + static (s, p) => ToggleDeferral(s, s.Collection.DeferNotifications, p), + static (s, p) => ToggleDeferral(s, s.Collection.DeferNotifications, p), + ]; + + /// The operations on a quaternary dictionary. + private static readonly Action>, Step>[] DictionaryOperations = + [ + static (s, p) => _ = s.Collection.TryAdd(p.A, p.B), + static (s, p) => s.Collection.AddOrUpdate(p.A, p.B), + static (s, p) => _ = s.Collection.Remove(p.A), + static (s, p) => _ = s.Collection.Remove(new KeyValuePair(p.A, p.B)), + static (s, _) => s.Collection.Clear(), + static (s, p) => s.Collection.AddRange([new(p.A, p.B), new(p.B, p.A), new(p.A, p.A)]), + static (s, p) => s.Collection.RemoveKeys([p.A, p.B]), + static (s, p) => _ = s.Collection.RemoveMany(pair => pair.Value % Divisor == p.A % Divisor), + static (s, p) => s.Collection.Edit(editor => + { + editor[p.A] = p.B; + _ = editor.Remove(p.B); + }), + static (s, _) => s.Collection.Edit(static editor => editor.Clear()), + static (s, _) => + { + s.Collection.AddValueIndex(IndexName, static value => value % Divisor); + s.Indexed.Value = true; + }, + static (s, p) => ToggleDeferral(s, s.Collection.DeferNotifications, p), + static (s, p) => ToggleDeferral(s, s.Collection.DeferNotifications, p), + ]; + + /// A replica of a ends equal to it after random mutators, including silent clears and deferrals. + /// A task representing the asynchronous test. + [Test] + public async Task ReactiveList_Replica_EqualsListAfterRandomMutators() + { + for (var seed = 0; seed < Scenarios; seed++) + { + var random = new StressRandom(seed); + using var list = new ReactiveList(RandomItems(random)); + var scenario = new Scenario>(list); + using var replica = Run(scenario, random, ListOperations, static l => new VersionedListReplica(l)); + + await Assert.That(replica.Snapshot()).IsEquivalentTo(list.ToArray(), CollectionOrdering.Matching).Because($"seed {seed}"); + } + } + + /// A replica of a ends equal to it after random mutators, deferrals and index changes. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryList_Replica_EqualsListAfterRandomMutators() + { + for (var seed = 0; seed < Scenarios; seed++) + { + var random = new StressRandom(seed); + using var list = new QuaternaryList(); + list.AddRange(RandomItems(random)); + var scenario = new Scenario>(list); + using var replica = Run(scenario, random, QuaternaryListOperations, static l => new VersionedListReplica(l)); + + await WaitUntilEqualAsync(seed, replica, list); + if (scenario.Indexed.Value) + { + AssertIndexMatches(seed, list.ToArray(), key => list.GetItemsBySecondaryIndex(IndexName, key)); + } + } + } + + /// A replica of a ends equal to it after random mutators, deferrals and index changes. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryDictionary_Replica_EqualsDictionaryAfterRandomMutators() + { + for (var seed = 0; seed < Scenarios; seed++) + { + var random = new StressRandom(seed); + using var dictionary = new QuaternaryDictionary(); + dictionary.AddRange(RandomPairs(random)); + var scenario = new Scenario>(dictionary); + using var replica = Run(scenario, random, DictionaryOperations, static d => new VersionedDictionaryReplica(d)); + + await TestWaitHelpers.WaitUntilAsync(() => Sorted(dictionary.ToArray()).SequenceEqual(replica.Snapshot())); + if (scenario.Indexed.Value) + { + AssertIndexMatches( + seed, + [.. dictionary.ToArray().Select(static pair => pair.Value)], + key => dictionary.GetValuesBySecondaryIndex(IndexName, key)); + } + } + } + + /// Runs the random operations and attaches the replica part-way through. + /// The collection type. + /// The replica type. + /// The collection and its open deferrals. + /// The random source. + /// The operations to choose from. + /// Creates the replica for the collection. + /// The replica, after every deferral was released. + private static TReplica Run( + Scenario scenario, + StressRandom random, + Action, Step>[] operations, + Func attach) + where TCollection : class + where TReplica : IDisposable + { + TReplica? replica = default; + var attachAt = random.Next(Steps); + for (var step = 0; step < Steps; step++) + { + if (step == attachAt) + { + replica = attach(scenario.Collection); + } + + operations[random.Next(operations.Length)](scenario, new(random.Next(Values), random.Next(Values), random.Next(Values * Values))); + } + + replica ??= attach(scenario.Collection); + for (var i = scenario.Deferrals.Count - 1; i >= 0; i--) + { + scenario.Deferrals[i].Dispose(); + } + + scenario.Deferrals.Clear(); + return replica; + } + + /// Opens a deferral, or closes the innermost one. + /// The collection type. + /// The collection and its open deferrals. + /// Opens a new deferral. + /// The generated step. + private static void ToggleDeferral(Scenario scenario, Func open, Step step) + where TCollection : class + { + if (scenario.Deferrals.Count == 0 || step.C % Divisor == 0) + { + scenario.Deferrals.Add(open()); + return; + } + + scenario.Deferrals[^1].Dispose(); + scenario.Deferrals.RemoveAt(scenario.Deferrals.Count - 1); + } + + /// Creates random initial items. + /// The random source. + /// The items. + private static int[] RandomItems(StressRandom random) + { + var items = new int[random.Next(Values)]; + for (var i = 0; i < items.Length; i++) + { + items[i] = random.Next(Values); + } + + return items; + } + + /// Creates random initial entries. + /// The random source. + /// The entries. + private static KeyValuePair[] RandomPairs(StressRandom random) + { + var pairs = new KeyValuePair[random.Next(Values)]; + for (var i = 0; i < pairs.Length; i++) + { + pairs[i] = new(random.Next(Values), random.Next(Values)); + } + + return pairs; + } + + /// Orders entries by key. + /// The entries. + /// The same array, sorted. + private static KeyValuePair[] Sorted(KeyValuePair[] entries) + { + Array.Sort(entries, static (left, right) => left.Key.CompareTo(right.Key)); + return entries; + } + + /// Waits for an asynchronously fed replica to equal the list, reporting the seed when it never does. + /// The scenario seed. + /// The replica. + /// The list. + /// A task representing the asynchronous wait. + private static async Task WaitUntilEqualAsync(int seed, VersionedListReplica replica, QuaternaryList list) + { + try + { + await TestWaitHelpers.WaitUntilAsync(() => replica.Snapshot().Order().SequenceEqual(list.ToArray().Order())); + } + catch (TimeoutException) + { + Assert.Fail($"Seed {seed}: replica [{string.Join(',', replica.Snapshot().Order())}] differs from the list [{string.Join(',', list.ToArray().Order())}]."); + } + } + + /// Checks that a secondary index returns exactly the items with each key. + /// The scenario seed. + /// The collection contents. + /// Reads the index for a key. + private static void AssertIndexMatches(int seed, int[] contents, Func> lookup) + { + for (var key = 0; key < Divisor; key++) + { + var expected = contents.Where(value => value % Divisor == key).Order().ToArray(); + var indexed = lookup(key).Order().ToArray(); + if (!indexed.SequenceEqual(expected)) + { + Assert.Fail($"Seed {seed}: index key {key} holds [{string.Join(',', indexed)}] but the collection has [{string.Join(',', expected)}]."); + } + } + } + + /// The values that drive one generated operation. + /// The first value. + /// The second value. + /// A larger value for positions and choices. + private readonly record struct Step(int A, int B, int C); + + /// A collection under test together with the deferrals the scenario holds open. + /// The collection type. + /// The collection. + private sealed record Scenario(TCollection Collection) + { + /// Gets the deferrals that are currently open, innermost last. + public List Deferrals { get; } = []; + + /// Gets a flag that is set once the scenario registered the secondary index. + public StrongBox Indexed { get; } = new(); + } +} diff --git a/src/tests/ReactiveList.Tests/ViewBatchRemovalTests.cs b/src/tests/ReactiveList.Tests/ViewBatchRemovalTests.cs new file mode 100644 index 00000000..06efc036 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewBatchRemovalTests.cs @@ -0,0 +1,122 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies batch removals leave exactly the surviving items in a view, however many items leave. +public sealed class ViewBatchRemovalTests +{ + /// The number of items in the large removal. + private const int Large = 100; + + /// The number of items mutated so the filter rejects them. + private const int Mutated = 40; + + /// The distance between removed items in the positionless removal. + private const int Stride = 2; + + /// The number of items in the positionless removal. + private const int CountedItems = 400; + + /// The batch size above which the view replaces its contents with one reset. + private const int SmallLimit = 20; + + /// The value that passes the filter. + private const int Passing = 1; + + /// The value that fails the filter. + private const int Failing = 100; + + /// The first value that fails the filter. + private const int FilterLimit = 10; + + /// The values in a list with repeats. + private static readonly int[] Repeats = [1, 2, 1, 3, 1, 4, 1]; + + /// The values removed from a list with repeats. + private static readonly int[] RemovedRepeats = [1, 1, 2]; + + /// The values expected after removing the earliest repeats. + private static readonly int[] KeptRepeats = [3, 1, 4, 1]; + + /// Items the filter now rejects are still removed by a large range removal. + /// A task representing the asynchronous test. + [Test] + public async Task RemoveRange_LargeBatchWithItemsNoLongerMatching_EmptiesTheView() + { + using var list = new ReactiveList(); + var items = new MutableValue[Large]; + for (var i = 0; i < items.Length; i++) + { + items[i] = new(Passing); + } + + list.AddRange(items); + using var view = new ReactiveView(list, static item => item.Value < FilterLimit, TimeSpan.Zero, Sequencer.Immediate); + view.BatchResetLimit = SmallLimit; + for (var i = 0; i < Mutated; i++) + { + items[i].Value = Failing; + } + + list.RemoveRange(0, Large); + + await Assert.That(view.Items.Count).IsEqualTo(0); + } + + /// A positionless batch removal finds its items without comparing each one with the mirror. + /// A task representing the asynchronous test. + [Test] + public async Task PositionlessBatchRemoval_ManyItems_FindsThemInOnePass() + { + var items = new EqualityCountingItem[CountedItems]; + for (var i = 0; i < items.Length; i++) + { + items[i] = new(i); + } + + using var source = new ReactiveList(items); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + + // Every other item, newest first. + var removed = new EqualityCountingItem[CountedItems / Stride]; + for (var i = 0; i < removed.Length; i++) + { + removed[i] = items[CountedItems - 1 - (i * Stride)]; + } + + var array = ArrayPool.Shared.Rent(removed.Length); + Array.Copy(removed, array, removed.Length); + EqualityCountingItem.ResetComparisons(); + _ = buffer.Capture(new(CacheAction.BatchRemoved, null, new(array, removed.Length)), source.Version + 1); + _ = buffer.ApplyNext(sink); + + await Assert.That(EqualityCountingItem.Comparisons).IsEqualTo(0); + await Assert.That(sink.Events.Count).IsEqualTo(removed.Length); + await Assert.That(buffer.Items.Count).IsEqualTo(CountedItems - removed.Length); + for (var i = 0; i < buffer.Items.Count; i++) + { + await Assert.That(buffer.Items[i].Id % Stride).IsEqualTo(0); + } + } + + /// A large positionless removal removes the earliest equal items and keeps the rest in order. + /// A task representing the asynchronous test. + [Test] + public async Task RemoveByValue_Duplicates_RemovesEarliestOccurrences() + { + using var list = new ReactiveList(); + list.AddRange(Repeats); + using var filtered = new FilteredReactiveView(list, static _ => true, Sequencer.Immediate, TimeSpan.Zero); + using var sorted = new SortedReactiveView(list, Comparer.Default, Sequencer.Immediate, TimeSpan.Zero); + using var grouped = new GroupedReactiveView(list, static value => value, Sequencer.Immediate, TimeSpan.Zero); + + list.Remove(RemovedRepeats.AsEnumerable()); + + await Assert.That(filtered.Items).IsEquivalentTo(KeptRepeats, CollectionOrdering.Matching); + await Assert.That(sorted.Items).IsEquivalentTo(ViewFuzzSupport.Sorted(KeptRepeats), CollectionOrdering.Matching); + await Assert.That(grouped.Groups.Sum(static group => group.Items.Count)).IsEqualTo(KeptRepeats.Length); + } +} diff --git a/src/tests/ReactiveList.Tests/ViewBatchResetLimitTests.cs b/src/tests/ReactiveList.Tests/ViewBatchResetLimitTests.cs new file mode 100644 index 00000000..4e271515 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewBatchResetLimitTests.cs @@ -0,0 +1,257 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies a view raises one reset for a batch larger than its limit and ends in the same state either way. +public sealed class ViewBatchResetLimitTests +{ + /// The number of generated cases per property. + private const int Iterations = 200; + + /// The longest generated mutation sequence. + private const int MaxOps = 25; + + /// The largest generated limit. + private const int MaxLimit = 8; + + /// The number of items in the batch of the notification tests. + private const int BatchSize = 10; + + /// A limit smaller than the batch. + private const int SmallLimit = 4; + + /// Which view type is built. + public enum LimitedView + { + /// A filtered view. + Filtered = 0, + + /// A sorted view. + Sorted = 1, + + /// A dynamic view. + Dynamic = 2, + } + + /// Verifies a batch larger than the limit raises exactly one reset on every view that supports the limit. + /// The view kind. + /// A task representing the asynchronous test. + [Test] + [Arguments(LimitedView.Filtered)] + [Arguments(LimitedView.Sorted)] + [Arguments(LimitedView.Dynamic)] + public async Task BatchLargerThanLimit_RaisesOneReset(LimitedView kind) + { + using var list = new ReactiveList(); + using var view = Create(kind, list); + view.SetLimit(SmallLimit); + var actions = new List(); + view.Watch((_, args) => actions.Add(args.Action)); + + list.AddRange(Enumerable.Range(0, BatchSize).ToArray()); + + await Assert.That(actions).IsEquivalentTo([NotifyCollectionChangedAction.Reset]); + await Assert.That(ViewFuzzSupport.Sorted(view.Items)).IsEquivalentTo(Expected(kind, 0, BatchSize), CollectionOrdering.Matching); + + actions.Clear(); + list.Remove(Enumerable.Range(0, BatchSize - 1).ToArray().AsEnumerable()); + await Assert.That(actions).IsEquivalentTo([NotifyCollectionChangedAction.Reset]); + await Assert.That(ViewFuzzSupport.Sorted(view.Items)).IsEquivalentTo(Expected(kind, BatchSize - 1, 1), CollectionOrdering.Matching); + } + + /// Verifies a batch within the limit and the default limit raise one notification per item. + /// The view kind. + /// The limit to apply. + /// A task representing the asynchronous test. + [Test] + [Arguments(LimitedView.Filtered, BatchSize)] + [Arguments(LimitedView.Filtered, int.MaxValue)] + [Arguments(LimitedView.Sorted, BatchSize)] + [Arguments(LimitedView.Sorted, int.MaxValue)] + [Arguments(LimitedView.Dynamic, BatchSize)] + [Arguments(LimitedView.Dynamic, int.MaxValue)] + public async Task BatchWithinLimit_RaisesOneNotificationPerItem(LimitedView kind, int limit) + { + using var list = new ReactiveList(); + using var view = Create(kind, list); + view.SetLimit(limit); + var actions = new List(); + view.Watch((_, args) => actions.Add(args.Action)); + + list.AddRange(Enumerable.Range(0, BatchSize).ToArray()); + + await Assert.That(actions.Count).IsEqualTo(Expected(kind, 0, BatchSize).Length); + await Assert.That(actions.Contains(NotifyCollectionChangedAction.Reset)).IsFalse(); + } + + /// Verifies a negative limit is rejected. + /// A task representing the asynchronous test. + [Test] + public async Task BatchResetLimit_Negative_Throws() + { + using var list = new ReactiveList(); + using var view = new FilteredReactiveView(list, static _ => true, Sequencer.Immediate, TimeSpan.Zero); + await Assert.That(view.BatchResetLimit).IsEqualTo(int.MaxValue); + await Assert.That(() => view.BatchResetLimit = -1).Throws(); + } + + /// Verifies a view with a random limit ends with the same items as a view without one. + /// A task representing the asynchronous test. + [Test] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task Limit_DoesNotChangeTheFinalItems() => + Check.SampleAsync( + Gen.Select(ViewFuzzSupport.InitialGen, ViewFuzzSupport.OpsGen(MaxOps), Gen.Int[0, MaxLimit], Gen.Enum()), + RunAsync, + iter: Iterations, + threads: 1); + + /// Applies the mutations to a list watched by a limited and an unlimited view and compares them. + /// The initial items. + /// The mutations. + /// The limit of the limited view. + /// The view kind. + /// A task representing the asynchronous check. + private static async Task RunAsync(int[] initial, ViewFuzzOp[] ops, int limit, LimitedView kind) + { + using var list = new ReactiveList(); + list.AddRange(initial); + using var limited = Create(kind, list); + using var unlimited = Create(kind, list); + limited.SetLimit(limit); + + // An observer that mirrors the collection from its notifications proves a reset leaves nothing out. + var mirror = new List(limited.Items); + limited.Watch((_, args) => Mirror(mirror, limited.Items, args)); + + foreach (var op in ops) + { + ViewFuzzSupport.Apply(list, op); + } + + await Assert.That(ViewFuzzSupport.Copy(limited.Items)).IsEquivalentTo(ViewFuzzSupport.Copy(unlimited.Items), CollectionOrdering.Matching); + await Assert.That(mirror).IsEquivalentTo(ViewFuzzSupport.Copy(limited.Items), CollectionOrdering.Matching); + } + + /// Gets the items a view of a kind holds after the source holds a range of values. + /// The view kind. + /// The first value. + /// The number of values. + /// The values the view holds, sorted. + private static int[] Expected(LimitedView kind, int first, int count) + { + var values = Enumerable.Range(first, count); + return kind == LimitedView.Sorted ? [.. values] : [.. values.Where(ViewFuzzSupport.Passes)]; + } + + /// Applies a notification to a mirror of the collection. + /// The mirror. + /// The collection that raised the notification. + /// The notification. + private static void Mirror(List mirror, IReadOnlyList items, NotifyCollectionChangedEventArgs args) + { + switch (args.Action) + { + case NotifyCollectionChangedAction.Add: + { + mirror.Insert(args.NewStartingIndex, (int)args.NewItems![0]!); + break; + } + + case NotifyCollectionChangedAction.Remove: + { + mirror.RemoveAt(args.OldStartingIndex); + break; + } + + case NotifyCollectionChangedAction.Replace: + { + mirror[args.NewStartingIndex] = (int)args.NewItems![0]!; + break; + } + + case NotifyCollectionChangedAction.Move: + { + var item = mirror[args.OldStartingIndex]; + mirror.RemoveAt(args.OldStartingIndex); + mirror.Insert(args.NewStartingIndex, item); + break; + } + + default: + { + mirror.Clear(); + mirror.AddRange(ViewFuzzSupport.Copy(items)); + break; + } + } + } + + /// Creates a view over a list. + /// The view kind. + /// The source list. + /// The view. + private static LimitedHandle Create(LimitedView kind, ReactiveList list) + { + switch (kind) + { + case LimitedView.Filtered: + { + var view = new FilteredReactiveView(list, ViewFuzzSupport.Passes, Sequencer.Immediate, TimeSpan.Zero); + return new(view, view.Items, limit => view.BatchResetLimit = limit); + } + + case LimitedView.Sorted: + { + var view = new SortedReactiveView(list, Comparer.Default, Sequencer.Immediate, TimeSpan.Zero); + return new(view, view.Items, limit => view.BatchResetLimit = limit); + } + + default: + { + var filters = new BehaviorSignal>(ViewFuzzSupport.Passes); + var view = new DynamicReactiveView(list, filters, TimeSpan.Zero, Sequencer.Immediate); + return new(new DisposePair(view, filters), view.Items, limit => view.BatchResetLimit = limit); + } + } + } + + /// A view with a setter for its limit. + /// The view to dispose. + /// The view's collection. + /// Sets the limit. + private sealed class LimitedHandle(IDisposable view, ReadOnlyObservableCollection items, Action setLimit) : IDisposable + { + /// Gets the view's collection. + public ReadOnlyObservableCollection Items => items; + + /// Sets the limit. + /// The limit. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetLimit(int limit) => setLimit(limit); + + /// Subscribes to the view's collection notifications. + /// The handler. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Watch(NotifyCollectionChangedEventHandler handler) => ((INotifyCollectionChanged)items).CollectionChanged += handler; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => view.Dispose(); + } + + /// Disposes a view and the signal that feeds it. + /// The view. + /// The signal. + private sealed class DisposePair(IDisposable view, IDisposable signal) : IDisposable + { + /// + public void Dispose() + { + view.Dispose(); + signal.Dispose(); + } + } +} diff --git a/src/tests/ReactiveList.Tests/ViewChangeBufferMirrorTests.cs b/src/tests/ReactiveList.Tests/ViewChangeBufferMirrorTests.cs new file mode 100644 index 00000000..c7f83cae --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewChangeBufferMirrorTests.cs @@ -0,0 +1,321 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies how a repairs its mirror when notifications are incomplete or disagree with the source. +public sealed class ViewChangeBufferMirrorTests +{ + /// The event the recording sink writes when the mirror is rebuilt. + private const string ResetEvent = "reset"; + + /// The event the recording sink writes when one item is inserted at index one. + private const string InsertSecond = "insert:1:1"; + + /// The first source item. + private const string First = "first"; + + /// The second source item. + private const string Second = "second"; + + /// The third source item. + private const string Third = "third"; + + /// An item that is not in any source. + private const string Absent = "absent"; + + /// The number of mirror items that makes a removal use one pass instead of one search per item. + private const int OnePassSize = 9; + + /// An index past the end of a two item mirror. + private const int PastTheEnd = 2; + + /// The source items shared by independent test instances. + private static readonly string[] _initialItems = [First, Second]; + + /// Verifies a reset notification replaces the mirror with its snapshot. + /// A task representing the asynchronous test. + [Test] + public async Task ApplyNext_ResetWithSnapshot_ReplacesMirror() + { + using var source = new ReactiveList(_initialItems); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + string[] replacement = [Third]; + _ = buffer.Capture(new(CacheAction.Reset, default, new PooledBatch(replacement, replacement.Length, ReturnToPool: false)), source.Version + 1); + + await Assert.That(buffer.ApplyNext(sink)).IsTrue(); + + await Assert.That(sink.Events).IsEquivalentTo([ResetEvent]); + await Assert.That(buffer.Items).IsEquivalentTo(replacement, CollectionOrdering.Matching); + } + + /// Verifies a notification that lacks the data it needs rebuilds the mirror from the source. + /// The notification action. + /// A task representing the asynchronous test. + [Test] + [Arguments(CacheAction.Added)] + [Arguments(CacheAction.Removed)] + [Arguments(CacheAction.Updated)] + [Arguments(CacheAction.Refreshed)] + [Arguments(CacheAction.BatchAdded)] + [Arguments(CacheAction.BatchRemoved)] + public async Task ApplyNext_NotificationWithoutItems_ResetsFromSource(CacheAction action) + { + using var source = new ReactiveList(_initialItems); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + _ = buffer.Capture(new(action, default), source.Version + 1); + + await Assert.That(buffer.ApplyNext(sink)).IsTrue(); + + await Assert.That(sink.Events).IsEquivalentTo([ResetEvent]); + await Assert.That(buffer.Items).IsEquivalentTo(_initialItems, CollectionOrdering.Matching); + } + + /// Verifies a refresh of an item the mirror does not hold rebuilds the mirror. + /// A task representing the asynchronous test. + [Test] + public async Task ApplyNext_RefreshOfAbsentItem_ResetsFromSource() + { + using var source = new ReactiveList(_initialItems); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + _ = buffer.Capture(new(CacheAction.Refreshed, Absent), source.Version + 1); + + await Assert.That(buffer.ApplyNext(sink)).IsTrue(); + + await Assert.That(sink.Events).IsEquivalentTo([ResetEvent]); + } + + /// Verifies a positional range removal that does not match the mirror rebuilds it. + /// The first removed position. + /// The removed item. + /// A task representing the asynchronous test. + [Test] + [Arguments(0, Second)] + [Arguments(PastTheEnd, First)] + public async Task ApplyNext_PositionalRemovalThatDisagrees_ResetsFromSource(int start, string item) + { + using var source = new ReactiveList(_initialItems); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + string[] removed = [item]; + _ = buffer.Capture(new(CacheAction.BatchRemoved, default, new PooledBatch(removed, removed.Length, ReturnToPool: false), CurrentIndex: start), source.Version + 1); + + await Assert.That(buffer.ApplyNext(sink)).IsTrue(); + + await Assert.That(sink.Events).IsEquivalentTo([ResetEvent]); + await Assert.That(buffer.Items).IsEquivalentTo(_initialItems, CollectionOrdering.Matching); + } + + /// Verifies a range removal without positions that names an absent item rebuilds the mirror, whichever search it uses. + /// The number of items the source holds. + /// A task representing the asynchronous test. + [Test] + [Arguments(1)] + [Arguments(OnePassSize)] + public async Task ApplyNext_UnpositionedRemovalOfAbsentItem_ResetsFromSource(int mirrorSize) + { + using var source = new ScriptedViewSource(); + var items = new string[mirrorSize]; + for (var i = 0; i < mirrorSize; i++) + { + items[i] = $"item{i}"; + source.Add(items[i]); + } + + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + items[^1] = Absent; + _ = buffer.Capture(new(CacheAction.BatchRemoved, default, new PooledBatch(items, items.Length, ReturnToPool: false)), source.Version + 1); + + await Assert.That(buffer.ApplyNext(sink)).IsTrue(); + + // Items found before the absent one are removed first, then the rebuild restores them. + await Assert.That(sink.Events[^1]).IsEqualTo(ResetEvent); + await Assert.That(buffer.Items.Count).IsEqualTo(mirrorSize); + } + + /// Verifies an unpositioned removal on a source without versions removes the first occurrence of a reference item. + /// The removed item. + /// The event the sink receives. + /// A task representing the asynchronous test. + [Test] + [Arguments(First, "remove:0")] + [Arguments(Second, "remove:1")] + public async Task ApplyNext_UnpositionedRemovalOfReferenceItem_RemovesFirstOccurrence(string item, string expectedEvent) + { + using var source = new ScriptedViewSource(); + source.Add(First); + source.Add(Second); + source.Add(First); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + string[] removed = [item]; + _ = buffer.Capture(new(CacheAction.BatchRemoved, default, new PooledBatch(removed, removed.Length, ReturnToPool: false)), source.Version + 1); + + await Assert.That(buffer.ApplyNext(sink)).IsTrue(); + + await Assert.That(sink.Events).IsEquivalentTo([expectedEvent]); + await Assert.That(buffer.Items.Count).IsEqualTo(PastTheEnd); + } + + /// Verifies an unpositioned removal on a source without versions removes the first occurrence of a value item. + /// The removed item. + /// The event the sink receives. + /// A task representing the asynchronous test. + [Test] + [Arguments(1, "remove:0")] + [Arguments(PastTheEnd, "remove:1")] + public async Task ApplyNext_UnpositionedRemovalOfValueItem_RemovesFirstOccurrence(int item, string expectedEvent) + { + using var source = new ScriptedViewSource(); + source.Add(1); + source.Add(PastTheEnd); + source.Add(1); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + int[] removed = [item]; + _ = buffer.Capture(new(CacheAction.BatchRemoved, default, new PooledBatch(removed, removed.Length, ReturnToPool: false)), source.Version + 1); + + await Assert.That(buffer.ApplyNext(sink)).IsTrue(); + + await Assert.That(sink.Events).IsEquivalentTo([expectedEvent]); + await Assert.That(buffer.Items.Count).IsEqualTo(PastTheEnd); + } + + /// Verifies the mirror is left alone when the source moved on after the last applied notification. + /// A task representing the asynchronous test. + [Test] + public async Task VerifyAtHead_SourceMovedAfterApply_LeavesMirror() + { + using var source = new ScriptedViewSource(); + source.Add(First); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + source.Add(Second); + ApplyInsertedBatch(buffer, sink, source, Second, 1); + source.Add(Third); + + buffer.VerifyAtHead(sink); + + await Assert.That(sink.Events).IsEquivalentTo([InsertSecond]); + await Assert.That(buffer.Items).IsEquivalentTo(_initialItems, CollectionOrdering.Matching); + } + + /// Verifies a range check that agrees with the source needs no copy and no repair. + /// A task representing the asynchronous test. + [Test] + public async Task VerifyAtHead_InsertedRangeMatchesSource_LeavesMirror() + { + using var source = new ScriptedViewSource(); + source.Add(First); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + source.Add(Second); + ApplyInsertedBatch(buffer, sink, source, Second, 1); + + buffer.VerifyAtHead(sink); + buffer.VerifyAtHead(sink); + + await Assert.That(sink.Events).IsEquivalentTo([InsertSecond]); + await Assert.That(buffer.Items).IsEquivalentTo(_initialItems, CollectionOrdering.Matching); + } + + /// Verifies a source with a different size than the mirror is copied and the mirror is rebuilt. + /// A task representing the asynchronous test. + [Test] + public async Task VerifyAtHead_SourceSizeDiffers_RebuildsMirror() + { + using var source = new ScriptedViewSource(); + source.Add(First); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + source.Add(Second); + ApplyInsertedBatch(buffer, sink, source, Second, 0, Third); + + buffer.VerifyAtHead(sink); + + await Assert.That(sink.Events).IsEquivalentTo(["insert:0:2", ResetEvent]); + await Assert.That(buffer.Items).IsEquivalentTo(_initialItems, CollectionOrdering.Matching); + } + + /// Verifies the mirror is left alone when the source changes while it is copied for the comparison. + /// A task representing the asynchronous test. + [Test] + public async Task VerifyAtHead_SourceChangesDuringCopy_LeavesMirror() + { + using var source = new ScriptedViewSource(); + source.Add(First); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + source.Add(Second); + ApplyInsertedBatch(buffer, sink, source, Third, 0); + source.OnCopy = () => source.Add(Third); + + buffer.VerifyAtHead(sink); + + await Assert.That(sink.Events).IsEquivalentTo(["insert:0:1"]); + } + + /// Verifies two unverified batches are compared in full and an agreeing mirror is kept. + /// A task representing the asynchronous test. + [Test] + public async Task VerifyAtHead_TwoUnverifiedBatchesThatAgree_LeavesMirror() + { + using var source = new ScriptedViewSource(); + source.Add(First); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + source.Add(Second); + ApplyInsertedBatch(buffer, sink, source, Second, 1); + source.Add(Third); + ApplyInsertedBatch(buffer, sink, source, Third, PastTheEnd); + + buffer.VerifyAtHead(sink); + + await Assert.That(sink.Events).IsEquivalentTo([InsertSecond, "insert:2:1"]); + await Assert.That(buffer.Items).IsEquivalentTo([First, Second, Third], CollectionOrdering.Matching); + } + + /// Verifies a source that shrinks while the range is checked falls back to the full comparison. + /// A task representing the asynchronous test. + [Test] + public async Task VerifyAtHead_SourceShrinksDuringRangeCheck_FallsBackToFullComparison() + { + using var source = new ScriptedViewSource(); + source.Add(First); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + source.Add(Second); + ApplyInsertedBatch(buffer, sink, source, Second, 1); + source.IndexerShrinks = true; + + buffer.VerifyAtHead(sink); + + await Assert.That(sink.Events).IsEquivalentTo([InsertSecond]); + await Assert.That(buffer.Items).IsEquivalentTo(_initialItems, CollectionOrdering.Matching); + } + + /// Captures and applies a range add at the current source revision. + /// The buffer to feed. + /// The sink that records the changes. + /// The source whose revision the notification carries. + /// The first inserted item. + /// The mirror index of the insert. + /// The items inserted after the first. + private static void ApplyInsertedBatch( + ViewChangeBuffer buffer, + RecordingMirrorSink sink, + ScriptedViewSource source, + string first, + int index, + params string[] more) + { + string[] inserted = [first, .. more]; + _ = buffer.Capture(new(CacheAction.BatchAdded, default, new PooledBatch(inserted, inserted.Length, ReturnToPool: false), CurrentIndex: index), source.Version); + _ = buffer.ApplyNext(sink); + } +} diff --git a/src/tests/ReactiveList.Tests/ViewChangeBufferTests.cs b/src/tests/ReactiveList.Tests/ViewChangeBufferTests.cs index dbb25514..c3d26c60 100644 --- a/src/tests/ReactiveList.Tests/ViewChangeBufferTests.cs +++ b/src/tests/ReactiveList.Tests/ViewChangeBufferTests.cs @@ -7,6 +7,9 @@ namespace ReactiveList.Tests; /// Verifies structural buffering, snapshot revisions and missing-index fallbacks. public sealed class ViewChangeBufferTests { + /// The event the recording sink writes when the mirror is rebuilt. + private const string ResetEvent = "reset"; + /// The first source item. private const string FirstItem = "first"; @@ -28,36 +31,63 @@ public sealed class ViewChangeBufferTests /// The source snapshot shared by independent test instances. private static readonly string[] _initialItems = [FirstItem, SecondItem]; - /// Verifies a missing removal index resolves one item without removing absent values. + /// Verifies a removal of an absent item repairs the mirror from the source. /// A task representing the asynchronous test. [Test] - public async Task Apply_RemoveWithoutIndex_UsesMembership() + public async Task ApplyNext_RemoveOfAbsentItem_ResetsFromSource() { using var source = new ReactiveList(_initialItems); var buffer = new ViewChangeBuffer(source); - buffer.Apply(Change.CreateRemove(MissingItem)); + var sink = new RecordingMirrorSink(); + _ = buffer.Capture(new(CacheAction.Removed, MissingItem), source.Version + 1); + await Assert.That(buffer.ApplyNext(sink)).IsTrue(); + await Assert.That(sink.Events).IsEquivalentTo([ResetEvent]); await Assert.That(buffer.Items).IsEquivalentTo(_initialItems, CollectionOrdering.Matching); - buffer.Apply(Change.CreateRemove(FirstItem)); - await Assert.That(buffer.Items.Count).IsEqualTo(1); - await Assert.That(buffer.Items[0]).IsEqualTo(SecondItem); } - /// Verifies updates without usable indexes resolve previous values and ignore missing occurrences. + /// Verifies a removal without a usable index finds the item by membership. /// A task representing the asynchronous test. [Test] - public async Task Apply_UpdateWithoutIndex_UsesPreviousOccurrence() + public async Task ApplyNext_RemoveWithoutIndex_UsesMembership() { using var source = new ReactiveList(_initialItems); var buffer = new ViewChangeBuffer(source); - buffer.Apply(new(ChangeReason.Update, ReplacementItem)); - buffer.Apply(Change.CreateUpdate(ReplacementItem, MissingItem, InvalidIndex)); - await Assert.That(buffer.Items).IsEquivalentTo(_initialItems, CollectionOrdering.Matching); - buffer.Apply(Change.CreateUpdate(ReplacementItem, SecondItem)); - await Assert.That(buffer.Items[0]).IsEqualTo(FirstItem); - await Assert.That(buffer.Items[1]).IsEqualTo(ReplacementItem); + var sink = new RecordingMirrorSink(); + _ = buffer.Capture(new(CacheAction.Removed, SecondItem), source.Version + 1); + _ = buffer.ApplyNext(sink); + await Assert.That(sink.Events).IsEquivalentTo(["remove:1"]); + await Assert.That(buffer.Items).IsEquivalentTo([FirstItem], CollectionOrdering.Matching); + } + + /// Verifies that removing a range does not remove an equal occurrence at a different index. + /// A task representing the asynchronous test. + [Test] + public async Task BatchRemoved_WithPosition_RemovesTheNamedOccurrence() + { + using ReactiveList source = [FirstItem, SecondItem, FirstItem]; + using var view = new FilteredReactiveView(source, static _ => true, Sequencer.Immediate, TimeSpan.Zero); + + source.RemoveRange(ReplacementValue, 1); + + await Assert.That(view.Items).IsEquivalentTo(_initialItems, CollectionOrdering.Matching); + } + + /// Verifies updates replace the previous occurrence and updates without it reset the mirror. + /// A task representing the asynchronous test. + [Test] + public async Task ApplyNext_Update_ReplacesPreviousOccurrenceOrResets() + { + using var source = new ReactiveList(_initialItems); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + _ = buffer.Capture(new(CacheAction.Updated, ReplacementItem, Previous: SecondItem, CurrentIndex: InvalidIndex), source.Version + 1); + _ = buffer.ApplyNext(sink); + _ = buffer.Capture(new(CacheAction.Updated, ReplacementItem, Previous: MissingItem, CurrentIndex: 0), source.Version + ReplacementValue); + _ = buffer.ApplyNext(sink); + await Assert.That(sink.Events).IsEquivalentTo(["replace:1", ResetEvent]); } - /// Verifies moves outside the mirror leave its order unchanged. + /// Verifies moves outside the mirror reset it from the source. /// The requested destination. /// The requested origin. /// A task representing the asynchronous test. @@ -66,24 +96,31 @@ public async Task Apply_UpdateWithoutIndex_UsesPreviousOccurrence() [Arguments(0, -1)] [Arguments(InvalidIndex, 0)] [Arguments(0, InvalidIndex)] - public async Task Apply_MoveOutsideBounds_PreservesSnapshot(int currentIndex, int previousIndex) + public async Task ApplyNext_MoveOutsideBounds_ResetsFromSource(int currentIndex, int previousIndex) { using var source = new ReactiveList(_initialItems); var buffer = new ViewChangeBuffer(source); - buffer.Apply(Change.CreateMove(FirstItem, currentIndex, previousIndex)); + var sink = new RecordingMirrorSink(); + _ = buffer.Capture(new(CacheAction.Moved, FirstItem, CurrentIndex: currentIndex, PreviousIndex: previousIndex), source.Version + 1); + _ = buffer.ApplyNext(sink); + await Assert.That(sink.Events).IsEquivalentTo([ResetEvent]); await Assert.That(buffer.Items).IsEquivalentTo(_initialItems, CollectionOrdering.Matching); } /// Verifies refresh preserves membership while clear removes the complete mirror. /// A task representing the asynchronous test. [Test] - public async Task Apply_RefreshAndClear_PreserveThenRemoveItems() + public async Task ApplyNext_RefreshAndClear_PreserveThenRemoveItems() { using var source = new ReactiveList(_initialItems); var buffer = new ViewChangeBuffer(source); - buffer.Apply(Change.CreateRefresh(FirstItem)); + var sink = new RecordingMirrorSink(); + _ = buffer.Capture(new(CacheAction.Refreshed, FirstItem), source.Version + 1); + _ = buffer.ApplyNext(sink); await Assert.That(buffer.Items).IsEquivalentTo(_initialItems, CollectionOrdering.Matching); - buffer.Apply(new(ChangeReason.Clear, string.Empty)); + _ = buffer.Capture(new(CacheAction.Cleared, default), source.Version + ReplacementValue); + _ = buffer.ApplyNext(sink); + await Assert.That(sink.Events).IsEquivalentTo(["refresh:0", "clear"]); await Assert.That(buffer.Items).IsEmpty(); } @@ -94,22 +131,37 @@ public async Task Reset_QueuedChanges_DiscardsCoveredRevisions() { using var source = new ReactiveList(_initialItems); var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); source.Add(MissingItem); - using var covered = new ChangeSet(new[] { Change.CreateAdd(MissingItem) }); - await Assert.That(buffer.Capture(covered, source.Version)).IsTrue(); - buffer.Reset(source); + await Assert.That(buffer.Capture(new(CacheAction.Added, MissingItem, CurrentIndex: 2), source.Version)).IsTrue(); + buffer.Reset(); source.Add(ReplacementItem); - using var subsequent = new ChangeSet(new[] { Change.CreateAdd(ReplacementItem) }); - await Assert.That(buffer.Capture(subsequent, source.Version)).IsTrue(); + await Assert.That(buffer.Capture(new(CacheAction.Added, ReplacementItem, CurrentIndex: 3), source.Version)).IsTrue(); await Assert.That(buffer.HasPending).IsTrue(); - await Assert.That(buffer.TryTake(out var changes)).IsTrue(); - await Assert.That(changes[0].Current).IsEqualTo(ReplacementItem); - buffer.Apply(changes[0]); + await Assert.That(buffer.ApplyNext(sink)).IsTrue(); + await Assert.That(sink.Events).IsEquivalentTo(["insert:3:1"]); await Assert.That(buffer.Items).IsEquivalentTo(source.ToArray(), CollectionOrdering.Matching); - await Assert.That(buffer.TryTake(out _)).IsFalse(); + await Assert.That(buffer.ApplyNext(sink)).IsFalse(); await Assert.That(buffer.HasPending).IsFalse(); } + /// Verifies batch notifications are verified against the source once every notification is applied. + /// A task representing the asynchronous test. + [Test] + public async Task VerifyAtHead_BatchWithWrongIndex_RepairsMirror() + { + using var source = new LiveQueryCountingList(new(_initialItems)); + var buffer = new ViewChangeBuffer(source); + var sink = new RecordingMirrorSink(); + source.AddRange([MissingItem]); + using var batch = new PooledBatch([MissingItem], 1, ReturnToPool: false); + _ = buffer.Capture(new(CacheAction.BatchAdded, default, batch, CurrentIndex: 0), source.Version); + _ = buffer.ApplyNext(sink); + buffer.VerifyAtHead(sink); + await Assert.That(sink.Events).IsEquivalentTo(["insert:0:1", ResetEvent]); + await Assert.That(buffer.Items).IsEquivalentTo(source.ToArray(), CollectionOrdering.Matching); + } + /// Verifies a source change during enumeration causes a fresh version-consistent snapshot. /// A task representing the asynchronous test. [Test] @@ -153,7 +205,11 @@ public event NotifyCollectionChangedEventHandler? CollectionChanged public IObservable> Stream => _source.Stream; /// - public IEnumerator GetEnumerator() + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator GetEnumerator() => ((IEnumerable)ToArray()).GetEnumerator(); + + /// + public int[] ToArray() { var snapshot = _source.ToArray(); if (!_mutated) @@ -162,13 +218,9 @@ public IEnumerator GetEnumerator() _source[0] = ReplacementValue; } - return ((IEnumerable)snapshot).GetEnumerator(); + return snapshot; } - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public int[] ToArray() => _source.ToArray(); - /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() => _source.Dispose(); diff --git a/src/tests/ReactiveList.Tests/ViewConcurrencyFuzzTests.cs b/src/tests/ReactiveList.Tests/ViewConcurrencyFuzzTests.cs new file mode 100644 index 00000000..ba0a6a22 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewConcurrencyFuzzTests.cs @@ -0,0 +1,526 @@ +// 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. + +using System.Buffers; +using System.Security.Cryptography; + +namespace ReactiveList.Tests; + +/// Concurrency tests for view disposal, handler registration and retained pooled notification batches. +public class ViewConcurrencyFuzzTests +{ + /// A filtered over a reactive list. + private const string ReactiveKind = "reactive"; + + /// A over a reactive list. + private const string FilteredKind = "filtered"; + + /// A over a reactive list. + private const string DynamicFilteredKind = "dynamicFiltered"; + + /// A over a reactive list. + private const string SortedKind = "sorted"; + + /// A over a reactive list. + private const string GroupedKind = "grouped"; + + /// A over a reactive list. + private const string DynamicKind = "dynamic"; + + /// A over a quaternary list. + private const string ReactiveQuaternaryKind = "reactiveQuaternary"; + + /// A over a quaternary list. + private const string DynamicQuaternaryKind = "dynamicQuaternary"; + + /// A over a quaternary list. + private const string SecondaryKind = "secondary"; + + /// The number of storm rounds per kind. + private const int Rounds = 10; + + /// The number of mutations a storm applies. + private const int StormMutations = 300; + + /// The number of mutations applied after disposal. + private const int AfterDisposalMutations = 20; + + /// The number of threads that add and remove handlers. + private const int HandlerThreads = 3; + + /// The number of add and remove cycles per handler thread. + private const int HandlerCycles = 200; + + /// The coalescing window of asynchronous rounds, in milliseconds. + private const int ThrottleMilliseconds = 1; + + /// The delay of the marker scheduled to prove earlier scheduled work has run, in milliseconds. + private const int MarkerMilliseconds = 20; + + /// The timeout for waiting on background delivery, in milliseconds. + private const int WaitMilliseconds = 10_000; + + /// The smallest pooled array length the shared pool recycles. + private const int PoolBucketLength = 16; + + /// The number of items the pooled batch claims. + private const int PooledBatchCount = 2; + + /// The hour long window that keeps a view from draining on its own. + private static readonly TimeSpan NeverDrains = TimeSpan.FromHours(1); + + /// Disposing a view while another thread mutates the source stops notifications once in-flight ones finish. + /// The view kind. + /// A task representing the asynchronous test. + [Test] + [Arguments(ReactiveKind)] + [Arguments(FilteredKind)] + [Arguments(DynamicFilteredKind)] + [Arguments(SortedKind)] + [Arguments(GroupedKind)] + [Arguments(DynamicKind)] + [Arguments(ReactiveQuaternaryKind)] + [Arguments(DynamicQuaternaryKind)] + [Arguments(SecondaryKind)] + public async Task Dispose_DuringMutationStorm_StopsNotifyingAfterQuiescence(string kind) + { + for (var round = 0; round < Rounds; round++) + { + var immediate = (round & 1) == 0; + var scheduler = immediate ? Sequencer.Immediate : ReactiveListScheduler.Default; + var throttle = immediate ? TimeSpan.Zero : TimeSpan.FromMilliseconds(ThrottleMilliseconds); + using var harness = ViewHarness.Create(kind, scheduler, throttle); + var counter = new HandlerCounter(); + harness.Attach(counter); + + var storm = Task.Run(() => harness.Storm(StormMutations)); + await TestWaitHelpers.WaitUntilAsync(() => counter.Invocations > 0 || storm.IsCompleted, WaitMilliseconds, 1); + harness.View.Dispose(); + await storm; + + await QuiesceAsync(harness, counter, scheduler); + var settled = counter.Invocations; + harness.Storm(AfterDisposalMutations); + await QuiesceAsync(harness, counter, scheduler); + await Assert.That(counter.Invocations).IsEqualTo(settled); + } + } + + /// Disposing a view twice, including from two threads at once, is harmless and later handlers are never invoked. + /// The view kind. + /// A task representing the asynchronous test. + [Test] + [Arguments(ReactiveKind)] + [Arguments(FilteredKind)] + [Arguments(DynamicFilteredKind)] + [Arguments(SortedKind)] + [Arguments(GroupedKind)] + [Arguments(DynamicKind)] + [Arguments(ReactiveQuaternaryKind)] + [Arguments(DynamicQuaternaryKind)] + [Arguments(SecondaryKind)] + public async Task Dispose_CalledTwiceAndConcurrently_IsIdempotent(string kind) + { + for (var round = 0; round < Rounds; round++) + { + using var harness = ViewHarness.Create(kind, Sequencer.Immediate, TimeSpan.Zero); + var counter = new HandlerCounter(); + harness.Attach(counter); + harness.Storm(AfterDisposalMutations); + + var first = Task.Run(harness.View.Dispose); + var second = Task.Run(harness.View.Dispose); + await Task.WhenAll(first, second); + harness.View.Dispose(); + + await QuiesceAsync(harness, counter, Sequencer.Immediate); + var settled = counter.Invocations; + harness.Storm(AfterDisposalMutations); + await QuiesceAsync(harness, counter, Sequencer.Immediate); + await Assert.That(counter.Invocations).IsEqualTo(settled); + } + } + + /// Handlers added and removed from several threads while the source changes never throw, and removed handlers stay silent. + /// The view kind. + /// A task representing the asynchronous test. + [Test] + [Arguments(ReactiveKind)] + [Arguments(FilteredKind)] + [Arguments(DynamicFilteredKind)] + [Arguments(SortedKind)] + [Arguments(GroupedKind)] + [Arguments(DynamicKind)] + [Arguments(ReactiveQuaternaryKind)] + [Arguments(DynamicQuaternaryKind)] + [Arguments(SecondaryKind)] + public async Task Handlers_AddedAndRemovedConcurrently_DoNotThrowAndRemovedHandlersStaySilent(string kind) + { + var scheduler = ReactiveListScheduler.Default; + using var harness = ViewHarness.Create(kind, scheduler, TimeSpan.FromMilliseconds(ThrottleMilliseconds)); + var storm = Task.Run(() => harness.Storm(StormMutations)); + var workers = new Task[HandlerThreads]; + for (var i = 0; i < workers.Length; i++) + { + workers[i] = Task.Run(() => + { + for (var cycle = 0; cycle < HandlerCycles; cycle++) + { + var counter = new HandlerCounter(); + harness.Attach(counter); + harness.Detach(counter); + } + }); + } + + await Task.WhenAll(workers); + await storm; + + // Work the storm left queued must finish first, or it could legitimately reach the handler while it is attached. + HandlerCounter removed = new(); + await QuiesceAsync(harness, removed, scheduler); + harness.Attach(removed); + harness.Detach(removed); + HandlerCounter kept = new(); + harness.Attach(kept); + harness.AddValue(1); + await QuiesceAsync(harness, kept, scheduler); + await Assert.That(removed.Invocations).IsEqualTo(0); + } + + /// A pooled batch queued in a view that is disposed before it drains goes back to the pool. + /// A task representing the asynchronous test. + [Test] + public async Task QueuedPooledBatch_WhenReactiveViewDisposed_ReturnsToPool() + { + using var stream = new Signal>(); + var items = new int[PoolBucketLength]; + var batch = new PooledBatch(items, PooledBatchCount); + var view = new ReactiveView(stream, [], static _ => true, NeverDrains, ReactiveListScheduler.Default); + + stream.OnNext(new(CacheAction.BatchAdded, default, batch)); + view.Dispose(); + + var rented = ArrayPool.Shared.Rent(PoolBucketLength); + var wasReturned = ReferenceEquals(rented, items); + ArrayPool.Shared.Return(rented); + await Assert.That(wasReturned).IsTrue(); + } + + /// A pooled batch retained by a view change buffer that is disposed with work queued goes back to the pool. + /// A task representing the asynchronous test. + [Test] + public async Task QueuedPooledBatch_WhenViewChangeBufferDisposed_ReturnsToPool() + { + using var source = new ReactiveList(); + var buffer = new ViewChangeBuffer(source); + var items = new int[PoolBucketLength]; + var batch = new PooledBatch(items, PooledBatchCount); + + _ = buffer.Capture(new(CacheAction.BatchAdded, default, batch), source.Version + 1); + buffer.Dispose(); + + var rented = ArrayPool.Shared.Rent(PoolBucketLength); + var wasReturned = ReferenceEquals(rented, items); + ArrayPool.Shared.Return(rented); + await Assert.That(wasReturned).IsTrue(); + } + + /// Waits until everything the source and scheduler had pending has been delivered and no handler is running. + /// The harness whose source is flushed. + /// The handler counter whose in-flight count must reach zero. + /// The scheduler the view dispatches on. + /// A task that completes when the system is quiet. + private static async Task QuiesceAsync(ViewHarness harness, HandlerCounter counter, ISequencer scheduler) + { + var seen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var probe = harness.Stream.Subscribe(new SentinelObserver(seen)); + harness.AddValue(ViewFuzzSupport.Sentinel); + await TestWaitHelpers.WaitUntilAsync(() => seen.Task.IsCompleted, WaitMilliseconds, 1); + + // Earlier scheduled view work was due sooner than this marker, so it has run once the marker has. + var marker = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var scheduled = ReactiveListScheduler.Schedule(scheduler, TimeSpan.FromMilliseconds(MarkerMilliseconds), () => marker.TrySetResult(true)); + await TestWaitHelpers.WaitUntilAsync(() => marker.Task.IsCompleted && counter.InFlight == 0, WaitMilliseconds, 1); + } + + /// Counts handler invocations and how many are running. + private sealed class HandlerCounter + { + /// The number of invocations. + private int _invocations; + + /// The number of handlers running now. + private int _inFlight; + + /// Gets the number of invocations. + internal int Invocations => Volatile.Read(ref _invocations); + + /// Gets the number of handlers running now. + internal int InFlight => Volatile.Read(ref _inFlight); + + /// Records a property change. + /// The sender. + /// The arguments. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void OnPropertyChanged(object? sender, PropertyChangedEventArgs args) => Record(); + + /// Records a collection change. + /// The sender. + /// The arguments. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs args) => Record(); + + /// Counts one invocation. + private void Record() + { + _ = Interlocked.Increment(ref _inFlight); + _ = Interlocked.Increment(ref _invocations); + _ = Interlocked.Decrement(ref _inFlight); + } + } + + /// Completes when the sentinel item arrives on a source stream. + /// The completion source set when the sentinel arrives. + private sealed class SentinelObserver(TaskCompletionSource seen) : IObserver> + { + /// + public void OnCompleted() + { + } + + /// + public void OnError(Exception error) + { + } + + /// + public void OnNext(CacheNotify value) + { + if (value.Item == ViewFuzzSupport.Sentinel) + { + _ = seen.TrySetResult(true); + } + } + } + + /// Owns a source and a view over it and exposes the operations the tests need. + private sealed class ViewHarness : IDisposable + { + /// The upper bound of generated operation numbers. + private const int MaxNumber = 30; + + /// The upper bound of generated item values. + private const int MaxValue = 12; + + /// The longest item array a generated operation carries. + private const int MaxItems = 6; + + /// The number of distinct operation kinds. + private const int OperationKinds = 15; + + /// The number of groups or index buckets items fall into. + private const int Buckets = 3; + + /// The disposables released with the harness, last in first out. + private readonly List _owned; + + /// Applies one mutation to the source. + private readonly Action _mutate; + + /// Adds one value to the source. + private readonly Action _add; + + /// Initializes a new instance of the class. + /// The disposables released with the harness. + /// The view under test. + /// The source notification stream. + /// Applies one mutation to the source. + /// Adds one value to the source. + private ViewHarness( + List owned, + IDisposable view, + IObservable> stream, + Action mutate, + Action add) + { + _owned = owned; + View = view; + Stream = stream; + _mutate = mutate; + _add = add; + } + + /// Gets the view under test. + internal IDisposable View { get; } + + /// Gets the source notification stream. + internal IObservable> Stream { get; } + + /// + public void Dispose() + { + for (var i = _owned.Count - 1; i >= 0; i--) + { + _owned[i].Dispose(); + } + } + + /// Creates a harness for a view kind. + /// The view kind. + /// The scheduler the view dispatches on. + /// The coalescing window. + /// The harness. + internal static ViewHarness Create(string kind, ISequencer scheduler, TimeSpan throttle) => + kind switch + { + ReactiveQuaternaryKind or DynamicQuaternaryKind or SecondaryKind => CreateQuaternary(kind, scheduler, throttle), + _ => CreateReactive(kind, scheduler, throttle), + }; + + /// Attaches a counter to every notification event the view exposes. + /// The counter. + internal void Attach(HandlerCounter counter) + { + ((INotifyPropertyChanged)View).PropertyChanged += counter.OnPropertyChanged; + if (View is INotifyCollectionChanged collection) + { + collection.CollectionChanged += counter.OnCollectionChanged; + } + } + + /// Detaches a counter from every notification event the view exposes. + /// The counter. + internal void Detach(HandlerCounter counter) + { + ((INotifyPropertyChanged)View).PropertyChanged -= counter.OnPropertyChanged; + if (View is INotifyCollectionChanged collection) + { + collection.CollectionChanged -= counter.OnCollectionChanged; + } + } + + /// Adds a value to the source. + /// The value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void AddValue(int value) => _add(value); + + /// Applies random mutations to the source. + /// The number of mutations. + internal void Storm(int count) + { + for (var i = 0; i < count; i++) + { + var items = new int[RandomNumberGenerator.GetInt32(MaxItems)]; + for (var item = 0; item < items.Length; item++) + { + items[item] = RandomNumberGenerator.GetInt32(MaxValue); + } + + _mutate(new( + (ViewFuzzKind)RandomNumberGenerator.GetInt32(OperationKinds), + RandomNumberGenerator.GetInt32(MaxNumber), + RandomNumberGenerator.GetInt32(MaxNumber), + items)); + } + } + + /// Creates a harness over a reactive list. + /// The view kind. + /// The scheduler the view dispatches on. + /// The coalescing window. + /// The harness. + private static ViewHarness CreateReactive(string kind, ISequencer scheduler, TimeSpan throttle) + { + var list = new ReactiveList(); + List owned = [list]; + IDisposable view; + switch (kind) + { + case FilteredKind: + { + view = new FilteredReactiveView(list, ViewFuzzSupport.Passes, scheduler, throttle); + break; + } + + case DynamicFilteredKind: + { + var filters = new BehaviorSignal>(ViewFuzzSupport.Passes); + owned.Add(filters); + view = new DynamicFilteredReactiveView(list, filters, scheduler, throttle); + break; + } + + case SortedKind: + { + view = new SortedReactiveView(list, Comparer.Default, scheduler, throttle); + break; + } + + case GroupedKind: + { + view = new GroupedReactiveView(list, static item => item % Buckets, scheduler, throttle); + break; + } + + case DynamicKind: + { + var filters = new BehaviorSignal>(ViewFuzzSupport.Passes); + owned.Add(filters); + view = new DynamicReactiveView(list, filters, throttle, scheduler); + break; + } + + default: + { + view = new ReactiveView(list, ViewFuzzSupport.Passes, throttle, scheduler); + break; + } + } + + owned.Add(view); + return new(owned, view, list.Stream, op => ViewFuzzSupport.Apply(list, op), list.Add); + } + + /// Creates a harness over a quaternary list. + /// The view kind. + /// The scheduler the view dispatches on. + /// The coalescing window. + /// The harness. + private static ViewHarness CreateQuaternary(string kind, ISequencer scheduler, TimeSpan throttle) + { + var list = new QuaternaryList(); + list.AddIndex("bucket", static item => item % Buckets); + List owned = [list]; + IDisposable view; + switch (kind) + { + case DynamicQuaternaryKind: + { + var filters = new BehaviorSignal>(ViewFuzzSupport.Passes); + owned.Add(filters); + view = new DynamicReactiveView(list, filters, throttle, scheduler); + break; + } + + case SecondaryKind: + { + var keys = new BehaviorSignal([1]); + owned.Add(keys); + view = new DynamicSecondaryIndexReactiveView(list, "bucket", keys, scheduler, throttle); + break; + } + + default: + { + view = new ReactiveView(list, ViewFuzzSupport.Passes, throttle, scheduler); + break; + } + } + + owned.Add(view); + return new(owned, view, list.Stream, op => ViewFuzzSupport.Apply(list, op), list.Add); + } + } +} diff --git a/src/tests/ReactiveList.Tests/ViewConstructorFailureTests.cs b/src/tests/ReactiveList.Tests/ViewConstructorFailureTests.cs new file mode 100644 index 00000000..49e5c2cc --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewConstructorFailureTests.cs @@ -0,0 +1,80 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies a view whose constructor throws does not leave a live subscription on its source. +public sealed class ViewConstructorFailureTests +{ + /// The items the source holds before a view is built. + private static readonly int[] Existing = [1, 2, 3]; + + /// The view kinds checked. + public enum ThrowingKind + { + /// A filtered engine whose filter throws. + Filtered = 0, + + /// A sorted engine whose comparer throws. + Sorted = 1, + + /// A grouped engine whose key selector throws. + Grouped = 2, + + /// A view over a source whose filter throws. + SourceView = 3, + } + + /// A constructor that throws while reading the existing items releases its subscription. + /// The view kind. + /// A task representing the asynchronous test. + [Test] + [Arguments(ThrowingKind.Filtered)] + [Arguments(ThrowingKind.Sorted)] + [Arguments(ThrowingKind.Grouped)] + [Arguments(ThrowingKind.SourceView)] + public async Task Constructor_ThrowsOnExistingItem_ReleasesTheSubscription(ThrowingKind kind) + { + using var inner = new QuaternaryList(); + inner.AddRange(Existing); + using var source = new VersionedCountingSource(inner); + + await Assert.That(() => Construct(kind, source)).Throws(); + + await Assert.That(source.ActiveSubscriptions).IsEqualTo(0); + } + + /// Builds a view whose callback throws for an existing item. + /// The view kind. + /// The source. + private static void Construct(ThrowingKind kind, VersionedCountingSource source) + { + switch (kind) + { + case ThrowingKind.Filtered: + { + _ = new FilteredViewEngine(source, static _ => throw new InvalidOperationException()); + break; + } + + case ThrowingKind.Sorted: + { + _ = new SortedViewEngine(source, Comparer.Create(static (_, _) => throw new InvalidOperationException())); + break; + } + + case ThrowingKind.Grouped: + { + _ = new GroupedViewEngine(source, static _ => throw new InvalidOperationException()); + break; + } + + default: + { + _ = new ReactiveView(source, static _ => throw new InvalidOperationException(), TimeSpan.Zero, Sequencer.Immediate); + break; + } + } + } +} diff --git a/src/tests/ReactiveList.Tests/ViewCoverageTests.cs b/src/tests/ReactiveList.Tests/ViewCoverageTests.cs index 0891e774..29e58f84 100644 --- a/src/tests/ReactiveList.Tests/ViewCoverageTests.cs +++ b/src/tests/ReactiveList.Tests/ViewCoverageTests.cs @@ -59,11 +59,11 @@ public async Task FilteredReactiveView_UpdateTransitions_ShouldAddRemoveReplaceA list.Update(TestConstants.TestValueThree, TestConstants.TestValueSix); await TestWaitHelpers.WaitUntilAsync(() => view.Items.Count == TestConstants.TestValueTwo); - await Assert.That(view.Items).IsEquivalentTo([TestConstants.TestValueFour, TestConstants.TestValueSix], CollectionOrdering.Matching); + await Assert.That(view.Items).IsEquivalentTo([TestConstants.TestValueSix, TestConstants.TestValueFour], CollectionOrdering.Matching); list.Update(TestConstants.TestValueFour, TestConstants.TestValueEight); - await TestWaitHelpers.WaitUntilAsync(() => view.Items.Count == TestConstants.TestValueTwo && view.Items[0] == TestConstants.TestValueEight); - await Assert.That(view.Items).IsEquivalentTo([TestConstants.TestValueEight, TestConstants.TestValueSix], CollectionOrdering.Matching); + await TestWaitHelpers.WaitUntilAsync(() => view.Items.Count == TestConstants.TestValueTwo && view.Items[1] == TestConstants.TestValueEight); + await Assert.That(view.Items).IsEquivalentTo([TestConstants.TestValueSix, TestConstants.TestValueEight], CollectionOrdering.Matching); list.Move(TestConstants.TestValueTwo, 0); await TestWaitHelpers.WaitUntilAsync(() => view.Items.Count == TestConstants.TestValueTwo); @@ -258,7 +258,7 @@ public async Task DynamicFilteredReactiveView_FilterAndSourceChanges_ShouldRebui list.Update(1, TestConstants.TestValueSix); await TestWaitHelpers.WaitUntilAsync(() => view.Items.Count == TestConstants.TestValueTwo); - await Assert.That(view.Items).IsEquivalentTo([TestConstants.TestValueFour, TestConstants.TestValueSix], CollectionOrdering.Matching); + await Assert.That(view.Items).IsEquivalentTo([TestConstants.TestValueSix, TestConstants.TestValueFour], CollectionOrdering.Matching); view.Refresh(); await Assert.That(view.Items).IsEquivalentTo([TestConstants.TestValueSix, TestConstants.TestValueFour], CollectionOrdering.Matching); @@ -381,6 +381,28 @@ public async Task DynamicReactiveView_BufferedUpdateAndAdd_ShouldNotDuplicateIte await Assert.That(view.Items).IsEquivalentTo([TestConstants.TestValueEight], CollectionOrdering.Matching); } + /// Immutable sources bypass refreshes but still apply replacements. + /// Whether the source declares its items immutable. + /// A task representing the asynchronous test. + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task ReactiveView_ImmutableSourceSkipsRefreshButAppliesUpdate(bool immutable) + { + using var source = new ReactiveSourceHarness([1]) { Options = new() { ItemsAreImmutable = immutable } }; + var include = false; + using var view = source.CreateView(_ => include, Sequencer.Immediate, 0); + + include = true; + source.Emit(new(CacheAction.Refreshed, 1)); + await Assert.That(view.Items.Count).IsEqualTo(immutable ? 0 : 1); + + source.RemoveItem(1); + source.AddItem(TestConstants.TestValueTwo); + source.Emit(new(CacheAction.Updated, TestConstants.TestValueTwo, Previous: 1)); + await Assert.That(view.Items).IsEquivalentTo([TestConstants.TestValueTwo]); + } + /// Dynamic reactive views should use the default include-all filter when null filters are emitted. /// A representing the asynchronous unit test. [Test] @@ -1077,7 +1099,7 @@ public IDisposable Subscribe(IObserver observer) /// Provides ReactiveSourceHarness. /// The T type. - private sealed class ReactiveSourceHarness : IReactiveSource + private sealed class ReactiveSourceHarness : IReactiveSource, IReactiveSourceWithOptions where T : notnull { /// The mutable source items exposed by this harness. @@ -1102,6 +1124,9 @@ private sealed class ReactiveSourceHarness : IReactiveSource /// Gets IsReadOnly. public bool IsReadOnly => false; + /// + public ReactiveSourceOptions Options { get; init; } = new(); + /// Gets Stream. public IObservable> Stream => _stream.AsObservable(); diff --git a/src/tests/ReactiveList.Tests/ViewDispatcherLifecycleTests.cs b/src/tests/ReactiveList.Tests/ViewDispatcherLifecycleTests.cs new file mode 100644 index 00000000..7199048a --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewDispatcherLifecycleTests.cs @@ -0,0 +1,54 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks how and behave around disposal. +public class ViewDispatcherLifecycleTests +{ + /// An immediate dispatcher with no throttle drains on the calling thread. + /// A task representing the asynchronous test. + [Test] + public async Task Notify_ImmediateWithoutThrottle_DrainsAtOnce() + { + StrongBox drains = new(); + ViewDispatcher dispatcher = new(ReactiveListScheduler.Immediate, TimeSpan.Zero, () => drains.Value++); + + dispatcher.Notify(); + + await Assert.That(drains.Value).IsEqualTo(1); + } + + /// A disposed dispatcher drains nothing, whether the window elapses or a scheduled run starts. + /// A task representing the asynchronous test. + [Test] + public async Task Disposed_WindowElapsedAndRun_DrainNothing() + { + StrongBox drains = new(); + ViewDispatcher dispatcher = new(ReactiveListScheduler.Immediate, TimeSpan.Zero, () => drains.Value++); + dispatcher.Dispose(); + + dispatcher.OnWindowElapsed(); + dispatcher.Run(); + dispatcher.Notify(); + + await Assert.That(drains.Value).IsEqualTo(0); + } + + /// A closed gate reports it, and entering a closed gate fails. + /// A task representing the asynchronous test. + [Test] + public async Task DisposalGate_Close_ReportsClosedAndRefusesEntry() + { + DisposalGate gate = new(); + var openEntered = gate.TryEnter(); + gate.Exit(); + + gate.Close(); + + await Assert.That(openEntered).IsTrue(); + await Assert.That(gate.IsClosed).IsTrue(); + await Assert.That(gate.TryEnter()).IsFalse(); + } +} diff --git a/src/tests/ReactiveList.Tests/ViewDispatcherTests.cs b/src/tests/ReactiveList.Tests/ViewDispatcherTests.cs new file mode 100644 index 00000000..f2723896 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewDispatcherTests.cs @@ -0,0 +1,102 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies the coalescing dispatcher never loses a wake-up when scheduling races with a drain. +public sealed class ViewDispatcherTests +{ + /// The drains expected from two notifications that race. + private const int TwoDrains = 2; + + /// A drain that ran before its schedule handle was recorded must not cancel the drain scheduled after it. + /// A task representing the asynchronous test. + [Test] + public async Task Notify_DrainRunsBeforeHandleIsTracked_LaterDrainStillRuns() + { + var sequencer = new ControllableSequencer(); + var drains = 0; + var dispatcher = new ViewDispatcher(sequencer, TimeSpan.Zero, () => drains++); + + // The first request runs inline, then a second producer notifies before the first producer records its handle. + sequencer.RunInline = static ordinal => ordinal == 1; + sequencer.Accepted = ordinal => + { + if (ordinal == 1) + { + dispatcher.Notify(); + } + }; + + dispatcher.Notify(); + sequencer.RunAll(); + + await Assert.That(drains).IsEqualTo(TwoDrains); + + // The dispatcher must still accept work afterwards. + sequencer.RunInline = null; + sequencer.Accepted = null; + dispatcher.Notify(); + sequencer.RunAll(); + + await Assert.That(drains).IsEqualTo(TwoDrains + 1); + } + + /// Disposing cancels a drain that has not run. + /// A task representing the asynchronous test. + [Test] + public async Task Dispose_PendingDrain_DoesNotRun() + { + var sequencer = new ControllableSequencer(); + var drains = 0; + var dispatcher = new ViewDispatcher(sequencer, TimeSpan.Zero, () => drains++); + + dispatcher.Notify(); + dispatcher.Dispose(); + sequencer.RunAll(); + + await Assert.That(drains).IsEqualTo(0); + } + + /// Verifies an immediate scheduler without a coalescing window drains on the calling thread. + /// A task representing the asynchronous test. + [Test] + public async Task Notify_ImmediateSchedulerWithoutWindow_DrainsOnTheCallingThread() + { + var drains = 0; + var dispatcher = new ViewDispatcher(ReactiveListScheduler.Immediate, TimeSpan.Zero, () => drains++); + + dispatcher.Notify(); + + await Assert.That(drains).IsEqualTo(1); + } + + /// Verifies an elapsed coalescing window schedules nothing once the dispatcher is disposed. + /// A task representing the asynchronous test. + [Test] + public async Task OnWindowElapsed_Disposed_SchedulesNothing() + { + var sequencer = new ControllableSequencer(); + var dispatcher = new ViewDispatcher(sequencer, TimeSpan.Zero, static () => { }); + dispatcher.Dispose(); + + dispatcher.OnWindowElapsed(); + + await Assert.That(sequencer.Requests).IsEqualTo(0); + } + + /// Verifies a scheduled drain that runs after disposal does not drain. + /// A task representing the asynchronous test. + [Test] + public async Task Run_Disposed_DoesNotDrain() + { + var drains = 0; + var dispatcher = new ViewDispatcher(new ControllableSequencer(), TimeSpan.Zero, () => drains++); + dispatcher.Dispose(); + + dispatcher.Run(); + + await Assert.That(drains).IsEqualTo(0); + } +} diff --git a/src/tests/ReactiveList.Tests/ViewDisposeTests.cs b/src/tests/ReactiveList.Tests/ViewDisposeTests.cs new file mode 100644 index 00000000..b1335f32 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewDisposeTests.cs @@ -0,0 +1,510 @@ +// 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. + +namespace ReactiveList.Tests; + +/// +/// Proves a view hands back the pooled batches it still holds when it is disposed, and that a view stops changing once +/// disposal has returned even when a drain is running on another thread. +/// +public sealed class ViewDisposeTests +{ + /// The item whose filtering blocks until it is released. + private const string BlockingItem = "blocking"; + + /// The number of items in each pooled batch. + private const int BatchLength = 8; + + /// The length of an array the shared pool accepts and clears when it is returned. + private const int PooledLength = 16; + + /// The longest a blocked filter waits to be released, in seconds. + private const int DrainWaitSeconds = 10; + + /// The number of dispose-versus-delivery races run per view kind. + private const int RaceRounds = 200; + + /// The number of batches the producer sends in each race. + private const int RaceBatches = 20; + + /// A batch of items added in one operation. + private static readonly int[] BatchOfThree = [1, 2, 3]; + + /// A coalescing window long enough that a queued notification is never applied during a test. + private static readonly TimeSpan NeverDrains = TimeSpan.FromHours(1); + + /// The view kinds whose disposal is checked. + public enum EngineKind + { + /// A filtered view engine. + Filtered = 0, + + /// A sorted view engine. + Sorted = 1, + + /// A grouped view engine. + Grouped = 2, + + /// A view over a source. + SourceView = 3, + + /// A dynamic view over a source. + DynamicView = 4, + + /// A view over a bare notification stream. + StreamView = 5, + } + + /// Verifies every pooled batch a view still holds is returned when the view is disposed. + /// The view kind. + /// The batch action that is queued. + /// A task representing the asynchronous test. + [Test] + [Arguments(EngineKind.Filtered, CacheAction.BatchAdded)] + [Arguments(EngineKind.Filtered, CacheAction.BatchRemoved)] + [Arguments(EngineKind.Filtered, CacheAction.Cleared)] + [Arguments(EngineKind.Sorted, CacheAction.BatchAdded)] + [Arguments(EngineKind.Sorted, CacheAction.BatchRemoved)] + [Arguments(EngineKind.Grouped, CacheAction.BatchAdded)] + [Arguments(EngineKind.Grouped, CacheAction.BatchRemoved)] + [Arguments(EngineKind.SourceView, CacheAction.BatchAdded)] + [Arguments(EngineKind.SourceView, CacheAction.BatchRemoved)] + [Arguments(EngineKind.DynamicView, CacheAction.BatchAdded)] + [Arguments(EngineKind.DynamicView, CacheAction.BatchRemoved)] + [Arguments(EngineKind.StreamView, CacheAction.BatchAdded)] + [Arguments(EngineKind.StreamView, CacheAction.BatchOperation)] + public async Task Dispose_ReturnsQueuedPooledBatches(EngineKind kind, CacheAction action) + { + using var source = new FakeSource(); + using var filters = new BehaviorSignal>(static _ => true); + var view = Create(kind, source, filters, NeverDrains); + + var rented = ArrayPool.Shared.Rent(BatchLength); + for (var i = 0; i < BatchLength; i++) + { + rented[i] = $"item{i}"; + } + + var batch = new PooledBatch(rented, BatchLength); + source.Emit(new(action, default, batch)); + await Assert.That(rented[0]).IsNotNull(); + + view.Dispose(); + + await Assert.That(rented[0]).IsNull(); + } + + /// Verifies a filtered engine makes no change after disposal returns, even when a drain was running on another thread. + /// A task representing the asynchronous test. + [Test] + public async Task FilteredEngineDispose_WaitsForARunningDrain() + { + using var source = new FakeSource(); + using var inFilter = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var engine = new FilteredViewEngine( + source, + item => + { + if (item == BlockingItem) + { + inFilter.Set(); + _ = release.Wait(TimeSpan.FromSeconds(DrainWaitSeconds)); + } + + return true; + }); + engine.Start(TimeSpan.Zero, Sequencer.Immediate); + var changes = 0; + engine.Filtered.CollectionChanged += (_, _) => Interlocked.Increment(ref changes); + + var emitter = Task.Run(() => source.AddItem(BlockingItem)); + await TestWaitHelpers.WaitUntilAsync(() => inFilter.IsSet); + + // Disposal must return while the drain is still blocked in the filter, and must stop that drain from changing the view. + await Task.Run(engine.Dispose).WaitAsync(TimeSpan.FromSeconds(DrainWaitSeconds)); + var atDispose = Volatile.Read(ref changes); + var countAtDispose = engine.Filtered.Count; + + release.Set(); + await emitter; + await Assert.That(Volatile.Read(ref changes)).IsEqualTo(atDispose); + await Assert.That(engine.Filtered.Count).IsEqualTo(countAtDispose); + } + + /// Verifies a view over a source makes no change after disposal returns, even when a drain was running on another thread. + /// A task representing the asynchronous test. + [Test] + public async Task SourceViewDispose_WaitsForARunningDrain() + { + using var source = new FakeSource(); + using var inFilter = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var throttle = TimeSpan.Zero; + var view = new ReactiveView( + source, + item => + { + if (item == BlockingItem) + { + inFilter.Set(); + _ = release.Wait(TimeSpan.FromSeconds(DrainWaitSeconds)); + } + + return true; + }, + throttle, + Sequencer.Immediate); + var changes = 0; + ((INotifyCollectionChanged)view.Items).CollectionChanged += (_, _) => Interlocked.Increment(ref changes); + + var emitter = Task.Run(() => source.AddItem(BlockingItem)); + await TestWaitHelpers.WaitUntilAsync(() => inFilter.IsSet); + + // Disposal must return while the drain is still blocked in the filter, and must stop that drain from changing the view. + await Task.Run(view.Dispose).WaitAsync(TimeSpan.FromSeconds(DrainWaitSeconds)); + var atDispose = Volatile.Read(ref changes); + var countAtDispose = view.Items.Count; + + release.Set(); + await emitter; + await Assert.That(Volatile.Read(ref changes)).IsEqualTo(atDispose); + await Assert.That(view.Items.Count).IsEqualTo(countAtDispose); + } + + /// Verifies disposing from inside a change handler returns and stops the rest of the batch from raising. + /// The view kind. + /// A task representing the asynchronous test. + [Test] + [Arguments(EngineKind.Filtered)] + [Arguments(EngineKind.Sorted)] + [Arguments(EngineKind.SourceView)] + public async Task Dispose_FromInsideAHandler_StopsTheRestOfTheBatch(EngineKind kind) + { + using var list = new ReactiveList(); + var events = 0; + IDisposable? view = null; + NotifyCollectionChangedEventHandler onChanged = (_, _) => + { + if (Interlocked.Increment(ref events) == 1) + { + view!.Dispose(); + } + }; + + switch (kind) + { + case EngineKind.Filtered: + { + var filtered = new FilteredReactiveView(list, static _ => true, Sequencer.Immediate, TimeSpan.Zero); + ((INotifyCollectionChanged)filtered.Items).CollectionChanged += onChanged; + view = filtered; + break; + } + + case EngineKind.Sorted: + { + var sorted = new SortedReactiveView(list, Comparer.Default, Sequencer.Immediate, TimeSpan.Zero); + ((INotifyCollectionChanged)sorted.Items).CollectionChanged += onChanged; + view = sorted; + break; + } + + default: + { + var sourceView = new ReactiveView(list, static _ => true, TimeSpan.Zero, Sequencer.Immediate); + ((INotifyCollectionChanged)sourceView.Items).CollectionChanged += onChanged; + view = sourceView; + break; + } + } + + await Task.Run(() => list.AddRange(BatchOfThree)).WaitAsync(TimeSpan.FromSeconds(DrainWaitSeconds)); + list.Add(BatchLength); + + await Assert.That(Volatile.Read(ref events)).IsEqualTo(1); + } + + /// Verifies no pooled batch is left unreturned when disposal races with notifications being delivered. + /// The view kind. + /// A task representing the asynchronous test. + [Test] + [Arguments(EngineKind.Filtered)] + [Arguments(EngineKind.Grouped)] + [Arguments(EngineKind.SourceView)] + [Arguments(EngineKind.StreamView)] + public async Task Dispose_RacingDelivery_ReturnsEveryBatch(EngineKind kind) + { + for (var round = 0; round < RaceRounds; round++) + { + using var source = new FakeSource(); + using var filters = new BehaviorSignal>(static _ => true); + var view = Create(kind, source, filters, (round & 1) == 0 ? NeverDrains : TimeSpan.Zero); + var rented = new string[]?[RaceBatches]; + using var start = new ManualResetEventSlim(); + + var producer = Task.Run(() => + { + start.Wait(); + for (var i = 0; i < RaceBatches; i++) + { + // A fresh array of a pooled size, so a returned and re-rented array cannot be mistaken for an unreturned one. + var array = new string[PooledLength]; + for (var j = 0; j < BatchLength; j++) + { + array[j] = $"race{j}"; + } + + rented[i] = array; + source.Emit(new(CacheAction.BatchAdded, default, new PooledBatch(array, BatchLength))); + } + }); + var disposer = Task.Run(() => + { + start.Wait(); + source.MarkDisposing(); + view.Dispose(); + }); + + start.Set(); + await Task.WhenAll(producer, disposer); + + // Delivery after disposal is dropped by the unsubscribed view, so the producer's own batches are the ones + // checked: each was either applied and returned, or never delivered. Delivered ones must all be returned. + await Assert.That(source.DeliveredAndUnreturned(rented)).IsEqualTo(0); + } + } + + /// Creates a view of a kind over a source. + /// The view kind. + /// The source. + /// The filter signal for dynamic views. + /// The coalescing window. + /// The view. + private static IDisposable Create(EngineKind kind, FakeSource source, BehaviorSignal> filters, TimeSpan throttle) + { + switch (kind) + { + case EngineKind.Filtered: + { + var engine = new FilteredViewEngine(source, static _ => true); + engine.Start(throttle, Sequencer.Immediate); + return engine; + } + + case EngineKind.Sorted: + { + var engine = new SortedViewEngine(source, Comparer.Default); + engine.Start(throttle, Sequencer.Immediate); + return engine; + } + + case EngineKind.Grouped: + { + var engine = new GroupedViewEngine(source, static item => item.Length); + engine.Start(throttle, Sequencer.Immediate); + return engine; + } + + case EngineKind.SourceView: + { + return new ReactiveView(source, static _ => true, throttle, Sequencer.Immediate); + } + + case EngineKind.DynamicView: + { + return new DynamicReactiveView(source, filters, throttle, Sequencer.Immediate); + } + + default: + { + return new ReactiveView(source.Stream, [], static _ => true, throttle, Sequencer.Immediate); + } + } + } + + /// A source that sends the notifications a test gives it. + private sealed class FakeSource : IReactiveSource + { + /// The source items. + private readonly List _items = []; + + /// The notification stream. + private readonly Signal> _stream = new(); + + /// The arrays carried by notifications that reached a subscriber. + private readonly HashSet _delivered = []; + + /// Non-zero once the test started disposing the view. + private int _disposing; + + /// The number of notifications sent. + private long _version; + + /// Non-zero once disposed. + private int _disposed; + + /// + public event NotifyCollectionChangedEventHandler? CollectionChanged + { + add + { + } + + remove + { + } + } + + /// + public int Count + { + get + { + lock (_items) + { + return _items.Count; + } + } + } + + /// + public bool IsReadOnly => false; + + /// + public bool IsDisposed => Volatile.Read(ref _disposed) != 0; + + /// + public long Version => Interlocked.Read(ref _version); + + /// + public IObservable> Stream => new Tap(_stream, _delivered, IsDisposing); + + /// Notes that the test is about to dispose the view. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void MarkDisposing() => Volatile.Write(ref _disposing, 1); + + /// Adds an item and announces it. + /// The item. + public void AddItem(string item) + { + lock (_items) + { + _items.Add(item); + } + + Emit(new(CacheAction.Added, item)); + } + + /// Announces a notification under a new version. + /// The notification. + public void Emit(CacheNotify notification) + { + _ = Interlocked.Increment(ref _version); + _stream.OnNext(notification); + } + + /// Counts the arrays that reached a subscriber and still hold their items. + /// The arrays rented by the producer, some of which may be unset. + /// The number of arrays that were delivered to a subscriber and not returned. + public int DeliveredAndUnreturned(string[]?[] arrays) + { + var count = 0; + for (var i = 0; i < arrays.Length; i++) + { + if (arrays[i] is { } array && array[0] is not null && WasDelivered(array)) + { + count++; + } + } + + return count; + } + + /// + public string[] ToArray() + { + lock (_items) + { + return [.. _items]; + } + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IEnumerator GetEnumerator() => ((IEnumerable)ToArray()).GetEnumerator(); + + /// + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + _stream.Dispose(); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// Checks whether a subscriber was handed an array. + /// The array. + /// when a subscriber received it. + private bool WasDelivered(string[] array) + { + lock (_delivered) + { + return _delivered.Contains(array); + } + } + + /// Checks whether the test has started disposing the view. + /// once disposal has started. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool IsDisposing() => Volatile.Read(ref _disposing) != 0; + + /// Records the arrays whose delivery finished before disposal started. + /// The notification stream. + /// Receives the arrays that were handed over completely. + /// Reports whether disposal has started. + private sealed class Tap(IObservable> stream, HashSet delivered, Func disposing) : IObservable> + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IDisposable Subscribe(IObserver> observer) => stream.Subscribe(new Relay(observer, delivered, disposing)); + } + + /// Passes a notification on and notes its array when the hand over finished before disposal started. + /// The subscriber. + /// Receives the arrays that were handed over completely. + /// Reports whether disposal has started. + private sealed class Relay(IObserver> inner, HashSet delivered, Func disposing) : IObserver> + { + /// + public void OnNext(CacheNotify value) + { + inner.OnNext(value); + + // Read after the hand over: a flag that is still clear means disposal had not started when it finished. + if (value.Batch is { } batch && !disposing()) + { + lock (delivered) + { + _ = delivered.Add(batch.Items); + } + } + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnError(Exception error) => inner.OnError(error); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnCompleted() => inner.OnCompleted(); + } + } +} diff --git a/src/tests/ReactiveList.Tests/ViewEngineRefreshTests.cs b/src/tests/ReactiveList.Tests/ViewEngineRefreshTests.cs new file mode 100644 index 00000000..8c531668 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewEngineRefreshTests.cs @@ -0,0 +1,107 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Checks how the sorted and filtered view engines react to refreshes and to filter changes that flip many items. +public class ViewEngineRefreshTests +{ + /// A rank that sorts last among the test items. + private const int LastRank = 5; + + /// The rank of the middle test item. + private const int MiddleRank = 2; + + /// The rank of the final test item. + private const int HighestRank = 3; + + /// A refresh of an item the sorted engine does not hold inserts it in order. + /// A task representing the asynchronous test. + [Test] + public async Task Sorted_RefreshOfUnknownItem_InsertsItInOrder() + { + using ReactiveList source = [new(1), new(HighestRank)]; + using SortedViewEngine engine = new(source, new RankComparer()); + + engine.ItemRefreshed(0, new(MiddleRank)); + + await Assert.That(engine.Sorted.Count).IsEqualTo(HighestRank); + await Assert.That(engine.Sorted[1].Rank).IsEqualTo(MiddleRank); + } + + /// A refresh leaves an item in place while it stays in order and moves it when it does not. + /// A task representing the asynchronous test. + [Test] + public async Task Sorted_RefreshOfKnownItem_StaysOrMovesWithItsRank() + { + Ranked first = new(1); + using ReactiveList source = [first, new(MiddleRank), new(HighestRank)]; + using SortedViewEngine engine = new(source, new RankComparer()); + + engine.ItemRefreshed(0, first); + var stayed = ReferenceEquals(engine.Sorted[0], first); + first.Rank = LastRank; + engine.ItemRefreshed(0, first); + + await Assert.That(stayed).IsTrue(); + await Assert.That(ReferenceEquals(engine.Sorted[MiddleRank], first)).IsTrue(); + } + + /// Removing an item the sorted engine does not hold changes nothing. + /// A task representing the asynchronous test. + [Test] + public async Task Sorted_RemovalOfUnknownItem_ChangesNothing() + { + using ReactiveList source = [new(1)]; + using SortedViewEngine engine = new(source, new RankComparer()); + + engine.ItemRemoved(0, new(MiddleRank)); + + await Assert.That(engine.Sorted.Count).IsEqualTo(1); + } + + /// A refresh of an included item keeps it in the filtered projection. + /// A task representing the asynchronous test. + [Test] + public async Task Filtered_RefreshOfIncludedItem_KeepsIt() + { + using ReactiveList source = [1]; + using FilteredViewEngine engine = new(source, static item => item > 0); + + engine.ItemRefreshed(0, 1); + + await Assert.That(engine.Filtered.Count).IsEqualTo(1); + } + + /// A filter change that flips more items than the reset limit replaces the projection in one step. + /// A task representing the asynchronous test. + [Test] + public async Task Filtered_FilterFlipsMoreThanTheResetLimit_ReplacesTheProjection() + { + using ReactiveList source = [1, MiddleRank, HighestRank]; + using FilteredViewEngine engine = new(source, static item => item > 0) { Filtered = { ResetLimit = 0 } }; + engine.Start(TimeSpan.Zero, ReactiveListScheduler.Immediate); + + engine.SetFilter(static item => item > 1); + engine.Refresh(); + + await Assert.That(engine.Filtered.Count).IsEqualTo(MiddleRank); + } + + /// Orders items by their rank. + private sealed class RankComparer : IComparer + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Compare(Ranked? x, Ranked? y) => x!.Rank.CompareTo(y!.Rank); + } + + /// An item whose rank can change. + /// The rank the item sorts by. + private sealed class Ranked(int rank) + { + /// Gets or sets the rank the item sorts by. + public int Rank { get; set; } = rank; + } +} diff --git a/src/tests/ReactiveList.Tests/ViewFacadeAccessorTests.cs b/src/tests/ReactiveList.Tests/ViewFacadeAccessorTests.cs new file mode 100644 index 00000000..a47dae60 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewFacadeAccessorTests.cs @@ -0,0 +1,227 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies the batch reset limit and change event accessors every view type exposes. +public sealed class ViewFacadeAccessorTests +{ + /// The name of the secondary index the indexed views read. + private const string IndexName = "parity"; + + /// A limit assigned and read back. + private const int AssignedLimit = 5; + + /// The divisor of the secondary index. + private const int IndexKeyCount = 2; + + /// Which view type is built. + public enum FacadeKind + { + /// A view with a fixed filter. + Filtered = 0, + + /// A view with a sort order. + Sorted = 1, + + /// A grouped view. + Grouped = 2, + + /// A view over a list with a changing filter. + Dynamic = 3, + + /// A view whose filter predicate changes. + DynamicFiltered = 4, + + /// A view of one secondary index key of a dictionary. + SecondaryIndex = 5, + + /// A view of changing secondary index keys of a list. + DynamicSecondaryIndex = 6, + + /// A view of changing secondary index keys of a dictionary. + DynamicSecondaryIndexDictionary = 7, + + /// A view over a source. + SourceView = 8, + } + + /// Verifies the limit defaults to unlimited, accepts a value and rejects a negative one. + /// The view kind. + /// A task representing the asynchronous test. + [Test] + [Arguments(FacadeKind.Filtered)] + [Arguments(FacadeKind.Sorted)] + [Arguments(FacadeKind.Grouped)] + [Arguments(FacadeKind.Dynamic)] + [Arguments(FacadeKind.DynamicFiltered)] + [Arguments(FacadeKind.SecondaryIndex)] + [Arguments(FacadeKind.DynamicSecondaryIndex)] + [Arguments(FacadeKind.DynamicSecondaryIndexDictionary)] + [Arguments(FacadeKind.SourceView)] + public async Task BatchResetLimit_GetAndSet_RoundTripsAndRejectsNegative(FacadeKind kind) + { + using var facade = Create(kind); + + await Assert.That(facade.GetLimit()).IsEqualTo(int.MaxValue); + facade.SetLimit(AssignedLimit); + await Assert.That(facade.GetLimit()).IsEqualTo(AssignedLimit); + await Assert.That(() => facade.SetLimit(-1)).Throws(); + } + + /// Verifies handlers can be added to and removed from both change events. + /// The view kind. + /// A task representing the asynchronous test. + [Test] + [Arguments(FacadeKind.Filtered)] + [Arguments(FacadeKind.Sorted)] + [Arguments(FacadeKind.Grouped)] + [Arguments(FacadeKind.Dynamic)] + [Arguments(FacadeKind.DynamicFiltered)] + [Arguments(FacadeKind.SecondaryIndex)] + [Arguments(FacadeKind.DynamicSecondaryIndex)] + [Arguments(FacadeKind.DynamicSecondaryIndexDictionary)] + [Arguments(FacadeKind.SourceView)] + public async Task ChangeEvents_AddAndRemoveHandlers_DoNotThrow(FacadeKind kind) + { + using var facade = Create(kind); + NotifyCollectionChangedEventHandler collectionHandler = static (_, _) => { }; + PropertyChangedEventHandler propertyHandler = static (_, _) => { }; + + if (facade.Changes is { } changes) + { + changes.CollectionChanged += collectionHandler; + changes.CollectionChanged -= collectionHandler; + } + + facade.Properties.PropertyChanged += propertyHandler; + facade.Properties.PropertyChanged -= propertyHandler; + + await Assert.That(facade.GetLimit()).IsEqualTo(int.MaxValue); + } + + /// Builds a view of a kind over an empty source. + /// The view kind. + /// The accessors of the view. + private static FacadeAccessors Create(FacadeKind kind) + { + if (kind is FacadeKind.SecondaryIndex or FacadeKind.DynamicSecondaryIndex or FacadeKind.DynamicSecondaryIndexDictionary) + { + return CreateIndexed(kind); + } + + switch (kind) + { + case FacadeKind.Filtered: + { + var list = new ReactiveList(); + var view = new FilteredReactiveView(list, static _ => true, Sequencer.Immediate, TimeSpan.Zero); + return new(new DisposeGroup(view, list), view, view, () => view.BatchResetLimit, limit => view.BatchResetLimit = limit); + } + + case FacadeKind.Sorted: + { + var list = new ReactiveList(); + var view = new SortedReactiveView(list, Comparer.Default, Sequencer.Immediate, TimeSpan.Zero); + return new(new DisposeGroup(view, list), view, view, () => view.BatchResetLimit, limit => view.BatchResetLimit = limit); + } + + case FacadeKind.Grouped: + { + var list = new ReactiveList(); + var view = new GroupedReactiveView(list, static value => value % IndexKeyCount, Sequencer.Immediate, TimeSpan.Zero); + return new(new DisposeGroup(view, list), view, view, () => view.BatchResetLimit, limit => view.BatchResetLimit = limit); + } + + case FacadeKind.Dynamic: + { + var list = new ReactiveList(); + var filters = new BehaviorSignal>(static _ => true); + var view = new DynamicReactiveView(list, filters, TimeSpan.Zero, Sequencer.Immediate); + return new(new DisposeGroup(view, list), null, view, () => view.BatchResetLimit, limit => view.BatchResetLimit = limit); + } + + case FacadeKind.DynamicFiltered: + { + var list = new ReactiveList(); + var filters = new BehaviorSignal>(static _ => true); + var view = new DynamicFilteredReactiveView(list, filters, Sequencer.Immediate, TimeSpan.Zero); + return new(new DisposeGroup(view, list), view, view, () => view.BatchResetLimit, limit => view.BatchResetLimit = limit); + } + + default: + { + var list = new ReactiveList(); + var view = new ReactiveView(list, static _ => true, TimeSpan.Zero, Sequencer.Immediate); + return new(new DisposeGroup(view, list), null, view, () => view.BatchResetLimit, limit => view.BatchResetLimit = limit); + } + } + } + + /// Builds a view of a kind over an empty secondary index source. + /// The view kind. + /// The accessors of the view. + private static FacadeAccessors CreateIndexed(FacadeKind kind) + { + switch (kind) + { + case FacadeKind.SecondaryIndex: + { + var dictionary = new QuaternaryDictionary(); + dictionary.AddValueIndex(IndexName, static value => value % IndexKeyCount); + var view = SecondaryIndexReactiveView.Create(dictionary, IndexName, 0, Sequencer.Immediate, TimeSpan.Zero); + return new(new DisposeGroup(view, dictionary), view, view, () => view.BatchResetLimit, limit => view.BatchResetLimit = limit); + } + + case FacadeKind.DynamicSecondaryIndex: + { + var list = new QuaternaryList(); + list.AddIndex(IndexName, static value => value % IndexKeyCount); + var keys = new BehaviorSignal([0]); + var view = new DynamicSecondaryIndexReactiveView(list, IndexName, keys, Sequencer.Immediate, TimeSpan.Zero); + return new(new DisposeGroup(view, list), view, view, () => view.BatchResetLimit, limit => view.BatchResetLimit = limit); + } + + default: + { + var dictionary = new QuaternaryDictionary(); + dictionary.AddValueIndex(IndexName, static value => value % IndexKeyCount); + var keys = new BehaviorSignal([0]); + var view = DynamicSecondaryIndexDictionaryReactiveView.Create(dictionary, IndexName, keys, Sequencer.Immediate, TimeSpan.Zero); + return new(new DisposeGroup(view, dictionary), view, view, () => view.BatchResetLimit, limit => view.BatchResetLimit = limit); + } + } + } + + /// Gives a test the pieces of a view it exercises. + /// Disposes the view and its source. + /// The collection change event of the view, or when the view has none. + /// The property change event of the view. + /// Reads the batch reset limit. + /// Assigns the batch reset limit. + private sealed record FacadeAccessors( + IDisposable Owner, + INotifyCollectionChanged? Changes, + INotifyPropertyChanged Properties, + Func GetLimit, + Action SetLimit) : IDisposable + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => Owner.Dispose(); + } + + /// Disposes a view and then its source. + /// The view. + /// The source. + private sealed record DisposeGroup(IDisposable View, IDisposable Source) : IDisposable + { + /// + public void Dispose() + { + View.Dispose(); + Source.Dispose(); + } + } +} diff --git a/src/tests/ReactiveList.Tests/ViewFuzzKind.cs b/src/tests/ReactiveList.Tests/ViewFuzzKind.cs new file mode 100644 index 00000000..08556d00 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewFuzzKind.cs @@ -0,0 +1,54 @@ +// 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. + +namespace ReactiveList.Tests; + +/// The kinds of source mutation the view fuzz tests generate. +internal enum ViewFuzzKind +{ + /// Add one item. + Add = 0, + + /// Add a range of items. + AddRange = 1, + + /// Insert one item at an index. + Insert = 2, + + /// Insert a range of items at an index. + InsertRange = 3, + + /// Remove one item by value. + Remove = 4, + + /// Remove one item by index. + RemoveAt = 5, + + /// Remove an index range. + RemoveRange = 6, + + /// Remove every item matching a predicate. + RemoveMany = 7, + + /// Replace an item through the update API. + Update = 8, + + /// Replace an item through the indexer. + SetIndex = 9, + + /// Move an item between indices. + Move = 10, + + /// Remove every item. + Clear = 11, + + /// Replace every item. + ReplaceAll = 12, + + /// Add and remove items inside one edit. + Edit = 13, + + /// Remove several items by value. + RemoveItems = 14, +} diff --git a/src/tests/ReactiveList.Tests/ViewFuzzOp.cs b/src/tests/ReactiveList.Tests/ViewFuzzOp.cs new file mode 100644 index 00000000..189158c6 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewFuzzOp.cs @@ -0,0 +1,12 @@ +// 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. + +namespace ReactiveList.Tests; + +/// One randomly generated source mutation used by the view fuzz tests. +/// The mutation kind. +/// The first generated number, used as an index or value. +/// The second generated number, used as an index or value. +/// The generated items for range operations. +internal readonly record struct ViewFuzzOp(ViewFuzzKind Kind, int A, int B, int[] Items); diff --git a/src/tests/ReactiveList.Tests/ViewFuzzSupport.cs b/src/tests/ReactiveList.Tests/ViewFuzzSupport.cs new file mode 100644 index 00000000..7d18b9a3 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewFuzzSupport.cs @@ -0,0 +1,433 @@ +// 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. + +using CsCheck; + +namespace ReactiveList.Tests; + +/// Generators, mutation drivers and model helpers shared by the view fuzz tests. +internal static class ViewFuzzSupport +{ + /// The exclusive upper bound of generated item values. Small so duplicates are common. + internal const int ValueRange = 12; + + /// The exclusive upper bound of generated dictionary keys. Small so keys collide and entries are updated. + internal const int KeyRange = 8; + + /// The number of times a racing copy of a view collection is retried. + internal const int CopyAttempts = 100; + + /// The value written last to prove every earlier notification has been processed. + internal const int Sentinel = 1000; + + /// The largest generated index or count. + private const int MaxNumber = 30; + + /// The longest generated item array. + private const int MaxItems = 5; + + /// The longest generated initial item array. + private const int MaxInitial = 12; + + /// The smallest divisor used by the generated remove-many predicate. + private const int DivisorBase = 2; + + /// The number of distinct divisors used by the generated remove-many predicate. + private const int DivisorSpan = 4; + + /// Values divisible by this number fail the default filter. + private const int FilterDivisor = 3; + + /// The timeout, in milliseconds, for waiting on background delivery. + private const int SettleTimeoutMilliseconds = 10_000; + + /// Gets a generator for a single mutation. + internal static Gen OpGen { get; } = Gen.Select( + Gen.Enum(), + Gen.Int[0, MaxNumber], + Gen.Int[0, MaxNumber], + Gen.Int[0, ValueRange - 1].Array[0, MaxItems], + static (kind, a, b, items) => new ViewFuzzOp(kind, a, b, items)); + + /// Gets a generator for an initial item array. + internal static Gen InitialGen { get; } = Gen.Int[0, ValueRange - 1].Array[0, MaxInitial]; + + /// Gets a generator for a sequence of mutations. + /// The longest sequence. + /// The sequence generator. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static Gen OpsGen(int maxLength) => OpGen.Array[0, maxLength]; + + /// The default filter used by the fuzz tests. Roughly two thirds of the values pass. + /// The value to test. + /// when the value passes. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool Passes(int value) => value % FilterDivisor != 0; + + /// Copies a view collection that a scheduler thread may still be changing. + /// The view collection. + /// The copy, which is empty when no consistent copy could be taken. + internal static int[] Copy(IReadOnlyList items) + { + for (var attempt = 0; attempt < CopyAttempts; attempt++) + { + try + { + var copy = new int[items.Count]; + for (var i = 0; i < copy.Length; i++) + { + copy[i] = items[i]; + } + + return copy; + } + catch (ArgumentOutOfRangeException) + { + // The collection shrank during the copy. + } + } + + return []; + } + + /// Returns whether a view collection holds a value while a scheduler thread may still be changing it. + /// The view collection. + /// The value to look for. + /// when the value is present. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool Holds(IReadOnlyList items, int value) => Array.IndexOf(Copy(items), value) >= 0; + + /// Returns the values sorted ascending so unordered collections compare as multisets. + /// The values to sort. + /// The sorted values. + internal static int[] Sorted(IEnumerable values) + { + var array = values is IReadOnlyList list ? Copy(list) : values.ToArray(); + Array.Sort(array); + return array; + } + + /// Applies one mutation to a reactive list, skipping operations that are invalid for its current size. + /// The list to mutate. + /// The mutation. + internal static void Apply(ReactiveList list, ViewFuzzOp op) + { + if (ApplyAdditions(list, op) || ApplyRemovals(list, op) || ApplyChanges(list, op)) + { + return; + } + + list.Add(op.A % ValueRange); + } + + /// Applies one mutation to a quaternary list, mapping index based operations to value based ones. + /// The list to mutate. + /// The mutation. + internal static void Apply(QuaternaryList list, ViewFuzzOp op) + { + var divisor = (op.A % DivisorSpan) + DivisorBase; + switch (op.Kind) + { + case ViewFuzzKind.AddRange or ViewFuzzKind.InsertRange: + { + list.AddRange(op.Items); + break; + } + + case ViewFuzzKind.Remove or ViewFuzzKind.RemoveAt: + { + _ = list.Remove(op.A % ValueRange); + break; + } + + case ViewFuzzKind.RemoveRange or ViewFuzzKind.RemoveItems: + { + list.RemoveRange(op.Items); + break; + } + + case ViewFuzzKind.RemoveMany: + { + _ = list.RemoveMany(item => item % divisor == 0); + break; + } + + case ViewFuzzKind.Clear: + { + list.Clear(); + break; + } + + case ViewFuzzKind.ReplaceAll: + { + list.ReplaceAll(op.Items); + break; + } + + case ViewFuzzKind.Edit: + { + list.Edit(edit => + { + foreach (var item in op.Items) + { + edit.Add(item); + } + + _ = edit.Remove(op.B % ValueRange); + }); + break; + } + + default: + { + list.Add(op.A % ValueRange); + break; + } + } + } + + /// Applies one mutation to a quaternary dictionary, mapping list style operations to key based ones. + /// The dictionary to mutate. + /// The mutation. + internal static void Apply(QuaternaryDictionary dictionary, ViewFuzzOp op) + { + var key = op.A % KeyRange; + var value = op.B % ValueRange; + var divisor = (op.A % DivisorSpan) + DivisorBase; + switch (op.Kind) + { + case ViewFuzzKind.Remove or ViewFuzzKind.RemoveAt: + { + _ = dictionary.Remove(key); + break; + } + + case ViewFuzzKind.RemoveRange or ViewFuzzKind.RemoveItems: + { + dictionary.RemoveKeys(op.Items); + break; + } + + case ViewFuzzKind.RemoveMany: + { + _ = dictionary.RemoveMany(entry => entry.Value % divisor == 0); + break; + } + + case ViewFuzzKind.Clear: + { + dictionary.Clear(); + break; + } + + case ViewFuzzKind.ReplaceAll or ViewFuzzKind.Edit: + { + dictionary.Edit(edit => + { + if (op.Kind == ViewFuzzKind.ReplaceAll) + { + edit.Clear(); + } + + foreach (var item in op.Items) + { + edit[item % KeyRange] = value; + } + + _ = edit.Remove(key); + }); + break; + } + + default: + { + dictionary.AddOrUpdate(key, value); + break; + } + } + } + + /// Waits until the view holds the sentinel that was written after every other mutation. + /// Returns whether the sentinel reached the view. + /// A task that completes when the view has caught up. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static Task SettleAsync(Func isSettled) => + TestWaitHelpers.WaitUntilAsync(isSettled, SettleTimeoutMilliseconds, 1); + + /// Captures the view on its scheduler after the drain that applied the final mutation. + /// The view that notifies after each completed drain. + /// The view items. + /// The value that marks the final mutation. + /// Writes the sentinel to the source. + /// A snapshot from the completed drain. + internal static async Task CaptureAfterDrainAsync(INotifyPropertyChanged view, IReadOnlyList items, int sentinel, Action mutate) + { + using var timeout = new CancellationTokenSource(TimeSpan.FromMilliseconds(SettleTimeoutMilliseconds)); + var drained = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + PropertyChangedEventHandler capture = (_, _) => + { + var snapshot = Copy(items); + if (Array.IndexOf(snapshot, sentinel) >= 0) + { + _ = drained.TrySetResult(snapshot); + } + }; + + view.PropertyChanged += capture; + try + { + mutate(); + return await drained.Task.WaitAsync(timeout.Token); + } + finally + { + view.PropertyChanged -= capture; + } + } + + /// Applies the mutations that add or replace items. + /// The list to mutate. + /// The mutation. + /// when the mutation was handled. + private static bool ApplyAdditions(ReactiveList list, ViewFuzzOp op) + { + var count = list.Count; + switch (op.Kind) + { + case ViewFuzzKind.AddRange: + { + list.AddRange(op.Items); + return true; + } + + case ViewFuzzKind.Insert: + { + list.Insert(op.A % (count + 1), op.B % ValueRange); + return true; + } + + case ViewFuzzKind.InsertRange: + { + list.InsertRange(op.A % (count + 1), op.Items); + return true; + } + + case ViewFuzzKind.ReplaceAll: + { + list.ReplaceAll(op.Items); + return true; + } + + case ViewFuzzKind.Edit: + { + // An edit whose added and removed values cancel reorders the list without any notification, which is + // quarantined in ReactiveListEditOrderQuarantineTests, so the shared generator avoids it. + var removed = op.B % ValueRange; + var cancels = Array.IndexOf(op.Items, removed) >= 0; + list.Edit(edit => + { + edit.AddRange(op.Items); + if (!cancels) + { + _ = edit.Remove(removed); + } + }); + return true; + } + + default: + { + return false; + } + } + } + + /// Applies the mutations that remove items. + /// The list to mutate. + /// The mutation. + /// when the mutation was handled. + private static bool ApplyRemovals(ReactiveList list, ViewFuzzOp op) + { + var count = list.Count; + var divisor = (op.A % DivisorSpan) + DivisorBase; + switch (op.Kind) + { + case ViewFuzzKind.Remove: + { + _ = list.Remove(op.A % ValueRange); + return true; + } + + case ViewFuzzKind.RemoveAt when count > 0: + { + list.RemoveAt(op.A % count); + return true; + } + + case ViewFuzzKind.RemoveRange when count > 0: + { + var start = op.A % count; + list.RemoveRange(start, op.B % (count - start + 1)); + return true; + } + + case ViewFuzzKind.RemoveMany: + { + _ = list.RemoveMany(item => item % divisor == 0); + return true; + } + + case ViewFuzzKind.Clear: + { + list.Clear(); + return true; + } + + case ViewFuzzKind.RemoveItems: + { + list.Remove((IEnumerable)op.Items); + return true; + } + + default: + { + return false; + } + } + } + + /// Applies the mutations that replace or reorder items in place. + /// The list to mutate. + /// The mutation. + /// when the mutation was handled. + private static bool ApplyChanges(ReactiveList list, ViewFuzzOp op) + { + var count = list.Count; + switch (op.Kind) + { + case ViewFuzzKind.Update when count > 0: + { + list.Update(list[op.A % count], op.B % ValueRange); + return true; + } + + case ViewFuzzKind.SetIndex when count > 0: + { + list[op.A % count] = op.B % ValueRange; + return true; + } + + case ViewFuzzKind.Move when count > 1: + { + list.Move(op.A % count, op.B % count); + return true; + } + + default: + { + return false; + } + } + } +} diff --git a/src/tests/ReactiveList.Tests/ViewIncrementalApplyTests.cs b/src/tests/ReactiveList.Tests/ViewIncrementalApplyTests.cs new file mode 100644 index 00000000..6ed4a067 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewIncrementalApplyTests.cs @@ -0,0 +1,242 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies common source notifications reach a view incrementally instead of through a full source copy. +public class ViewIncrementalApplyTests +{ + /// The value inserted at the head of a list. + private const int InsertedValue = 5; + + /// The value written over an existing entry. + private const int ReplacementValue = 7; + + /// The index an entry is moved to, and the length of a removed range. + private const int Span = 2; + + /// The number of concurrent writers. + private const int WriterCount = 4; + + /// The gap between the first values of two writers. + private const int WriterStride = 10_000; + + /// The number of writes each writer makes. + private const int WritesPerWriter = 500; + + /// The items a list starts with. + private static readonly int[] Initial = [1, 2, 3]; + + /// The values added in one batch. + private static readonly int[] Batch = [1, 2, 3, 4, 5, 7, 8]; + + /// The values removed as a batch. + private static readonly int[] RemovedBatch = [2, 4]; + + /// Single and batch notifications on a reactive list never trigger a resync. + /// A task representing the asynchronous test. + [Test] + public async Task ReactiveList_CommonNotifications_ApplyWithoutResync() + { + using var list = new ReactiveList(); + list.AddRange(Initial); + using var view = new ReactiveView(list, ViewFuzzSupport.Passes, TimeSpan.Zero, Sequencer.Immediate); + await SettleAsync(view, list); + var baseline = view.ResyncCount; + + list.Add(ViewFuzzSupport.Sentinel); + await SettleAsync(view, list); + list.Add(1); + await SettleAsync(view, list); + list.Insert(0, InsertedValue); + await SettleAsync(view, list); + list.AddRange(Batch); + await SettleAsync(view, list); + list[1] = ReplacementValue; + await SettleAsync(view, list); + list.Move(0, Span); + await SettleAsync(view, list); + _ = list.Remove(Batch[0]); + await SettleAsync(view, list); + list.RemoveAt(0); + await SettleAsync(view, list); + list.RemoveRange(0, Span); + await SettleAsync(view, list); + list.Remove((IEnumerable)RemovedBatch); + await SettleAsync(view, list); + list.Clear(); + await SettleAsync(view, list); + + await Assert.That(view.ResyncCount).IsEqualTo(baseline); + } + + /// Single and batch notifications on a quaternary list never trigger a resync. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryList_CommonNotifications_ApplyWithoutResync() + { + using var list = new QuaternaryList(); + list.AddRange(Initial); + using var view = new ReactiveView(list, ViewFuzzSupport.Passes, TimeSpan.Zero, Sequencer.Immediate); + + // A versioned source needs no confirming copy, so the copy taken at creation is the only one. + var baseline = view.ResyncCount; + list.Add(ViewFuzzSupport.Sentinel); + await SettleAsync(view, list); + + list.Add(1); + await SettleAsync(view, list); + list.AddRange(Batch); + await SettleAsync(view, list); + _ = list.Remove(Batch[0]); + await SettleAsync(view, list); + list.RemoveRange(RemovedBatch); + await SettleAsync(view, list); + list.Clear(); + await SettleAsync(view, list); + + await Assert.That(view.ResyncCount).IsEqualTo(baseline); + } + + /// A view over a quaternary list converges under concurrent writers without taking a confirming copy. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryList_ConcurrentWriters_ConvergeWithoutConfirmingCopy() + { + using var list = new QuaternaryList(); + list.AddRange(Initial); + using var view = new ReactiveView(list, ViewFuzzSupport.Passes, TimeSpan.Zero, Sequencer.Immediate); + var baseline = view.ResyncCount; + + var writers = new Task[WriterCount]; + for (var w = 0; w < WriterCount; w++) + { + var start = (w + 1) * WriterStride; + writers[w] = Task.Run(() => WriteRange(list, start)); + } + + await Task.WhenAll(writers); + await SettleAsync(view, list); + + await Assert.That(view.ResyncCount).IsEqualTo(baseline); + } + + /// A drain does not publish a later add on top of the stale contents from before an edit. + /// A task representing the asynchronous test. + [Test] + public async Task QuaternaryList_CoalescedEditAndAdd_PublishesConsistentSnapshot() + { + using var list = new QuaternaryList(); + list.AddRange(Initial); + var scheduler = new QueuedDrain(); + using var view = ((IReactiveSource)list).CreateView(static _ => true, scheduler, 0); + using var timeout = new CancellationTokenSource(TimeSpan.FromMilliseconds(TestWaitHelpers.DefaultTimeoutMilliseconds)); + var addDelivered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var subscription = list.VersionedStream.Subscribe(change => + { + if (change.Notification.Item == ViewFuzzSupport.Sentinel) + { + _ = addDelivered.TrySetResult(); + } + }); + + int[]? firstSnapshotWithAdd = null; + ((INotifyCollectionChanged)view.Items).CollectionChanged += (_, _) => + { + if (firstSnapshotWithAdd is null && view.Items.Contains(ViewFuzzSupport.Sentinel)) + { + firstSnapshotWithAdd = ViewFuzzSupport.Sorted(view.Items); + } + }; + + list.Edit(static items => items.Clear()); + list.Add(ViewFuzzSupport.Sentinel); + await addDelivered.Task.WaitAsync(timeout.Token); + scheduler.RunAll(); + + await Assert.That(firstSnapshotWithAdd).IsEquivalentTo([ViewFuzzSupport.Sentinel], CollectionOrdering.Matching); + await Assert.That(view.Items).IsEquivalentTo([ViewFuzzSupport.Sentinel], CollectionOrdering.Matching); + } + + /// Adds and removes a run of values one at a time. + /// The list to write to. + /// The first value. + private static void WriteRange(QuaternaryList list, int start) + { + for (var i = 0; i < WritesPerWriter; i++) + { + list.Add(start + i); + if ((i & 1) == 1) + { + _ = list.Remove(start + i - 1); + } + } + } + + /// Waits until the view matches the filtered source ignoring order. + /// The view. + /// The source. + /// A task that completes when the view has converged. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Task SettleAsync(ReactiveView view, IReactiveSource source) => + ViewFuzzSupport.SettleAsync(() => ViewFuzzSupport.Sorted(view.Items).SequenceEqual(ViewFuzzSupport.Sorted(source.ToArray().Where(ViewFuzzSupport.Passes)))); + + /// Holds scheduled drains until the source reader has delivered every change of interest. + private sealed class QueuedDrain : ISequencer + { +#if REACTIVELIST_REACTIVE + /// The callbacks queued by the source reader. + private readonly System.Collections.Concurrent.ConcurrentQueue _work = new(); + + /// + public DateTimeOffset Now => Sequencer.Immediate.Now; + + /// + public IDisposable Schedule(TState state, Func action) + { + var ticket = new System.Reactive.Disposables.SingleAssignmentDisposable(); + _work.Enqueue(() => ticket.Disposable = action(this, state)); + return ticket; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IDisposable Schedule(TState state, TimeSpan dueTime, Func action) => Schedule(state, action); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public IDisposable Schedule(TState state, DateTimeOffset dueTime, Func action) => Schedule(state, action); +#else + /// The work items queued by the source reader. + private readonly System.Collections.Concurrent.ConcurrentQueue _work = new(); + + /// + public DateTimeOffset Now => Sequencer.Immediate.Now; + + /// + public long Timestamp => Sequencer.Immediate.Timestamp; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Schedule(IWorkItem item) => _work.Enqueue(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Schedule(IWorkItem item, long dueTimestamp) => Schedule(item); +#endif + + /// Executes the queued drains. + internal void RunAll() + { + while (_work.TryDequeue(out var item)) + { +#if REACTIVELIST_REACTIVE + item(); +#else + item.Execute(); +#endif + } + } + } +} diff --git a/src/tests/ReactiveList.Tests/ViewMirrorPumpTests.cs b/src/tests/ReactiveList.Tests/ViewMirrorPumpTests.cs new file mode 100644 index 00000000..ef11eade --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewMirrorPumpTests.cs @@ -0,0 +1,170 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies the start, drain and disposal edges of . +public sealed class ViewMirrorPumpTests +{ + /// The first value inserted. + private const int FirstItem = 7; + + /// The second value inserted. + private const int SecondItem = 8; + + /// The source revision of the second notification. + private const long SecondVersion = 2; + + /// The call of the work check that reports queued work once. + private const int QueuedWorkCall = 3; + + /// The event the recording sink writes when the mirror is rebuilt. + private const string ResetEvent = "reset"; + + /// Verifies a failed first copy releases the source subscription and rethrows. + /// A task representing the asynchronous test. + [Test] + public async Task Constructor_CopyFails_ReleasesTheSubscription() + { + using var inner = new QuaternaryList(); + using var source = new VersionedCountingSource(inner) { FailCopies = true }; + + await Assert.That(() => new ViewMirrorPump(source)).Throws(); + + await Assert.That(source.ActiveSubscriptions).IsEqualTo(0); + } + + /// Verifies a failure reported by the source is rethrown and completion is accepted. + /// A task representing the asynchronous test. + [Test] + public async Task OnError_SourceFails_Rethrows() + { + using var source = new ScriptedViewSource(); + using var pump = new ViewMirrorPump(source); + + pump.OnCompleted(); + + await Assert.That(() => pump.OnError(new InvalidOperationException())).Throws(); + } + + /// Verifies a notification that arrives while earlier ones are retained is queued behind them. + /// A task representing the asynchronous test. + [Test] + public async Task OnNext_NotificationsAlreadyRetained_AppliesInOrder() + { + using var inner = new QuaternaryList(); + using var source = new VersionedCountingSource(inner); + using var pump = new ViewMirrorPump(source); + var sink = new RecordingMirrorSink(); + pump.Start(sink, TimeSpan.Zero, ReactiveListScheduler.Immediate); + _ = pump.Buffer.Capture(new(CacheAction.Added, FirstItem, CurrentIndex: 0), 1); + + pump.OnNext(new VersionedNotification(new(CacheAction.Added, SecondItem, CurrentIndex: 1), SecondVersion)); + + await Assert.That(sink.Events).IsEquivalentTo(["insert:0:1", "insert:1:1"]); + await Assert.That(pump.Buffer.Items).IsEquivalentTo([FirstItem, SecondItem], CollectionOrdering.Matching); + } + + /// Verifies work that arrives while an inline drain finishes is drained before the call returns. + /// A task representing the asynchronous test. + [Test] + public async Task OnNext_WorkArrivesDuringInlineDrain_DrainsAgain() + { + using var inner = new QuaternaryList(); + using var source = new VersionedCountingSource(inner); + using var pump = new ViewMirrorPump(source); + var sink = new RecordingMirrorSink(); + var checks = 0; + pump.Start( + sink, + TimeSpan.Zero, + ReactiveListScheduler.Immediate, + hasQueued: () => + { + checks++; + return checks == QueuedWorkCall; + }); + + pump.OnNext(new VersionedNotification(new(CacheAction.Added, FirstItem, CurrentIndex: 0), 1)); + + await Assert.That(sink.Events).IsEquivalentTo(["insert:0:1"]); + await Assert.That(checks).IsGreaterThan(QueuedWorkCall); + } + + /// Verifies work queued by the owner both before and after the changes is applied and reported. + /// A task representing the asynchronous test. + [Test] + public async Task Refresh_OwnerWorkQueued_RebuildsTheMirror() + { + using var source = new ScriptedViewSource(); + using var pump = new ViewMirrorPump(source); + var sink = new RecordingMirrorSink(); + pump.Start(sink, TimeSpan.Zero, ReactiveListScheduler.Immediate, static () => true); + + pump.Refresh(); + + await Assert.That(sink.Events).IsEquivalentTo([ResetEvent]); + } + + /// Verifies a drain requested while another drain owns the pump is left to that drain. + /// A task representing the asynchronous test. + [Test] + public async Task Drain_WhileAnotherDrainOwnsThePump_ReturnsAtOnce() + { + using var source = new ScriptedViewSource(); + using var pump = new ViewMirrorPump(source); + var sink = new RecordingMirrorSink(); + var nestedDrains = 0; + sink.OnReset = () => + { + pump.Drain(); + nestedDrains++; + }; + pump.Start(sink, TimeSpan.Zero, ReactiveListScheduler.Immediate); + + pump.Refresh(); + + await Assert.That(nestedDrains).IsEqualTo(1); + await Assert.That(sink.Events).IsEquivalentTo([ResetEvent]); + } + + /// Verifies a drain before the pump started has nothing to apply. + /// A task representing the asynchronous test. + [Test] + public async Task Drain_BeforeStart_DoesNothing() + { + using var source = new ScriptedViewSource(); + using var pump = new ViewMirrorPump(source); + + pump.Drain(); + + await Assert.That(pump.IsDisposed).IsFalse(); + } + + /// Verifies a pump disposed before it started releases the source subscription at once. + /// A task representing the asynchronous test. + [Test] + public async Task Start_AfterDispose_ReleasesTheSourceSubscription() + { + using var source = new ScriptedViewSource(); + var pump = new ViewMirrorPump(source); + pump.Dispose(); + + pump.Start(new RecordingMirrorSink(), TimeSpan.Zero, ReactiveListScheduler.Immediate); + + await Assert.That(source.Notifications.HasObserver).IsFalse(); + } + + /// Verifies the property change stream of a disposed pump is already disposed. + /// A task representing the asynchronous test. + [Test] + public async Task PropertyChanges_AfterDispose_ReturnsADisposedSignal() + { + using var source = new ScriptedViewSource(); + var pump = new ViewMirrorPump(source); + pump.Dispose(); + + await Assert.That(() => pump.PropertyChanges.Subscribe(static _ => { })).Throws(); + } +} diff --git a/src/tests/ReactiveList.Tests/ViewResetLimitRegimeTests.cs b/src/tests/ReactiveList.Tests/ViewResetLimitRegimeTests.cs new file mode 100644 index 00000000..98851b26 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewResetLimitRegimeTests.cs @@ -0,0 +1,283 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies the batch reset limit is the only thing that turns a batch into a reset, on both sides of the limit, for every list view kind. +public sealed class ViewResetLimitRegimeTests +{ + /// The number of items in the batch, which is above the size a fixed internal threshold would have used. + private const int BatchSize = 100; + + /// A limit below the batch size. + private const int SmallLimit = 10; + + /// The number of groups the grouped view splits the items into. + private const int GroupCount = 4; + + /// The index of the first batch item in the source. + private const int FirstBatchIndex = GroupCount; + + /// The items the source holds before the batch, one per group. + private static readonly int[] Seed = [0, 1, 2, 3]; + + /// The view kinds checked. + public enum ViewKind + { + /// A filtered view. + Filtered = 0, + + /// A sorted view. + Sorted = 1, + + /// A dynamic view. + Dynamic = 2, + + /// A view over a source. + SourceView = 3, + + /// A grouped view. + Grouped = 4, + } + + /// The limit regimes checked. + public enum LimitRegime + { + /// The limit was left at its default. + Default = 0, + + /// The limit equals the batch size, so the batch is within it. + WithinLimit = 1, + + /// The limit is below the batch size. + OverLimit = 2, + } + + /// A batch add raises one notification per item unless it is larger than the limit, and then raises one reset per changed collection. + /// A task representing the asynchronous test. + [Test] + public async Task BatchAdd_NotificationShapeFollowsTheLimit() + { + foreach (var kind in Enum.GetValues()) + { + foreach (var regime in Enum.GetValues()) + { + using var list = new ReactiveList(); + list.AddRange(Seed); + using var probe = Create(kind, list, regime); + var actions = new List(); + probe.Watch((_, args) => actions.Add(args.Action)); + + list.AddRange(Batch()); + + await AssertShapeAsync(actions, kind, regime, NotifyCollectionChangedAction.Add); + await Assert.That(probe.Values()).IsEquivalentTo(Expected(0, Seed.Length + BatchSize), CollectionOrdering.Matching); + } + } + } + + /// A batch removed by position follows the same limit rules. + /// A task representing the asynchronous test. + [Test] + public async Task BatchRemoveByPosition_NotificationShapeFollowsTheLimit() + { + foreach (var kind in Enum.GetValues()) + { + foreach (var regime in Enum.GetValues()) + { + using var list = new ReactiveList(); + list.AddRange(Seed); + list.AddRange(Batch()); + using var probe = Create(kind, list, regime); + var actions = new List(); + probe.Watch((_, args) => actions.Add(args.Action)); + + list.RemoveRange(FirstBatchIndex, BatchSize); + + await AssertShapeAsync(actions, kind, regime, NotifyCollectionChangedAction.Remove); + await Assert.That(probe.Values()).IsEquivalentTo(Expected(0, Seed.Length), CollectionOrdering.Matching); + } + } + } + + /// A batch removed by value follows the same limit rules. + /// A task representing the asynchronous test. + [Test] + public async Task BatchRemoveByValue_NotificationShapeFollowsTheLimit() + { + foreach (var kind in Enum.GetValues()) + { + foreach (var regime in Enum.GetValues()) + { + using var list = new ReactiveList(); + list.AddRange(Seed); + list.AddRange(Batch()); + using var probe = Create(kind, list, regime); + var actions = new List(); + probe.Watch((_, args) => actions.Add(args.Action)); + + list.Remove(Batch().AsEnumerable()); + + await AssertShapeAsync(actions, kind, regime, NotifyCollectionChangedAction.Remove); + await Assert.That(probe.Values()).IsEquivalentTo(Expected(0, Seed.Length), CollectionOrdering.Matching); + } + } + } + + /// Gets the batch values, which follow the seed values. + /// The values. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int[] Batch() => Expected(Seed.Length, BatchSize); + + /// Gets a run of consecutive values. + /// The first value. + /// The number of values. + /// The values. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int[] Expected(int first, int count) => [.. Enumerable.Range(first, count)]; + + /// Checks the notifications raised for a batch. + /// The notifications raised. + /// The view kind. + /// The limit regime. + /// The action expected once per item when the batch is within the limit. + /// A task representing the asynchronous check. + private static async Task AssertShapeAsync(List actions, ViewKind kind, LimitRegime regime, NotifyCollectionChangedAction perItem) + { + if (regime != LimitRegime.OverLimit) + { + await Assert.That(actions.Count).IsEqualTo(BatchSize); + await Assert.That(actions.TrueForAll(action => action == perItem)).IsTrue(); + return; + } + + // One reset per collection the batch changed: the view's own collection, or each of the groups. + var expected = kind == ViewKind.Grouped ? GroupCount : 1; + await Assert.That(actions.Count).IsEqualTo(expected); + await Assert.That(actions.TrueForAll(static action => action == NotifyCollectionChangedAction.Reset)).IsTrue(); + } + + /// Creates a view with its limit set for a regime. + /// The view kind. + /// The source list. + /// The limit regime. + /// The probe over the view. + private static ViewProbe Create(ViewKind kind, ReactiveList list, LimitRegime regime) + { + var limit = regime switch + { + LimitRegime.WithinLimit => BatchSize, + LimitRegime.OverLimit => SmallLimit, + _ => int.MaxValue, + }; + + switch (kind) + { + case ViewKind.Filtered: + { + var view = new FilteredReactiveView(list, static _ => true, Sequencer.Immediate, TimeSpan.Zero) { BatchResetLimit = limit }; + return ViewProbe.ForList(view, view.Items); + } + + case ViewKind.Sorted: + { + var view = new SortedReactiveView(list, Comparer.Default, Sequencer.Immediate, TimeSpan.Zero) { BatchResetLimit = limit }; + return ViewProbe.ForList(view, view.Items); + } + + case ViewKind.Dynamic: + { + var filters = new BehaviorSignal>(static _ => true); + var view = new DynamicReactiveView(list, filters, TimeSpan.Zero, Sequencer.Immediate) { BatchResetLimit = limit }; + return ViewProbe.ForList(new DisposePair(view, filters), view.Items); + } + + case ViewKind.SourceView: + { + var view = new ReactiveView(list, static _ => true, TimeSpan.Zero, Sequencer.Immediate) { BatchResetLimit = limit }; + return ViewProbe.ForList(view, view.Items); + } + + default: + { + var view = new GroupedReactiveView(list, static value => value % GroupCount, Sequencer.Immediate, TimeSpan.Zero) { BatchResetLimit = limit }; + return ViewProbe.ForGroups(view); + } + } + } + + /// A view under test. + private sealed class ViewProbe : IDisposable + { + /// The view to dispose. + private readonly IDisposable _view; + + /// Reads the items, sorted. + private readonly Func _values; + + /// Subscribes to every collection the view publishes changes on. + private readonly Action _watch; + + /// Initializes a new instance of the class. + /// The view to dispose. + /// Reads the items, sorted. + /// Subscribes to every collection the view publishes changes on. + private ViewProbe(IDisposable view, Func values, Action watch) + { + _view = view; + _values = values; + _watch = watch; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => _view.Dispose(); + + /// Creates a probe over a view that publishes one collection. + /// The view to dispose. + /// The collection. + /// The probe. + internal static ViewProbe ForList(IDisposable view, ReadOnlyObservableCollection items) => + new(view, () => ViewFuzzSupport.Sorted(items), handler => ((INotifyCollectionChanged)items).CollectionChanged += handler); + + /// Creates a probe over a grouped view, watching the group collection and every group present now. + /// The view. + /// The probe. + internal static ViewProbe ForGroups(GroupedReactiveView view) => + new( + view, + () => ViewFuzzSupport.Sorted(view.Groups.SelectMany(static group => group.Items)), + handler => + { + ((INotifyCollectionChanged)view.Groups).CollectionChanged += handler; + foreach (var group in view.Groups) + { + ((INotifyCollectionChanged)group.Items).CollectionChanged += handler; + } + }); + + /// Reads the items, sorted. + /// The items. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal int[] Values() => _values(); + + /// Subscribes to every collection the view publishes changes on. + /// The handler. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void Watch(NotifyCollectionChangedEventHandler handler) => _watch(handler); + } + + /// Disposes a view and the signal that feeds it. + /// The view. + /// The signal. + private sealed class DisposePair(IDisposable view, IDisposable signal) : IDisposable + { + /// + public void Dispose() + { + view.Dispose(); + signal.Dispose(); + } + } +} diff --git a/src/tests/ReactiveList.Tests/ViewRetentionTests.cs b/src/tests/ReactiveList.Tests/ViewRetentionTests.cs new file mode 100644 index 00000000..aa57f4e7 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewRetentionTests.cs @@ -0,0 +1,568 @@ +// 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. + +namespace ReactiveList.Tests; + +/// +/// Proves a disposed view, its collections and every item removed from its source become unreachable while the source +/// stays alive, and that a disposed view raises nothing further. +/// +public sealed class ViewRetentionTests +{ + /// The name of the secondary index. + private const string IndexName = "parity"; + + /// The number of items added before the view is built. + private const int SeedCount = 20; + + /// The number of items added in one batch. + private const int BatchCount = 40; + + /// The first identifier of the batch items. + private const int BatchFirst = 100; + + /// The first identifier of the items added after disposal. + private const int LateFirst = 200; + + /// The identifier of the single item added after disposal. + private const int LateSingle = 300; + + /// The first identifier of the untracked items that replace the list's last removal batch. + private const int FlushFirst = 400; + + /// The number of untracked items that replace the list's last removal batch. + private const int FlushCount = 3; + + /// The number of groups. + private const int GroupCount = 4; + + /// The size of each block allocated to push the runtime into a full collection. + private const int PressureBlockSize = 4 * 1024 * 1024; + + /// The longest time spent waiting for the full collections, in milliseconds. + private const int PressureTimeoutMilliseconds = 3000; + + /// A window long enough that a throttled view never drains during a test. + private static readonly TimeSpan NeverDrains = TimeSpan.FromHours(1); + + /// The block most recently allocated while applying memory pressure. + private static byte[]? _pressure; + + /// Which view is built. + public enum ViewCase + { + /// A filtered view over a reactive list. + FilteredOverList = 0, + + /// A dynamic filtered view over a reactive list. + DynamicFilteredOverList = 1, + + /// A sorted view over a reactive list. + SortedOverList = 2, + + /// A grouped view over a reactive list. + GroupedOverList = 3, + + /// A dynamic view over a reactive list. + DynamicOverList = 4, + + /// A view over the stream of a reactive list. + StreamOverList = 5, + + /// A dynamic view over a quaternary list. + DynamicOverQuaternaryList = 6, + + /// A secondary index view over a quaternary list. + IndexedOverQuaternaryList = 7, + + /// A dynamic secondary index view over a quaternary list. + DynamicIndexedOverQuaternaryList = 8, + + /// A dynamic view over a quaternary dictionary. + DynamicOverDictionary = 9, + + /// A secondary index view over a quaternary dictionary. + IndexedOverDictionary = 10, + + /// A dynamic secondary index view over a quaternary dictionary. + DynamicIndexedOverDictionary = 11, + } + + /// Changes a source and owns what it needs. + private interface ISourceDriver : IDisposable + { + /// Adds an item. + /// The item. + void Add(Tracked item); + + /// Adds items in one batch. + /// The items. + void AddRange(Tracked[] items); + + /// Removes an item. + /// The item. + void Remove(Tracked item); + + /// Removes items in one batch. + /// The items. + void RemoveRange(Tracked[] items); + } + + /// Verifies a disposed view and every removed item are released, whether the view applied changes or still held them queued. + /// The view under test. + /// Whether the view coalesces for so long that it never applies a change. + /// A task representing the asynchronous test. + [Test] + [Arguments(ViewCase.FilteredOverList, false)] + [Arguments(ViewCase.FilteredOverList, true)] + [Arguments(ViewCase.DynamicFilteredOverList, false)] + [Arguments(ViewCase.DynamicFilteredOverList, true)] + [Arguments(ViewCase.SortedOverList, false)] + [Arguments(ViewCase.SortedOverList, true)] + [Arguments(ViewCase.GroupedOverList, false)] + [Arguments(ViewCase.GroupedOverList, true)] + [Arguments(ViewCase.DynamicOverList, false)] + [Arguments(ViewCase.DynamicOverList, true)] + [Arguments(ViewCase.StreamOverList, false)] + [Arguments(ViewCase.StreamOverList, true)] + [Arguments(ViewCase.DynamicOverQuaternaryList, false)] + [Arguments(ViewCase.DynamicOverQuaternaryList, true)] + [Arguments(ViewCase.IndexedOverQuaternaryList, false)] + [Arguments(ViewCase.IndexedOverQuaternaryList, true)] + [Arguments(ViewCase.DynamicIndexedOverQuaternaryList, false)] + [Arguments(ViewCase.DynamicIndexedOverQuaternaryList, true)] + [Arguments(ViewCase.DynamicOverDictionary, false)] + [Arguments(ViewCase.DynamicOverDictionary, true)] + [Arguments(ViewCase.IndexedOverDictionary, false)] + [Arguments(ViewCase.IndexedOverDictionary, true)] + [Arguments(ViewCase.DynamicIndexedOverDictionary, false)] + [Arguments(ViewCase.DynamicIndexedOverDictionary, true)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task DisposedView_IsReleasedWithItsRemovedItems(ViewCase viewCase, bool queued) => + AssertReleasedAsync(viewCase, queued ? NeverDrains : TimeSpan.Zero); + + /// Gets whether an item has an even identifier. + /// The item. + /// for even identifiers. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool IsEven(Tracked item) => (item.Id & 1) == 0; + + /// Gets whether a dictionary entry has an even identifier. + /// The entry. + /// for even identifiers. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool PairIsEven(KeyValuePair pair) => IsEven(pair.Value); + + /// Gets the parity of an item. + /// The item. + /// The parity. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int ParityOf(Tracked item) => item.Id & 1; + + /// Gets the group of an item. + /// The item. + /// The group. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int GroupOf(Tracked item) => item.Id % GroupCount; + + /// Creates tracked items with consecutive identifiers. + /// The first identifier. + /// The number of items. + /// The items. + private static Tracked[] Items(int first, int count) + { + var items = new Tracked[count]; + for (var i = 0; i < count; i++) + { + items[i] = new(first + i); + } + + return items; + } + + /// Builds a view and the driver for its source. + /// The view to build. + /// The coalescing window. + /// The run. + private static Run Create(ViewCase viewCase, TimeSpan throttle) + { + switch (viewCase) + { + case ViewCase.FilteredOverList: + { + var list = new ReactiveList(); + var view = new FilteredReactiveView(list, IsEven, Sequencer.Immediate, throttle); + return new(view, view, view.Items, new ListDriver(list, null)); + } + + case ViewCase.DynamicFilteredOverList: + { + var list = new ReactiveList(); + var filters = new BehaviorSignal>(IsEven); + var view = new DynamicFilteredReactiveView(list, filters, Sequencer.Immediate, throttle); + return new(view, view, view.Items, new ListDriver(list, filters)); + } + + case ViewCase.SortedOverList: + { + var list = new ReactiveList(); + var view = new SortedReactiveView(list, new TrackedComparer(), Sequencer.Immediate, throttle); + return new(view, view, view.Items, new ListDriver(list, null)); + } + + case ViewCase.GroupedOverList: + { + var list = new ReactiveList(); + var view = new GroupedReactiveView(list, GroupOf, Sequencer.Immediate, throttle); + return new(view, view, view.Groups, new ListDriver(list, null)); + } + + case ViewCase.DynamicOverList: + { + var list = new ReactiveList(); + var filters = new BehaviorSignal>(IsEven); + var view = new DynamicReactiveView(list, filters, throttle, Sequencer.Immediate); + return new(view, view, view.Items, new ListDriver(list, filters)); + } + + case ViewCase.StreamOverList: + { + var list = new ReactiveList(); + var view = new ReactiveView(list.Stream, [], IsEven, throttle, Sequencer.Immediate); + return new(view, view, view.Items, new ListDriver(list, null)); + } + + default: + { + return CreateQuaternary(viewCase, throttle); + } + } + } + + /// Builds a view over a quaternary source and the driver for it. + /// The view to build. + /// The coalescing window. + /// The run. + private static Run CreateQuaternary(ViewCase viewCase, TimeSpan throttle) + { + var throttleMs = (int)throttle.TotalMilliseconds; + switch (viewCase) + { + case ViewCase.DynamicOverQuaternaryList: + { + var list = new QuaternaryList(); + var filters = new BehaviorSignal>(IsEven); + var view = new DynamicReactiveView(list, filters, throttle, Sequencer.Immediate); + return new(view, view, view.Items, new QuaternaryListDriver(list, filters)); + } + + case ViewCase.IndexedOverQuaternaryList: + { + var list = new QuaternaryList(); + list.AddIndex(IndexName, ParityOf); + var view = list.CreateViewBySecondaryIndex(IndexName, 0, Sequencer.Immediate, throttleMs); + return new(view, view, view.Items, new QuaternaryListDriver(list, null)); + } + + case ViewCase.DynamicIndexedOverQuaternaryList: + { + var list = new QuaternaryList(); + list.AddIndex(IndexName, ParityOf); + var keys = new BehaviorSignal([0]); + var view = new DynamicSecondaryIndexReactiveView(list, IndexName, keys, Sequencer.Immediate, throttle); + return new(view, view, view.Items, new QuaternaryListDriver(list, keys)); + } + + case ViewCase.DynamicOverDictionary: + { + var dictionary = new QuaternaryDictionary(); + var filters = new BehaviorSignal, bool>>(PairIsEven); + var view = new DynamicReactiveView>(dictionary, filters, throttle, Sequencer.Immediate); + return new(view, view, view.Items, new DictionaryDriver(dictionary, filters)); + } + + case ViewCase.IndexedOverDictionary: + { + var dictionary = new QuaternaryDictionary(); + dictionary.AddValueIndex(IndexName, ParityOf); + var view = dictionary.CreateViewBySecondaryIndex(IndexName, 0, Sequencer.Immediate, throttleMs); + return new(view, view, view.Items, new DictionaryDriver(dictionary, null)); + } + + default: + { + var dictionary = new QuaternaryDictionary(); + dictionary.AddValueIndex(IndexName, ParityOf); + var keys = new BehaviorSignal([0]); + var view = DynamicSecondaryIndexDictionaryReactiveView.Create(dictionary, IndexName, keys, Sequencer.Immediate, throttle); + return new(view, view, view.Items, new DictionaryDriver(dictionary, keys)); + } + } + } + + /// Drives a view through its life and returns only weak references to what must be released. + /// The view to build. + /// The coalescing window. + /// The outcome. + [MethodImpl(MethodImplOptions.NoInlining)] + private static Outcome Execute(ViewCase viewCase, TimeSpan throttle) + { + var run = Create(viewCase, throttle); + var events = 0; + run.Notifier.PropertyChanged += (_, _) => Interlocked.Increment(ref events); + run.Items.CollectionChanged += (_, _) => Interlocked.Increment(ref events); + + var seed = Items(0, SeedCount); + run.Driver.AddRange(seed); + var singles = Items(SeedCount, SeedCount / GroupCount); + for (var i = 0; i < singles.Length; i++) + { + run.Driver.Add(singles[i]); + } + + var batch = Items(BatchFirst, BatchCount); + run.Driver.AddRange(batch); + var removed = new List(); + RemoveEach(run, removed, seed[3], seed[4], batch[1]); + RemoveTogether(run, removed, batch[2], batch[3], batch[4], batch[5]); + + var view = new WeakReference(run.View); + var items = new WeakReference(run.Items); + run.View.Dispose(); + var atDispose = Volatile.Read(ref events); + + var late = Items(LateFirst, SeedCount); + run.Driver.AddRange(late); + run.Driver.Add(new(LateSingle)); + RemoveEach(run, removed, late[1], seed[5]); + RemoveTogether(run, removed, late[2], late[3], late[4]); + + // The reactive list keeps the items of its most recent batch removal, so an untracked batch replaces it and the + // assertions below speak about the view rather than the list. + var flush = Items(FlushFirst, FlushCount); + run.Driver.AddRange(flush); + run.Driver.RemoveRange(flush); + + return new(run.Driver, view, items, [.. removed], atDispose, () => Volatile.Read(ref events)); + } + + /// Removes items one at a time and tracks them weakly. + /// The run. + /// Receives the weak references. + /// The items to remove. + private static void RemoveEach(Run run, List removed, params Tracked[] items) + { + for (var i = 0; i < items.Length; i++) + { + removed.Add(new(items[i])); + run.Driver.Remove(items[i]); + } + } + + /// Removes items in one batch and tracks them weakly. + /// The run. + /// Receives the weak references. + /// The items to remove. + private static void RemoveTogether(Run run, List removed, params Tracked[] items) + { + for (var i = 0; i < items.Length; i++) + { + removed.Add(new(items[i])); + } + + run.Driver.RemoveRange(items); + } + + /// Counts the weakly held objects that are still reachable. + /// The outcome. + /// The number of survivors, with the view and its collection counted first. + private static string Survivors(Outcome outcome) + { + var survivors = new System.Text.StringBuilder(); + if (outcome.View.IsAlive) + { + _ = survivors.Append("view "); + } + + if (outcome.Items.IsAlive) + { + _ = survivors.Append("items "); + } + + for (var i = 0; i < outcome.Removed.Length; i++) + { + if (outcome.Removed[i].IsAlive) + { + _ = survivors.Append("removed").Append(i).Append(' '); + } + } + + return survivors.ToString(); + } + + /// Allocates large blocks until the runtime has collected everything unreachable or the time runs out. + /// The outcome whose weak references are watched. + private static void CollectByPressure(Outcome outcome) + { + var start = Stopwatch.GetTimestamp(); + while (Survivors(outcome).Length != 0 && Stopwatch.GetElapsedTime(start).TotalMilliseconds < PressureTimeoutMilliseconds) + { + Volatile.Write(ref _pressure, new byte[PressureBlockSize]); + } + + Volatile.Write(ref _pressure, null); + } + + /// Runs a scenario and asserts the disposed view and every removed item were released. + /// The view to build. + /// The coalescing window. + /// A task representing the asynchronous test. + private static async Task AssertReleasedAsync(ViewCase viewCase, TimeSpan throttle) + { + var outcome = Execute(viewCase, throttle); + CollectByPressure(outcome); + var leakedItems = Survivors(outcome); + + await Assert.That(leakedItems).IsEqualTo(string.Empty); + await Assert.That(outcome.EventsNow()).IsEqualTo(outcome.EventsAtDispose); + outcome.Driver.Dispose(); + } + + /// Changes a reactive list. + /// The list. + /// A signal that feeds the view, or . + private sealed class ListDriver(ReactiveList list, IDisposable? signal) : ISourceDriver + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(Tracked item) => list.Add(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddRange(Tracked[] items) => list.AddRange(items.AsEnumerable()); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Remove(Tracked item) => _ = list.Remove(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RemoveRange(Tracked[] items) => list.Remove(items.AsEnumerable()); + + /// + public void Dispose() + { + signal?.Dispose(); + list.Dispose(); + } + } + + /// Changes a quaternary list. + /// The list. + /// A signal that feeds the view, or . + private sealed class QuaternaryListDriver(QuaternaryList list, IDisposable? signal) : ISourceDriver + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(Tracked item) => list.Add(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void AddRange(Tracked[] items) => list.AddRange(items); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Remove(Tracked item) => _ = list.Remove(item); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void RemoveRange(Tracked[] items) => list.RemoveRange(items); + + /// + public void Dispose() + { + signal?.Dispose(); + list.Dispose(); + } + } + + /// Changes a quaternary dictionary keyed by identifier. + /// The dictionary. + /// A signal that feeds the view, or . + private sealed class DictionaryDriver(QuaternaryDictionary dictionary, IDisposable? signal) : ISourceDriver + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Add(Tracked item) => dictionary.AddOrUpdate(item.Id, item); + + /// + public void AddRange(Tracked[] items) + { + var pairs = new KeyValuePair[items.Length]; + for (var i = 0; i < items.Length; i++) + { + pairs[i] = new(items[i].Id, items[i]); + } + + dictionary.AddRange(pairs); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Remove(Tracked item) => _ = dictionary.Remove(item.Id); + + /// + public void RemoveRange(Tracked[] items) + { + var keys = new int[items.Length]; + for (var i = 0; i < items.Length; i++) + { + keys[i] = items[i].Id; + } + + dictionary.RemoveKeys(keys); + } + + /// + public void Dispose() + { + signal?.Dispose(); + dictionary.Dispose(); + } + } + + /// Orders items by identifier. + private sealed class TrackedComparer : IComparer + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Compare(Tracked? x, Tracked? y) => (x?.Id ?? 0).CompareTo(y?.Id ?? 0); + } + + /// An item whose lifetime is observed. + /// The identifier. + private sealed record Tracked(int Id); + + /// A view with the driver that changes its source. + /// The view. + /// The view's property notifications. + /// The view's collection notifications. + /// The driver. + private sealed record Run(IDisposable View, INotifyPropertyChanged Notifier, INotifyCollectionChanged Items, ISourceDriver Driver); + + /// What a scenario leaves behind. + /// The driver, which keeps the source alive. + /// The disposed view. + /// The disposed view's collection. + /// The items removed from the source. + /// The notifications seen when the view was disposed. + /// Reads the notifications seen so far. + private sealed record Outcome( + ISourceDriver Driver, + WeakReference View, + WeakReference Items, + WeakReference[] Removed, + int EventsAtDispose, + Func EventsNow); +} diff --git a/src/tests/ReactiveList.Tests/ViewSourceDisposalTests.cs b/src/tests/ReactiveList.Tests/ViewSourceDisposalTests.cs new file mode 100644 index 00000000..a2b7710c --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewSourceDisposalTests.cs @@ -0,0 +1,148 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies a view whose versioned source is disposed before the view drains stops quietly instead of failing on the scheduler thread. +public sealed class ViewSourceDisposalTests +{ + /// The name of the parity index. + private const string IndexName = "parity"; + + /// The index key the dictionary view selects. + private const int OddKey = 1; + + /// The divisor of the index. + private const int IndexKeyCount = 2; + + /// The items the source holds when a view is built. + private static readonly int[] Existing = [1, 3, 5]; + + /// The view kinds over a list source. + public enum ListViewKind + { + /// A filtered engine. + Filtered = 0, + + /// A sorted engine. + Sorted = 1, + + /// A grouped engine. + Grouped = 2, + + /// A view over a source. + SourceView = 3, + } + + /// A list view keeps its items and raises nothing when the list is disposed before the drain that needs a source read. + /// The view kind. + /// A task representing the asynchronous test. + [Test] + [Arguments(ListViewKind.Filtered)] + [Arguments(ListViewKind.Sorted)] + [Arguments(ListViewKind.Grouped)] + [Arguments(ListViewKind.SourceView)] + public async Task ListSourceDisposedBeforeDrain_ViewStopsQuietly(ListViewKind kind) + { + var inner = new QuaternaryList(); + inner.AddRange(Existing); + var source = new VersionedCountingSource(inner); + var sequencer = new ControllableSequencer(); + using var probe = CreateProbe(kind, source, sequencer); + var events = 0; + probe.Collection.CollectionChanged += (_, _) => Interlocked.Increment(ref events); + var countBefore = probe.Count(); + + using var delivered = new ManualResetEventSlim(); + using var watch = inner.VersionedStream.Subscribe(_ => delivered.Set()); + inner.Edit(static items => items.Add(Existing.Length)); + await TestWaitHelpers.WaitUntilAsync(() => delivered.IsSet); + + inner.Dispose(); + sequencer.RunAll(); + + await Assert.That(probe.Count()).IsEqualTo(countBefore); + await Assert.That(Volatile.Read(ref events)).IsEqualTo(0); + await Assert.That(source.ActiveSubscriptions).IsEqualTo(0); + } + + /// A secondary index view keeps its items and raises nothing when the dictionary is disposed before the drain. + /// A task representing the asynchronous test. + [Test] + public async Task DictionarySourceDisposedBeforeDrain_ViewStopsQuietly() + { + var dictionary = new QuaternaryDictionary(); + dictionary.AddValueIndex(IndexName, static value => value % IndexKeyCount); + foreach (var value in Existing) + { + dictionary.AddOrUpdate(value, value); + } + + var sequencer = new ControllableSequencer(); + using var view = SecondaryIndexReactiveView.Create(dictionary, IndexName, OddKey, sequencer, TimeSpan.Zero); + var events = 0; + ((INotifyCollectionChanged)view.Items).CollectionChanged += (_, _) => Interlocked.Increment(ref events); + var countBefore = view.Count; + + using var delivered = new ManualResetEventSlim(); + using var watch = dictionary.VersionedStream.Subscribe(_ => delivered.Set()); + dictionary.Edit(static items => items[1] = Existing.Length); + await TestWaitHelpers.WaitUntilAsync(() => delivered.IsSet); + + dictionary.Dispose(); + sequencer.RunAll(); + + await Assert.That(view.Count).IsEqualTo(countBefore); + await Assert.That(Volatile.Read(ref events)).IsEqualTo(0); + } + + /// Builds a view of a kind. + /// The view kind. + /// The source. + /// The scheduler that applies changes. + /// The probe over the view. + private static ViewProbe CreateProbe(ListViewKind kind, VersionedCountingSource source, ISequencer sequencer) + { + switch (kind) + { + case ListViewKind.Filtered: + { + var engine = new FilteredViewEngine(source, static _ => true); + engine.Start(TimeSpan.Zero, sequencer); + return new(engine, engine.Filtered, () => engine.Filtered.Count); + } + + case ListViewKind.Sorted: + { + var engine = new SortedViewEngine(source, Comparer.Default); + engine.Start(TimeSpan.Zero, sequencer); + return new(engine, engine.Sorted, () => engine.Sorted.Count); + } + + case ListViewKind.Grouped: + { + var engine = new GroupedViewEngine(source, static value => value); + engine.Start(TimeSpan.Zero, sequencer); + return new(engine, engine.Groups, () => engine.Groups.Count); + } + + default: + { + var view = new ReactiveView(source, static _ => true, TimeSpan.Zero, sequencer); + return new(view, view.Items, () => view.Items.Count); + } + } + } + + /// A view under test with the collection it publishes. + /// The view, disposed after the test. + /// The collection whose changes are counted. + /// Reads the number of items. + private sealed record ViewProbe(IDisposable View, INotifyCollectionChanged Collection, Func Count) : IDisposable + { + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Dispose() => View.Dispose(); + } +} diff --git a/src/tests/ReactiveList.Tests/ViewSourceRulesTests.cs b/src/tests/ReactiveList.Tests/ViewSourceRulesTests.cs new file mode 100644 index 00000000..8300e278 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewSourceRulesTests.cs @@ -0,0 +1,106 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies how retries a copy that fails because the source changed. +public sealed class ViewSourceRulesTests +{ + /// The value a reset batch carries. + private const int Copied = 7; + + /// The number of changes a one item reset becomes. + private const int ChangeCount = 2; + + /// The kinds of failure a concurrent change can cause while a source is copied. + public enum CopyFailure + { + /// The source changed size during the copy. + Argument = 0, + + /// The source was modified during enumeration. + InvalidOperation = 1, + + /// The source shrank between sizing the copy and filling it. + IndexOutOfRange = 2, + } + + /// Verifies a copy that fails once because the source changed is retried and returns the items. + /// The failure the first copy throws. + /// A task representing the asynchronous test. + [Test] + [Arguments(CopyFailure.Argument)] + [Arguments(CopyFailure.InvalidOperation)] + [Arguments(CopyFailure.IndexOutOfRange)] + public async Task ReadSource_FirstCopyFails_RetriesAndReturnsTheItems(CopyFailure failure) + { + using var source = new ScriptedViewSource(); + source.Add(1); + source.OnCopy = () => Fail(failure); + + var items = ViewSourceRules.ReadSource(source); + + await Assert.That(items).IsEquivalentTo([1], CollectionOrdering.Matching); + } + + /// Verifies a copy that keeps failing lets the exception surface on the last attempt. + /// A task representing the asynchronous test. + [Test] + public async Task CopyWithRetry_AlwaysFails_Throws() => + await Assert.That(static () => ViewSourceRules.CopyWithRetry(0, static _ => throw new ArgumentException("changed"))).Throws(); + + /// Verifies a reset notification without a batch is dropped by the filter. + /// A task representing the asynchronous test. + [Test] + public async Task FilterNotification_ResetWithoutBatch_IsDropped() + { + CacheNotify reset = new(CacheAction.Reset, default); + + await Assert.That(ReactiveListExtensions.FilterNotification(reset, static _ => true)).IsNull(); + } + + /// Verifies a reset batch becomes a clear followed by one addition per item. + /// A task representing the asynchronous test. + [Test] + public async Task ToResetChanges_Batch_ClearsThenAddsEveryItem() + { + var items = ArrayPool.Shared.Rent(1); + items[0] = Copied; + using PooledBatch batch = new(items, 1); + + var changes = CacheNotifyExtensions.ToResetChanges(batch); + + await Assert.That(changes.Count).IsEqualTo(ChangeCount); + await Assert.That(changes[0].Reason).IsEqualTo(ChangeReason.Clear); + await Assert.That(changes[1].Current).IsEqualTo(Copied); + } + + /// Throws the exception of a failure kind. + /// The failure kind. + /// The failure kind is . + /// The failure kind is . + private static void Fail(CopyFailure failure) + { + switch (failure) + { + case CopyFailure.Argument: + { + throw new ArgumentException("The source changed size."); + } + + case CopyFailure.InvalidOperation: + { + throw new InvalidOperationException("The source was modified."); + } + + default: + { + // The runtime raises this when an array read lands past the end, which is what a shrinking source causes. + int[] values = []; + _ = values[values.Length]; + break; + } + } + } +} diff --git a/src/tests/ReactiveList.Tests/ViewStartTests.cs b/src/tests/ReactiveList.Tests/ViewStartTests.cs new file mode 100644 index 00000000..bece74d5 --- /dev/null +++ b/src/tests/ReactiveList.Tests/ViewStartTests.cs @@ -0,0 +1,95 @@ +// 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. + +namespace ReactiveList.Tests; + +/// Verifies a view does not lose changes made, or drains requested, before it starts observing. +public sealed class ViewStartTests +{ + /// The value added between the initial copy and the subscription. + private const int InTheGap = 9; + + /// The items the source holds when a view is built. + private static readonly int[] Existing = [1, 2]; + + /// The items expected once the value in the gap is included. + private static readonly int[] WithGap = [1, 2, InTheGap]; + + /// The engines checked. + public enum EngineKind + { + /// A filtered engine. + Filtered = 0, + + /// A sorted engine. + Sorted = 1, + + /// A grouped engine. + Grouped = 2, + } + + /// A change that lands after a non-versioned source was copied and before the view subscribed is not lost. + /// The engine kind. + /// A task representing the asynchronous test. + [Test] + [Arguments(EngineKind.Filtered)] + [Arguments(EngineKind.Sorted)] + [Arguments(EngineKind.Grouped)] + public async Task Start_NonVersionedSourceChangedAfterCopy_IncludesTheChange(EngineKind kind) + { + using var inner = new QuaternaryList(); + inner.AddRange(Existing); + using var source = new LiveQueryCountingSource(inner); + + int[] items; + switch (kind) + { + case EngineKind.Filtered: + { + using var engine = new FilteredViewEngine(source, static _ => true); + inner.Add(InTheGap); + engine.Start(TimeSpan.Zero, Sequencer.Immediate); + items = ViewFuzzSupport.Sorted(engine.Filtered); + break; + } + + case EngineKind.Sorted: + { + using var engine = new SortedViewEngine(source, Comparer.Default); + inner.Add(InTheGap); + engine.Start(TimeSpan.Zero, Sequencer.Immediate); + items = ViewFuzzSupport.Sorted(engine.Sorted); + break; + } + + default: + { + using var engine = new GroupedViewEngine(source, static value => value); + inner.Add(InTheGap); + engine.Start(TimeSpan.Zero, Sequencer.Immediate); + items = ViewFuzzSupport.Sorted(engine.SnapshotKeys()); + break; + } + } + + await Assert.That(items).IsEquivalentTo(WithGap, CollectionOrdering.Matching); + } + + /// A filter queued before the view started is applied by the first drain. + /// A task representing the asynchronous test. + [Test] + public async Task Start_FilterQueuedBeforeStart_IsApplied() + { + using var inner = new QuaternaryList(); + inner.AddRange(Existing); + using var engine = new FilteredViewEngine(inner, static _ => true); + var sequencer = new ControllableSequencer(); + + engine.SetFilter(static value => value == 1); + engine.Start(TimeSpan.Zero, sequencer); + sequencer.RunAll(); + + await Assert.That(engine.Filtered.Count).IsEqualTo(1); + } +} diff --git a/src/tests/ReactiveListTestApp.Tests/FilteredReactiveViewTests.cs b/src/tests/ReactiveListTestApp.Tests/FilteredReactiveViewTests.cs index a9470816..7422053c 100644 --- a/src/tests/ReactiveListTestApp.Tests/FilteredReactiveViewTests.cs +++ b/src/tests/ReactiveListTestApp.Tests/FilteredReactiveViewTests.cs @@ -109,10 +109,10 @@ public async Task EqualReferenceReplacement_PreservesSourceIdentity() await Assert.That(view[0]).IsSameReferenceAs(replacement); } - /// Preserves incremental append-on-membership behavior after a queued move. + /// Places an item that gains membership after a queued move at its source position. /// A task representing the asynchronous test. [Test] - public async Task MoveThenMembershipUpdate_PreservesIncrementalInsertionOrder() + public async Task MoveThenMembershipUpdate_KeepsSourceOrder() { using var source = new ReactiveList(MembershipSource); var scheduler = new QueuedViewSequencer(); @@ -124,8 +124,10 @@ public async Task MoveThenMembershipUpdate_PreservesIncrementalInsertionOrder() scheduler.RunAll(); await Assert.That(view.Count).IsEqualTo(ParityDivisor); - await Assert.That(view[0]).IsEqualTo(FourthItem); - await Assert.That(view[1]).IsEqualTo(SixthItem); + + // The source ends as 6, 5, 4, so the view lists 6 before 4. + await Assert.That(view[0]).IsEqualTo(SixthItem); + await Assert.That(view[1]).IsEqualTo(FourthItem); } /// Does not replay pending additions over an explicit live-source refresh.