Skip to content
This repository has been archived by the owner on Oct 14, 2023. It is now read-only.

Commit

Permalink
[jOOQ#305] added ArrayList initialization based on source.estimateSize()
Browse files Browse the repository at this point in the history
  • Loading branch information
Tomasz Linkowski committed May 2, 2017
1 parent e0ccabe commit f54482e
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/main/java/org/jooq/lambda/SeqBuffer.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@
*/
final class SeqBuffer<T> {

/**
* @see ArrayList#MAX_ARRAY_SIZE
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

@SuppressWarnings("unchecked")
static <T> SeqBuffer<T> of(Stream<? extends T> stream) {
return of((Spliterator<T>) stream.spliterator());
Expand All @@ -31,7 +36,7 @@ static <T> SeqBuffer<T> of(Spliterator<T> spliterator) {
}

private final Spliterator<T> source;
private final List<T> buffer = new ArrayList<>();
private final List<T> buffer;

/**
* <code>True</code> while <code>source</code> hasn't reported that it's exhausted.
Expand All @@ -44,6 +49,7 @@ static <T> SeqBuffer<T> of(Spliterator<T> spliterator) {

private SeqBuffer(Spliterator<T> source) {
this.source = Objects.requireNonNull(source);
this.buffer = initBuffer(source);
}

/**
Expand All @@ -57,6 +63,17 @@ Seq<T> seq() {
return Seq.seq(new BufferSpliterator());
}

private static <T> List<T> initBuffer(Spliterator<T> source) {
long estimateSize = source.estimateSize();
if (estimateSize == Long.MAX_VALUE) // infinite/unknown size
return new ArrayList<>();

if (estimateSize > MAX_ARRAY_SIZE)
throw new IllegalArgumentException("Stream is too long to be buffered: " + estimateSize);

return new ArrayList<>((int) estimateSize);
}

/**
* Special <code>Spliterator</code> whose <code>tryAdvance</code> method can buffer
* (i.e. can advance the <code>source</code> spliterator).
Expand Down

0 comments on commit f54482e

Please sign in to comment.