package org.xbib.datastructures.immutable;

/**
 * Implementation of {@code Entry} for {@link ImmutableMap} that adds extra methods to traverse hash
 * buckets for the key and the value. This allows reuse in {@link RegularImmutableMap} and {@link
 * RegularImmutableBiMap}, which don't have to recopy the entries created by their {@code Builder}
 * implementations.
 *
 * <p>This base implementation has no key or value pointers, so instances of ImmutableMapEntry (but
 * not its subclasses) can be reused when copied from one ImmutableMap to another.
 */
class ImmutableMapEntry<K, V> extends ImmutableEntry<K, V> {

    ImmutableMapEntry(K key, V value) {
        super(key, value);
        checkEntryNotNull(key, value);
    }

    ImmutableMapEntry(ImmutableMapEntry<K, V> contents) {
        super(contents.getKey(), contents.getValue());
        // null check would be redundant
    }

    ImmutableMapEntry<K, V> getNextInKeyBucket() {
        return null;
    }

    ImmutableMapEntry<K, V> getNextInValueBucket() {
        return null;
    }

    /**
     * Returns true if this entry has no bucket links and can safely be reused as a terminal entry in
     * a bucket in another map.
     */
    boolean isReusable() {
        return true;
    }

    static void checkEntryNotNull(Object key, Object value) {
        if (key == null) {
            throw new NullPointerException("null key in entry: null=" + value);
        } else if (value == null) {
            throw new NullPointerException("null value in entry: " + key + "=null");
        }
    }

    /**
     * Creates an {@code ImmutableMapEntry} array to hold parameterized entries. The result must never
     * be upcast back to ImmutableMapEntry[] (or Object[], etc.), or allowed to escape the class.
     *
     * <p>The returned array has all its elements set to their initial null values. However, we don't
     * declare it as {@code @Nullable ImmutableMapEntry[]} because our checker doesn't require newly
     * created arrays to have a {@code @Nullable} element type even when they're created directly with
     * {@code new ImmutableMapEntry[...]}, so it seems silly to insist on that only here.
     */
    @SuppressWarnings("unchecked") // Safe as long as the javadocs are followed
    static <K, V> ImmutableMapEntry<K, V>[] createEntryArray(int size) {
        return new ImmutableMapEntry[size];
    }
}
