package org.xbib.datastructures.immutable;

import java.util.Objects;
import static org.xbib.datastructures.immutable.SingletonImmutableList.singletonIterator;

/**
 * Implementation of {@link ImmutableSet} with exactly one element.
 */
final class SingletonImmutableSet<E> extends ImmutableSet<E> {
    // We deliberately avoid caching the asList and hashCode here, to ensure that with
    // compressed oops, a SingletonImmutableSet packs all the way down to the optimal 16 bytes.

    final transient E element;

    SingletonImmutableSet(E element) {
        this.element = Objects.requireNonNull(element);
    }

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

    @Override
    public boolean contains(Object target) {
        return element.equals(target);
    }

    @Override
    public UnmodifiableIterator<E> iterator() {
        return singletonIterator(element);
    }

    @Override
    public ImmutableList<E> asList() {
        return ImmutableList.of(element);
    }

    @Override
    boolean isPartialView() {
        return false;
    }

    @Override
    int copyIntoArray(Object[] dst, int offset) {
        dst[offset] = element;
        return offset + 1;
    }

    @Override
    public int hashCode() {
        return element.hashCode();
    }

    @Override
    public String toString() {
        return '[' + element.toString() + ']';
    }
}
