dev.marksman.collectionviews.ImmutableVectorSlice 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;
final class ImmutableVectorSlice extends ConcreteVector
implements ImmutableVector {
private final int offset;
private final int size;
private final ImmutableVector underlying;
private ImmutableVectorSlice(int offset, int size, ImmutableVector 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 ImmutableVector immutableVectorSlice(int offset, int size, ImmutableVector underlying) {
if (underlying instanceof ImmutableVectorSlice>) {
ImmutableVectorSlice underlyingSlice = (ImmutableVectorSlice) underlying;
int endIndex = Math.min(offset + size, underlyingSlice.size);
return new ImmutableVectorSlice<>(offset + underlyingSlice.offset, endIndex - offset, underlyingSlice.underlying);
} else {
return new ImmutableVectorSlice<>(offset, size, underlying);
}
}
}