Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java
Original file line number Diff line number Diff line change
Expand Up @@ -587,10 +587,14 @@ static class ListEnumerable<T> extends CollectionEnumerable<T> {

@Override public Enumerable<T> skip(int count) {
final List<T> list = toList();
if (count >= list.size()) {
// Clamp to zero, as the BigDecimal overload does, so that a negative
// count skips nothing and matches EnumerableDefaults.skip rather than
// throwing from List.subList.
final int rows = Math.max(count, 0);
if (rows >= list.size()) {
return Linq4j.emptyEnumerable();
}
return new ListEnumerable<>(list.subList(count, list.size()));
return new ListEnumerable<>(list.subList(rows, list.size()));
}

@Override public Enumerable<T> skip(BigDecimal count) {
Expand All @@ -605,10 +609,14 @@ static class ListEnumerable<T> extends CollectionEnumerable<T> {

@Override public Enumerable<T> take(int count) {
final List<T> list = toList();
if (count >= list.size()) {
// Clamp to zero, as the BigDecimal overload does, so that a negative
// count yields an empty enumerable and matches EnumerableDefaults.take
// rather than throwing from List.subList.
final int rows = Math.max(count, 0);
if (rows >= list.size()) {
return this;
}
return new ListEnumerable<>(list.subList(0, count));
return new ListEnumerable<>(list.subList(0, rows));
}

@Override public Enumerable<T> take(BigDecimal count) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2238,4 +2238,20 @@ public String toString() {
new Department("HR", 20, ImmutableList.of()),
new Department("Marketing", 30, ImmutableList.of(emps[1])),
};

@Test void testTakeListEnumerableNegativeSize() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be reflected in some SQL tests as well? What happens for SELECT * LIMIT -2.5?

final List<Integer> values = Arrays.asList(1, 2, 3);

assertThat(EnumerableDefaults.take(Linq4j.asEnumerable(values), -1).toList(),
is(empty()));
assertThat(Linq4j.asEnumerable(values).take(-1).toList(), is(empty()));
}

@Test void testSkipListEnumerableNegativeSize() {
final List<Integer> values = Arrays.asList(1, 2, 3);

assertThat(EnumerableDefaults.skip(Linq4j.asEnumerable(values), -1).toList(),
is(values));
assertThat(Linq4j.asEnumerable(values).skip(-1).toList(), is(values));
}
}
Loading