package com.datastax.oss.driver.internal.core;
import com.datastax.oss.driver.api.core.PagingIterable;
import com.datastax.oss.driver.api.core.cql.ColumnDefinitions;
import com.datastax.oss.driver.api.core.cql.ExecutionInfo;
import com.datastax.oss.driver.internal.core.cql.PagingIterableSpliterator;
import com.datastax.oss.driver.shaded.guava.common.collect.AbstractIterator;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.function.Function;
public class PagingIterableWrapper<SourceT, TargetT> implements PagingIterable<TargetT> {
private final PagingIterable<SourceT> source;
private final boolean sized;
private final Iterator<TargetT> iterator;
public PagingIterableWrapper(
@NonNull PagingIterable<SourceT> source,
@NonNull Function<? super SourceT, ? extends TargetT> elementMapper) {
this(source, elementMapper, false);
}
public PagingIterableWrapper(
@NonNull PagingIterable<SourceT> source,
@NonNull Function<? super SourceT, ? extends TargetT> elementMapper,
boolean sized) {
this.source = source;
this.sized = sized;
Iterator<SourceT> sourceIterator = source.iterator();
this.iterator =
new AbstractIterator<TargetT>() {
@Override
protected TargetT computeNext() {
return sourceIterator.hasNext()
? elementMapper.apply(sourceIterator.next())
: endOfData();
}
};
}
@NonNull
@Override
public ColumnDefinitions getColumnDefinitions() {
return source.getColumnDefinitions();
}
@NonNull
@Override
public List<ExecutionInfo> getExecutionInfos() {
return source.getExecutionInfos();
}
@Override
public boolean isFullyFetched() {
return source.isFullyFetched();
}
@Override
public int getAvailableWithoutFetching() {
return source.getAvailableWithoutFetching();
}
@Override
public boolean wasApplied() {
return source.wasApplied();
}
@NonNull
@Override
public Iterator<TargetT> iterator() {
return iterator;
}
@NonNull
@Override
public Spliterator<TargetT> spliterator() {
PagingIterableSpliterator.Builder<TargetT> builder = PagingIterableSpliterator.builder(this);
if (sized) {
builder.withEstimatedSize(getAvailableWithoutFetching());
}
return builder.build();
}
@NonNull
@Override
public <NewTargetT> PagingIterable<NewTargetT> map(
Function<? super TargetT, ? extends NewTargetT> elementMapper) {
return new PagingIterableWrapper<>(this, elementMapper, sized);
}
}