dev.marksman.collectionviews.VectorSlice Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of collection-views Show documentation
Show all versions of collection-views Show documentation
Low overhead, protected views over Java collections
package dev.marksman.collectionviews;
import static dev.marksman.collectionviews.ImmutableVectorSlice.immutableVectorSlice;
final class VectorSlice extends ConcreteVector {
private final int offset;
private final int size;
private final Vector underlying;
private VectorSlice(int offset, int size, Vector underlying) {
this.offset = offset;
this.size = size;
this.underlying = underlying;
}
@Override
public int size() {
return size;
}
@Override
public A unsafeGet(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return underlying.unsafeGet(offset + index);
}
static Vector vectorSlice(int offset, int size, Vector underlying) {
if (underlying instanceof VectorSlice>) {
VectorSlice underlyingSlice = (VectorSlice) underlying;
int endIndex = Math.min(offset + size, underlyingSlice.size);
return new VectorSlice<>(offset + underlyingSlice.offset, endIndex - offset, underlyingSlice.underlying);
} else if (underlying instanceof ImmutableVectorSlice>) {
return immutableVectorSlice(offset, size, (ImmutableVectorSlice) underlying);
} else {
return new VectorSlice<>(offset, size, underlying);
}
}
}