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

org.jhotdraw8.collection.spliterator.FailFastSpliterator Maven / Gradle / Ivy

The newest version!
/*
 * @(#)FailFastSpliterator.java
 * Copyright © 2023 The authors and contributors of JHotDraw. MIT License.
 */

package org.jhotdraw8.collection.spliterator;

import org.jspecify.annotations.Nullable;

import java.util.ConcurrentModificationException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.function.IntSupplier;

/**
 * A spliterator that fails when a provided modification counter does not have an
 * expected value.
 *
 * @param  the element type
 */
public class FailFastSpliterator extends Spliterators.AbstractSpliterator {
    private final Spliterator s;
    private final int expectedModCount;
    private final IntSupplier modCountSupplier;

    public FailFastSpliterator(Spliterator s, IntSupplier modCountSupplier) {
        super(s.estimateSize(), s.characteristics());
        this.s = s;
        this.modCountSupplier = modCountSupplier;
        this.expectedModCount = modCountSupplier.getAsInt();
    }

    @Override
    public boolean tryAdvance(Consumer action) {
        ensureUnmodified();
        return s.tryAdvance(action);
    }

    protected void ensureUnmodified() {
        if (expectedModCount != modCountSupplier.getAsInt()) {
            throw new ConcurrentModificationException();
        }
    }


    @Override
    public @Nullable Spliterator trySplit() {
        Spliterator split = s.trySplit();
        return split == null ? null : new FailFastSpliterator<>(split, modCountSupplier);
    }

    @Override
    public long estimateSize() {
        return s.estimateSize();
    }

    @Override
    public int characteristics() {
        return s.characteristics() & ~Spliterator.IMMUTABLE;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy