-
Notifications
You must be signed in to change notification settings - Fork 59
/
WindowedSpliterator.java
123 lines (95 loc) · 2.88 KB
/
WindowedSpliterator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package com.codepoetics.protonpack;
import com.codepoetics.protonpack.comparators.Comparators;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;
class WindowedSpliterator<T> implements Spliterator<List<T>> {
private final Spliterator<T> source;
private final int windowSize;
private int overlap;
private boolean allowLesserSize;
List<T> queue = new LinkedList<>();
List<T> next = new LinkedList<>();
private boolean windowSeeded;
WindowedSpliterator(Spliterator<T> input, int windowSize, int overlap, boolean allowLesserSize) {
source = input;
this.windowSize = windowSize;
this.overlap = overlap;
this.allowLesserSize = allowLesserSize;
}
static <T> WindowedSpliterator<T> over(Spliterator<T> source, int windowSize, int overlap, boolean allowLesserSize) {
return new WindowedSpliterator<>(source, windowSize, overlap, allowLesserSize);
}
private boolean hasNext() {
if (!windowSeeded) {
seedWindow();
windowSeeded = true;
}
return next.size() > 0;
}
private void nextWindow() {
for (int i = 0; i < overlap; i++) {
if(next.isEmpty()){
return;
}
next.remove(0);
source.tryAdvance(next::add);
}
}
private void seedWindow() {
int window = windowSize;
while (source.tryAdvance(next::add)) {
window--;
if (window == 0) {
return;
}
}
if (next.size() != windowSize && !allowLesserSize) {
next.clear();
}
}
private List<T> next() {
queue = new LinkedList<>(next);
nextWindow();
if (!allowLesserSize) {
if (next.size() != windowSize) {
next.clear();
}
}
return queue;
}
@Override
public boolean tryAdvance(Consumer<? super List<T>> action) {
if (hasNext()) {
action.accept(next());
return true;
}
return false;
}
@Override
public Spliterator<List<T>> trySplit() {
return null;
}
@Override
public long estimateSize() {
long sourceSize = source.estimateSize();
if (sourceSize == 0) {
return 0;
}
if (sourceSize <= windowSize) {
return 1;
}
return sourceSize - windowSize;
}
@Override
public int characteristics() {
return source.characteristics() & ~(Spliterator.SIZED | Spliterator.ORDERED);
}
@Override
public Comparator<? super List<T>> getComparator() {
Comparator<? super T> comparator = source.getComparator();
return comparator == null ? null : Comparators.toListComparator(comparator);
}
}