Skip to content

Commit 13c8c83

Browse files
Oraceatifaziz
authored andcommitted
Fix SkipUntil to not call MoveNext past end of sequence
This is a squashed merge of PR #666 that closes #664.
1 parent b94870c commit 13c8c83

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

MoreLinq.Test/SkipUntilTest.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
namespace MoreLinq.Test
1919
{
2020
using NUnit.Framework;
21+
using NUnit.Framework.Interfaces;
22+
using System.Collections.Generic;
2123

2224
[TestFixture]
2325
public class SkipUntilTest
@@ -57,5 +59,25 @@ public void SkipUntilEvaluatesPredicateLazily()
5759
var sequence = Enumerable.Range(-2, 5).SkipUntil(x => 1 / x == -1);
5860
sequence.AssertSequenceEqual(0, 1, 2);
5961
}
62+
63+
public static readonly IEnumerable<ITestCaseData> TestData =
64+
from e in new[]
65+
{
66+
new { Source = new int[0] , Min = 0, Expected = new int[0] }, // empty sequence
67+
new { Source = new[] { 0 }, Min = 0, Expected = new int[0] }, // one-item sequence, predicate succeed
68+
new { Source = new[] { 0 }, Min = 1, Expected = new int[0] }, // one-item sequence, predicate don't succeed
69+
new { Source = new[] { 1, 2, 3 }, Min = 0, Expected = new[] { 2, 3 } }, // predicate succeed on first item
70+
new { Source = new[] { 1, 2, 3 }, Min = 1, Expected = new[] { 2, 3 } },
71+
new { Source = new[] { 1, 2, 3 }, Min = 2, Expected = new[] { 3 } },
72+
new { Source = new[] { 1, 2, 3 }, Min = 3, Expected = new int[0] }, // predicate succeed on last item
73+
new { Source = new[] { 1, 2, 3 }, Min = 4, Expected = new int[0] } // predicate never succeed
74+
}
75+
select new TestCaseData(e.Source, e.Min).Returns(e.Expected);
76+
77+
[Test, TestCaseSource(nameof(TestData))]
78+
public int[] TestSkipUntil(int[] source, int min)
79+
{
80+
return source.AsTestingSequence().SkipUntil(v => v >= min).ToArray();
81+
}
6082
}
6183
}

MoreLinq/SkipUntil.cs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,16 +59,17 @@ public static IEnumerable<TSource> SkipUntil<TSource>(this IEnumerable<TSource>
5959

6060
return _(); IEnumerable<TSource> _()
6161
{
62-
using var iterator = source.GetEnumerator();
62+
using var enumerator = source.GetEnumerator();
6363

64-
while (iterator.MoveNext())
64+
do
6565
{
66-
if (predicate(iterator.Current))
67-
break;
66+
if (!enumerator.MoveNext())
67+
yield break;
6868
}
69+
while (!predicate(enumerator.Current));
6970

70-
while (iterator.MoveNext())
71-
yield return iterator.Current;
71+
while (enumerator.MoveNext())
72+
yield return enumerator.Current;
7273
}
7374
}
7475
}

0 commit comments

Comments
 (0)