Skip to content

Commit

Permalink
more robust slideby classifier function handling (#2642)
Browse files Browse the repository at this point in the history
When the classifier function is pure everything works fine, but with
state, `slideBy` might end up in an infinite loop. The reason: `slideBy`
calls the classifier two times on the same item. If the second call
returns a different value, `slideBy` will not advance anymore and
iterate indefinitely on the same item.
  • Loading branch information
jwbargsten committed Apr 11, 2021
1 parent cc4b4b6 commit a09f8cc
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/main/java/io/vavr/collection/Iterator.java
Original file line number Diff line number Diff line change
Expand Up @@ -1909,6 +1909,7 @@ public boolean hasNext() {
if (next == null && source.hasNext()) {
final Object key = classifier.apply(source.touch());
final java.util.List<T> acc = new ArrayList<>();
acc.add(source.next());
while (source.hasNext() && key.equals(classifier.apply(source.touch()))) {
acc.add(source.next());
}
Expand Down
12 changes: 12 additions & 0 deletions src/test/java/io/vavr/collection/AbstractTraversableTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
Expand Down Expand Up @@ -1919,6 +1920,17 @@ public void shouldSlideNilByClassifier() {
assertThat(empty().slideBy(Function.identity())).isEmpty();
}

@Test(timeout=1000)
public void shouldTerminateSlideByClassifier() {
AtomicInteger ai = new AtomicInteger(0);
List<List<String>> expected = List.of(List.of("a", "-"), List.of( "-"), List.of("d") );
List<List<String>> actual = List.of("a", "-", "-", "d")
.slideBy(x -> x.equals("-") ? ai.getAndIncrement() : ai.get())
.toList();
assertThat(actual).containsAll(expected);
assertThat(expected).containsAll(actual);
}

@Test
public void shouldSlideSingularByClassifier() {
final List<Traversable<Integer>> actual = of(1).slideBy(Function.identity()).toList().map(io.vavr.collection.Vector::ofAll);
Expand Down

0 comments on commit a09f8cc

Please sign in to comment.