diff --git a/Source/aweXpect.Core/Core/EvaluationContext/EvaluationContextExtensions.cs b/Source/aweXpect.Core/Core/EvaluationContext/EvaluationContextExtensions.cs index d11f620840..4c4cb95810 100644 --- a/Source/aweXpect.Core/Core/EvaluationContext/EvaluationContextExtensions.cs +++ b/Source/aweXpect.Core/Core/EvaluationContext/EvaluationContextExtensions.cs @@ -105,6 +105,46 @@ public static IAsyncEnumerable UseMaterializedAsyncEnumerable( } #endif + /// + /// Gets the item at the of the sequence, and returns + /// when it has fewer items. + /// + /// + /// A sequence from reads + /// its source only as far as needed and without an enumerator, so that a loop over the positions is cheaper than + /// enumerating it. An exception of the source is thrown like by an enumeration. Another implementation is + /// enumerated up to the . + /// + /// The sequence is . + /// The is negative. + public static bool TryGetItem(this IMaterializedEnumerable materialized, int index, out TItem item) + { + materialized.ThrowIfNull(); + if (index < 0) + { + throw Tracing.WriteException( + new ArgumentOutOfRangeException(nameof(index), "The index must not be negative.")); + } + + if (materialized is MaterializingEnumerable materializing) + { + return materializing.TryGetItem(index, out item); + } + + int position = 0; + foreach (TItem current in materialized) + { + if (position++ == index) + { + item = current; + return true; + } + } + + item = default!; + return false; + } + /// /// Gets the current timestamp on the clock of the evaluation, from which /// measures. diff --git a/Source/aweXpect.Core/Core/Helpers/MaterializingEnumerable.cs b/Source/aweXpect.Core/Core/Helpers/MaterializingEnumerable.cs index 756c7e670b..fa3d56621d 100644 --- a/Source/aweXpect.Core/Core/Helpers/MaterializingEnumerable.cs +++ b/Source/aweXpect.Core/Core/Helpers/MaterializingEnumerable.cs @@ -89,6 +89,28 @@ private bool MoveNext() return false; } + /// + /// Gets the item at the , reading the source only as far as needed. + /// + /// + /// Reads the items without an enumerator, so that a consumer that knows the position of the next item, e.g. a + /// counting loop, avoids the overhead of one. + /// + internal bool TryGetItem(int index, out T item) + { + while (index >= _materializedItems.Count) + { + if (!MoveNext()) + { + item = default!; + return false; + } + } + + item = _materializedItems[index]; + return true; + } + private bool ReadNextItem() { _enumerator ??= _enumerable.GetEnumerator(); diff --git a/Source/aweXpect.Core/PublicAPI/net10.0/PublicAPI.Unshipped.txt b/Source/aweXpect.Core/PublicAPI/net10.0/PublicAPI.Unshipped.txt index 7dc5c58110..c4a8f44c12 100644 --- a/Source/aweXpect.Core/PublicAPI/net10.0/PublicAPI.Unshipped.txt +++ b/Source/aweXpect.Core/PublicAPI/net10.0/PublicAPI.Unshipped.txt @@ -1 +1,2 @@ #nullable enable +static aweXpect.Core.EvaluationContext.EvaluationContextExtensions.TryGetItem(this aweXpect.Core.EvaluationContext.IMaterializedEnumerable! materialized, int index, out TItem item) -> bool diff --git a/Source/aweXpect.Core/PublicAPI/net8.0/PublicAPI.Unshipped.txt b/Source/aweXpect.Core/PublicAPI/net8.0/PublicAPI.Unshipped.txt index 7dc5c58110..c4a8f44c12 100644 --- a/Source/aweXpect.Core/PublicAPI/net8.0/PublicAPI.Unshipped.txt +++ b/Source/aweXpect.Core/PublicAPI/net8.0/PublicAPI.Unshipped.txt @@ -1 +1,2 @@ #nullable enable +static aweXpect.Core.EvaluationContext.EvaluationContextExtensions.TryGetItem(this aweXpect.Core.EvaluationContext.IMaterializedEnumerable! materialized, int index, out TItem item) -> bool diff --git a/Source/aweXpect.Core/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt b/Source/aweXpect.Core/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt index 7dc5c58110..c4a8f44c12 100644 --- a/Source/aweXpect.Core/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt +++ b/Source/aweXpect.Core/PublicAPI/netstandard2.0/PublicAPI.Unshipped.txt @@ -1 +1,2 @@ #nullable enable +static aweXpect.Core.EvaluationContext.EvaluationContextExtensions.TryGetItem(this aweXpect.Core.EvaluationContext.IMaterializedEnumerable! materialized, int index, out TItem item) -> bool diff --git a/Tests/aweXpect.Core.Tests/Core/EvaluationContext/EvaluationContextExtensionsTests.cs b/Tests/aweXpect.Core.Tests/Core/EvaluationContext/EvaluationContextExtensionsTests.cs index 98485eeda8..eac02416c9 100644 --- a/Tests/aweXpect.Core.Tests/Core/EvaluationContext/EvaluationContextExtensionsTests.cs +++ b/Tests/aweXpect.Core.Tests/Core/EvaluationContext/EvaluationContextExtensionsTests.cs @@ -5,6 +5,7 @@ using System.Threading; using aweXpect.Chronology; using aweXpect.Core.EvaluationContext; +using aweXpect.Core.Helpers; using aweXpect.Core.Tests.TestHelpers; using aweXpect.Core.TimeSystem; using aweXpect.Signaling; @@ -46,6 +47,95 @@ await That(timestamp).IsGreaterThanOrEqualTo(before).And await That(elapsed).IsGreaterThanOrEqualTo(TimeSpan.Zero); } + [Test] + public async Task TryGetItem_BeyondTheLastItem_ShouldReturnFalse() + { + IEvaluationContext context = new Context(); + IMaterializedEnumerable materialized = + (IMaterializedEnumerable)context.UseMaterializedEnumerable(ToEnumerable(2, 4)); + + bool result = materialized.TryGetItem(2, out int item); + + await That(result).IsFalse(); + await That(item).IsEqualTo(0); + await That(materialized.Count).IsEqualTo(2) + .Because("the source was read to its end while searching the item"); + } + + [Test] + public async Task TryGetItem_ForAnotherImplementation_ShouldEnumerateItUpToTheIndex() + { + ForeignMaterializedEnumerable materialized = new(2, 4, 6); + + bool result = materialized.TryGetItem(1, out int item); + + await That(result).IsTrue(); + await That(item).IsEqualTo(4); + } + + [Test] + public async Task TryGetItem_ShouldReadTheSourceOnlyUpToTheIndex() + { + IEvaluationContext context = new Context(); + OneShotEnumerable source = new(2, 4, 6); + IMaterializedEnumerable materialized = + (IMaterializedEnumerable)context.UseMaterializedEnumerable(source); + + bool result = materialized.TryGetItem(1, out int item); + + await That(result).IsTrue(); + await That(item).IsEqualTo(4); + await That(materialized.MaterializedItems).IsEqualTo([2, 4,]) + .Because("only the items up to the index are read from the source"); + await That(materialized.ToList()).IsEqualTo([2, 4, 6,]) + .Because("an enumeration replays the read items and continues the source"); + await That(source.Enumerations).IsEqualTo(1); + } + + [Test] + public async Task TryGetItem_WhenIndexIsNegative_ShouldThrowArgumentOutOfRangeException() + { + IEvaluationContext context = new Context(); + IMaterializedEnumerable materialized = + (IMaterializedEnumerable)context.UseMaterializedEnumerable(ToEnumerable(2, 4)); + + void Act() => materialized.TryGetItem(-1, out _); + + await That(Act).Throws() + .WithParamName("index").And + .WithMessage("The index must not be negative.").AsPrefix(); + } + + [Test] + public async Task TryGetItem_WhenMaterializedIsNull_ShouldThrowArgumentNullException() + { + IMaterializedEnumerable materialized = null!; + + void Act() => materialized.TryGetItem(0, out _); + + await That(Act).Throws() + .WithParamName("materialized").And + .WithMessage("The 'materialized' cannot be null.").AsPrefix(); + } + + [Test] + public async Task TryGetItem_WhenTheSourceThrows_ShouldThrowLikeAnEnumeration() + { + IEvaluationContext context = new Context(); + InvalidOperationException exception = new("the source is broken"); + IMaterializedEnumerable materialized = + (IMaterializedEnumerable)context.UseMaterializedEnumerable(new DisposeTrackingEnumerable(exception, 1)); + + Exception? fromTryGetItem = Catch(() => materialized.TryGetItem(1, out _)); + Exception? fromEnumeration = Catch(() => _ = materialized.ToList()); + + await That(fromTryGetItem).Is() + .Whose(e => e.InnerException, inner => inner.IsSameAs(exception)) + .Because("an exception of the source fails the expectation like one of the subject"); + await That(fromEnumeration).IsSameAs(fromTryGetItem) + .Because("every further read throws the exception of the source again"); + } + #if NET8_0_OR_GREATER [Test] public async Task UseMaterializedAsyncEnumerable_ForDifferentSources_ShouldReturnDifferentInstances() @@ -508,6 +598,19 @@ await That(Act).Throws() .WithParamName("amount"); } + private static Exception? Catch(Action action) + { + try + { + action(); + return null; + } + catch (Exception exception) + { + return exception; + } + } + private static IEnumerable ToEnumerable(params T[] items) { foreach (T item in items) @@ -538,6 +641,17 @@ private sealed class AlwaysEqualEnumerable(params int[] items) : IEnumerable 0; } + private sealed class ForeignMaterializedEnumerable(params int[] items) : IMaterializedEnumerable + { + public int? Count => null; + + public IReadOnlyList MaterializedItems => []; + + public IEnumerator GetEnumerator() => items.AsEnumerable().GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + private sealed class OneShotEnumerable(params int[] items) : IEnumerable { public int Enumerations { get; private set; }