Skip to content

Commit 775fbc9

Browse files
committed
Rewrite setIndex(int) to pass unit tests
Original did not cover the case of when streams is empty and documentation does not specify any input restrictions. There's an ambiguity with broadcasting an event between the documentation and the actual code (see TODO).
1 parent 8d0f2d3 commit 775fbc9

1 file changed

Lines changed: 23 additions & 5 deletions

File tree

app/src/main/java/org/schabi/newpipe/player/playqueue/PlayQueue.java

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -135,18 +135,36 @@ public int getIndex() {
135135
public synchronized void setIndex(final int index) {
136136
final int oldIndex = getIndex();
137137

138-
int newIndex = index;
138+
final int newIndex;
139+
139140
if (index < 0) {
140141
newIndex = 0;
142+
} else if (index < streams.size()) {
143+
// Regular assignment for index in bounds
144+
newIndex = index;
145+
} else if (streams.isEmpty()) {
146+
// Out of bounds from here on
147+
// Need to check if stream is empty to prevent arithmetic error and negative index
148+
newIndex = 0;
149+
} else if (isComplete()) {
150+
// Circular indexing
151+
newIndex = index % streams.size();
152+
} else {
153+
// Index of last element
154+
newIndex = streams.size() - 1;
141155
}
142-
if (index >= streams.size()) {
143-
newIndex = isComplete() ? index % streams.size() : streams.size() - 1;
144-
}
156+
157+
queueIndex.set(newIndex);
158+
145159
if (oldIndex != newIndex) {
146160
history.add(streams.get(newIndex));
147161
}
148162

149-
queueIndex.set(newIndex);
163+
/*
164+
TODO: Documentation states that a SelectEvent will only be emitted if the new index is...
165+
different from the old one but this is emitted regardless? Not sure what this what it does
166+
exactly so I won't touch it
167+
*/
150168
broadcast(new SelectEvent(oldIndex, newIndex));
151169
}
152170

0 commit comments

Comments
 (0)