Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,46 @@ public static IAsyncEnumerable<TItem> UseMaterializedAsyncEnumerable<TItem>(
}
#endif

/// <summary>
/// Gets the item at the <paramref name="index" /> of the <paramref name="materialized" /> sequence, and returns
/// <see langword="false" /> when it has fewer items.
/// </summary>
/// <remarks>
/// A sequence from <see cref="UseMaterializedEnumerable{TItem}(IEvaluationContext, IEnumerable{TItem})" /> 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 <paramref name="index" />.
/// </remarks>
/// <exception cref="ArgumentNullException">The <paramref name="materialized" /> sequence is <see langword="null" />.</exception>
/// <exception cref="ArgumentOutOfRangeException">The <paramref name="index" /> is negative.</exception>
public static bool TryGetItem<TItem>(this IMaterializedEnumerable<TItem> 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<TItem> 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;
}

/// <summary>
/// Gets the current timestamp on the clock of the evaluation, from which
/// <see cref="GetElapsedTime(IEvaluationContext, long)" /> measures.
Expand Down
22 changes: 22 additions & 0 deletions Source/aweXpect.Core/Core/Helpers/MaterializingEnumerable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,28 @@ private bool MoveNext()
return false;
}

/// <summary>
/// Gets the item at the <paramref name="index" />, reading the source only as far as needed.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
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();
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#nullable enable
static aweXpect.Core.EvaluationContext.EvaluationContextExtensions.TryGetItem<TItem>(this aweXpect.Core.EvaluationContext.IMaterializedEnumerable<TItem>! materialized, int index, out TItem item) -> bool
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#nullable enable
static aweXpect.Core.EvaluationContext.EvaluationContextExtensions.TryGetItem<TItem>(this aweXpect.Core.EvaluationContext.IMaterializedEnumerable<TItem>! materialized, int index, out TItem item) -> bool
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#nullable enable
static aweXpect.Core.EvaluationContext.EvaluationContextExtensions.TryGetItem<TItem>(this aweXpect.Core.EvaluationContext.IMaterializedEnumerable<TItem>! materialized, int index, out TItem item) -> bool
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<int> materialized =
(IMaterializedEnumerable<int>)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<int> materialized =
(IMaterializedEnumerable<int>)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<int> materialized =
(IMaterializedEnumerable<int>)context.UseMaterializedEnumerable(ToEnumerable(2, 4));

void Act() => materialized.TryGetItem(-1, out _);

await That(Act).Throws<ArgumentOutOfRangeException>()
.WithParamName("index").And
.WithMessage("The index must not be negative.").AsPrefix();
}

[Test]
public async Task TryGetItem_WhenMaterializedIsNull_ShouldThrowArgumentNullException()
{
IMaterializedEnumerable<int> materialized = null!;

void Act() => materialized.TryGetItem(0, out _);

await That(Act).Throws<ArgumentNullException>()
.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<int> materialized =
(IMaterializedEnumerable<int>)context.UseMaterializedEnumerable(new DisposeTrackingEnumerable(exception, 1));

Exception? fromTryGetItem = Catch(() => materialized.TryGetItem(1, out _));
Exception? fromEnumeration = Catch(() => _ = materialized.ToList());

await That(fromTryGetItem).Is<UserCodeException>()
.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()
Expand Down Expand Up @@ -508,6 +598,19 @@ await That(Act).Throws<ArgumentOutOfRangeException>()
.WithParamName("amount");
}

private static Exception? Catch(Action action)
{
try
{
action();
return null;
}
catch (Exception exception)
{
return exception;
}
}

private static IEnumerable<T> ToEnumerable<T>(params T[] items)
{
foreach (T item in items)
Expand Down Expand Up @@ -538,6 +641,17 @@ private sealed class AlwaysEqualEnumerable(params int[] items) : IEnumerable<int
public override int GetHashCode() => 0;
}

private sealed class ForeignMaterializedEnumerable(params int[] items) : IMaterializedEnumerable<int>
{
public int? Count => null;

public IReadOnlyList<int> MaterializedItems => [];

public IEnumerator<int> GetEnumerator() => items.AsEnumerable().GetEnumerator();

IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

private sealed class OneShotEnumerable(params int[] items) : IEnumerable<int>
{
public int Enumerations { get; private set; }
Expand Down
Loading