Skip to content

Commit

Permalink
Fix MoreGatherers.windowSliding() (#64)
Browse files Browse the repository at this point in the history
  • Loading branch information
pivovarit authored Oct 23, 2024
1 parent 38509b5 commit c877d30
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
12 changes: 7 additions & 5 deletions src/main/java/com/pivovarit/gatherers/WindowSlidingGatherer.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,13 @@ public BiConsumer<WindowSlidingGatherer.SlidingWindow, Downstream<? super List<T
}

class SlidingWindow {
Object[] window = new Object[windowSize];
int at = 0;
boolean firstWindow = true;
private Object[] window = new Object[windowSize];
private int at = 0;
private boolean emitted = false;

boolean integrate(T element, Downstream<? super List<T>> downstream) {
window[at++] = element;
emitted = false;
if (at < windowSize) {
return true;
} else {
Expand All @@ -52,17 +53,18 @@ boolean integrate(T element, Downstream<? super List<T>> downstream) {
System.arraycopy(oldWindow, step, newWindow, 0, windowSize - step);
window = newWindow;
at -= step;
firstWindow = false;
emitted = true;
return downstream.push((List<T>) Arrays.asList(oldWindow));
}
}

void finish(Downstream<? super List<T>> downstream) {
if (firstWindow && at > 0 && !downstream.isRejecting()) {
if (!emitted && at > 0 && !downstream.isRejecting()) {
var lastWindow = new Object[at];
System.arraycopy(window, 0, lastWindow, 0, at);
window = null;
at = 0;
emitted = true;
downstream.push((List<T>) Arrays.asList(lastWindow));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,6 @@ void shouldWindowSlidingWithStep1() {
@Test
void shouldWindowSlidingWithStep2() {
assertThat(Stream.of(1, 2, 3, 4, 5).gather(MoreGatherers.windowSliding(2, 2)))
.containsExactly(of(1, 2), of(3, 4));
.containsExactly(of(1, 2), of(3, 4), of(5));
}
}

0 comments on commit c877d30

Please sign in to comment.