All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dev.marksman.collectionviews.LazyVector Maven / Gradle / Ivy

There is a newer version: 1.2.3
Show newest version
package dev.marksman.collectionviews;

import com.jnape.palatable.lambda.functions.Fn1;

import static dev.marksman.collectionviews.Validation.*;

final class LazyVector extends ConcreteVector
        implements ImmutableNonEmptyVector, Primitive {
    private final int size; // must be >= 1
    private final int offset;
    private final Fn1 valueSupplier;

    LazyVector(int size, int offset, Fn1 valueSupplier) {
        assert (size >= 1);
        this.size = size;
        this.offset = offset;
        this.valueSupplier = valueSupplier;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public A unsafeGet(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException();
        }
        return valueSupplier.apply(index + offset);
    }

    @Override
    public ImmutableVector drop(int count) {
        validateDrop(count);
        if (count == 0) {
            return this;
        } else if (count < size) {
            return new LazyVector<>(size - count, offset + count, valueSupplier);
        } else {
            return Vectors.empty();
        }
    }

    @Override
    public ImmutableVector slice(int startIndex, int endIndexExclusive) {
        validateSlice(startIndex, endIndexExclusive);
        if (startIndex == 0) {
            return take(endIndexExclusive);
        }
        endIndexExclusive = Math.min(endIndexExclusive, size);
        if (endIndexExclusive >= startIndex) {
            return new LazyVector<>(endIndexExclusive - startIndex, offset + startIndex, valueSupplier);
        } else {
            return Vector.empty();
        }
    }

    @Override
    public ImmutableVector take(int count) {
        validateTake(count);
        if (count == 0) {
            return Vectors.empty();
        } else if (count >= size) {
            return this;
        } else {
            return new LazyVector<>(count, offset, valueSupplier);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy