/*
 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

//package java.util;
import java.util.*;

import java.io.*;
import java.util.function.Consumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Hash table based implementation of the <tt>Map</tt> interface.  This
 * implementation provides all of the optional map operations, and permits
 * <tt>null</tt> values and the <tt>null</tt> key.  (The <tt>SHM</tt>
 * class is roughly equivalent to <tt>Hashtable</tt>, except that it is
 * unsynchronized and permits nulls.)  This class makes no guarantees as to
 * the order of the map; in particular, it does not guarantee that the order
 * will remain constant over time.
 *
 * <p>This implementation provides constant-time performance for the basic
 * operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function
 * disperses the elements properly among the buckets.  Iteration over
 * collection views requires time proportional to the "capacity" of the
 * <tt>SHM</tt> instance (the number of buckets) plus its size (the number
 * of key-value mappings).  Thus, it's very important not to set the initial
 * capacity too high (or the load factor too low) if iteration performance is
 * important.
 *
 * <p>An instance of <tt>SHM</tt> has two parameters that affect its
 * performance: <i>initial capacity</i> and <i>load factor</i>.  The
 * <i>capacity</i> is the number of buckets in the hash table, and the initial
 * capacity is simply the capacity at the time the hash table is created.  The
 * <i>load factor</i> is a measure of how full the hash table is allowed to
 * get before its capacity is automatically increased.  When the number of
 * entries in the hash table exceeds the product of the load factor and the
 * current capacity, the hash table is <i>rehashed</i> (that is, internal data
 * structures are rebuilt) so that the hash table has approximately twice the
 * number of buckets.
 *
 * <p>As a general rule, the default load factor (.75) offers a good tradeoff
 * between time and space costs.  Higher values decrease the space overhead
 * but increase the lookup cost (reflected in most of the operations of the
 * <tt>SHM</tt> class, including <tt>get</tt> and <tt>put</tt>).  The
 * expected number of entries in the map and its load factor should be taken
 * into account when setting its initial capacity, so as to minimize the
 * number of rehash operations.  If the initial capacity is greater
 * than the maximum number of entries divided by the load factor, no
 * rehash operations will ever occur.
 *
 * <p>If many mappings are to be stored in a <tt>SHM</tt> instance,
 * creating it with a sufficiently large capacity will allow the mappings to
 * be stored more efficiently than letting it perform automatic rehashing as
 * needed to grow the table.
 *
 * <p><strong>Note that this implementation is not synchronized.</strong>
 * If multiple threads access a hash map concurrently, and at least one of
 * the threads modifies the map structurally, it <i>must</i> be
 * synchronized externally.  (A structural modification is any operation
 * that adds or deletes one or more mappings; merely changing the value
 * associated with a key that an instance already contains is not a
 * structural modification.)  This is typically accomplished by
 * synchronizing on some object that naturally encapsulates the map.
 *
 * If no such object exists, the map should be "wrapped" using the
 * {@link Collections#synchronizedMap Collections.synchronizedMap}
 * method.  This is best done at creation time, to prevent accidental
 * unsynchronized access to the map:<pre>
 *   Map m = Collections.synchronizedMap(new SHM(...));</pre>
 *
 * <p>The iterators returned by all of this class's "collection view methods"
 * are <i>fail-fast</i>: if the map is structurally modified at any time after
 * the iterator is created, in any way except through the iterator's own
 * <tt>remove</tt> method, the iterator will throw a
 * {@link ConcurrentModificationException}.  Thus, in the face of concurrent
 * modification, the iterator fails quickly and cleanly, rather than risking
 * arbitrary, non-deterministic behavior at an undetermined time in the
 * future.
 *
 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
 * as it is, generally speaking, impossible to make any hard guarantees in the
 * presence of unsynchronized concurrent modification.  Fail-fast iterators
 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
 * Therefore, it would be wrong to write a program that depended on this
 * exception for its correctness: <i>the fail-fast behavior of iterators
 * should be used only to detect bugs.</i>
 *
 * <p>This class is a member of the
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 * Java Collections Framework</a>.
 *
 * @param <K> the type of keys maintained by this map
 * @param <V> the type of mapped values
 *
 * @author  Doug Lea
 * @author  Josh Bloch
 * @author  Arthur van Hoff
 * @author  Neal Gafter
 * @see     Object#hashCode()
 * @see     Collection
 * @see     Map
 * @see     TreeMap
 * @see     Hashtable
 * @since   1.2
 */

public class SHM<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable
{

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    static final int TREE_THRESHOLD = 16;

    /**
     * The table, resized as necessary. Length MUST Always be a power of two.
     */
    transient Node<K,V>[] table;

    /**
     * The number of key-value mappings contained in this map.
     */
    transient int size;

    /**
     * The next size value at which to resize (capacity * load factor).
     * @serial
     */
    // When table is null this is the initial capacity when constructed
    int threshold;

    /**
     * The load factor for the hash table.
     *
     * @serial
     */
    final float loadFactor;

    /**
     * The number of times this SHM has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the SHM or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the SHM fail-fast.  (See ConcurrentModificationException).
     */
    transient int modCount;

    // views
    transient Set<Map.Entry<K,V>> entrySet;
    transient Set<K> keySet; // fixme when not outside package
    transient Collection<V> values;

    /**
     * Constructs an empty <tt>SHM</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    public SHM(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        threshold = initialCapacity;
        init();
    }

    /**
     * Constructs an empty <tt>SHM</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public SHM(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * Constructs an empty <tt>SHM</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public SHM() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }

    /**
     * Constructs a new <tt>SHM</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>SHM</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     */
    public SHM(Map<? extends K, ? extends V> m) {
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        internalPutAll(m, false);
    }

    private static int tableSizeFor(int number) {
        int n = number - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    // internal utilities

    /**
     * Initialization hook for subclasses. This method is called
     * in all constructors and pseudo-constructors (clone, readObject)
     * after SHM has been initialized but before any entries have
     * been inserted.  (In the absence of this method, readObject would
     * require explicit knowledge of subclasses.)
     */
    void init() {
    }

    /**
     * Spreads higher bits of hash to lower.  Because the table uses
     * power-of-two masking, sets of hashes that vary only in bits
     * above the current mask will always collide. (Among known
     * examples are sets of Float keys holding consecutive whole
     * numbers in small tables.)  To counter this, we apply a
     * transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed across bits (so don't
     * benefit from spreading), and because we use trees to handle
     * large sets of collisions in bins, we don't need excessively
     * high quality.
     */
    final int spread(int h) {
        h ^= (h >>> 18) ^ (h >>> 12);
        return h ^ (h >>> 10);
    }

    static Class<?> comparableClassFor(Object x) {
        Class<?> c, s, cmpc; Type[] ts, as; Type t; ParameterizedType p;
        if (x != null) {
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((cmpc = Comparable.class).isAssignableFrom(c)) {
                while (cmpc.isAssignableFrom(s = c.getSuperclass()))
                    c = s; // find topmost comparable class
                if ((ts = c.getGenericInterfaces()) != null) {
                    for (int i = 0; i < ts.length; ++i) {
                        if (((t = ts[i]) instanceof ParameterizedType) &&
                            ((p = (ParameterizedType)t).getRawType() == cmpc) &&
                            (as = p.getActualTypeArguments()) != null &&
                            as.length == 1 && as[0] == c) // type arg is c
                            return c;
                    }
                }
            }
        }
        return null;
    }

    /**
     * Returns the number of key-value mappings in this map.
     *
     * @return the number of key-value mappings in this map
     */
    public int size() {
        return size;
    }

    /**
     * Returns <tt>true</tt> if this map contains no key-value mappings.
     *
     * @return <tt>true</tt> if this map contains no key-value mappings
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(key)) == null ? null : e.value;
    }

    public V getOrDefault(Object key, V defaultValue) {
        Node<K,V> e;
        return (e = getNode(key)) == null ? defaultValue : e.value;
    }

    /**
     * Returns <tt>true</tt> if this map contains a mapping for the
     * specified key.
     *
     * @param   key   The key whose presence in this map is to be tested
     * @return <tt>true</tt> if this map contains a mapping for the specified
     * key.
     */
    public boolean containsKey(Object key) {
        return getNode(key) != null;
    }

    /**
     * Returns the entry associated with the specified key in the
     * SHM.  Returns null if the SHM contains no mapping
     * for the key.
     */
    final Node<K,V> getNode(Object key) {
        int h = (key == null) ? 0 : spread(key.hashCode());
        Node<K,V>[] tab; Node<K,V> e; int i; K k;
        if ((tab = table) != null && (i = (tab.length - 1) & h) >= 0 &&
            (e = tab[i]) != null) {
            if (e.hash == h && 
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
            if ((e = e.next) != null) {
                if (e instanceof TreeNode)
                    return getTreeNode((TreeNode<K,V>)e, h, key);
                do {
                    if (e.hash == h && 
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

    final V internalPut(K key, V value, boolean onlyIfAbsent, boolean evict) {
        Node<K,V>[] tab; Node<K,V> e; int i;
        int h = (key == null) ? 0 : spread(key.hashCode());
        if ((tab = table) == null)
            tab = presize(threshold);
        else if (size >= threshold)
            tab = resize();
        int len = 0;
        Node<K,V> p = null;
        if ((e = tab[i = (tab.length - 1) & h]) != null) {
            K k;
            if (e.hash == h && 
                ((k = e.key) == key || (key != null && key.equals(k))))
                p = e;
            else if ((e = e.next) != null) {
                if (e instanceof TreeNode) {
                    if ((p = treePut(tab, h, key, value, evict)) == null)
                        return null;
                }
                else {
                    do {
                        if (e.hash == h && 
                            ((k = e.key) == key || 
                             (key != null && key.equals(k)))) {
                            p = e;
                            break;
                        }
                        ++len;
                    } while ((e = e.next) != null);
                }
            }
        }
        if (p != null) {
            V v = p.value;
            if (!onlyIfAbsent)
                p.value = value;
            return v;
        }
        tab[i] = new Node<K,V>(h, key, value, tab[i]);
        ++modCount;
        ++size;
        if (len >= TREE_THRESHOLD)
            convertToTree(tab, i, key);
        return null;
    }

    final void internalPutAll(Map<? extends K, ? extends V> m, boolean evict) {
        int numKeysToBeAdded = m.size();
        if (numKeysToBeAdded > 0) {
            if (table == null) 
                presize(Math.max(numKeysToBeAdded, threshold));
            else if (numKeysToBeAdded > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
                internalPut(e.getKey(), e.getValue(), false, evict);
        }
    }

    final Node<K,V> internalRemove(Object key, Object value, boolean checkValue) {
        int h = (key == null) ? 0 : spread(key.hashCode());
        Node<K,V> result = null;
        Node<K,V>[] tab; Node<K,V> e; int i;
        if ((tab = table) != null && (i = (tab.length - 1) & h) >= 0 &&
            (e = tab[i]) != null) {
            K k; V v;
            if (e instanceof TreeNode) {
                TreeNode<K,V> p = getTreeNode((TreeNode<K,V>)e, h, key);
                if (p != null && (!checkValue || (v = p.value) == value ||
                                  (value != null && value.equals(v)))) {
                    result = p;
                    treeDelete(tab, i, p);
                }
            }
            else {
                Node<K,V> prev = null, next;
                do {
                    next = e.next;
                    if (e.hash == h &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        if (!checkValue || (v = e.value) == value ||
                            (value != null && value.equals(v))) {
                            result = e;
                            if (prev == null)
                                tab[i] = next;
                            else
                                prev.next = next;
                        }
                        break;
                    }
                    prev = e;
                } while ((e = next) != null);
            }
            if (result != null) {
                --size;
                ++modCount;
            }
        }
        return result;
    }

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return internalPut(key, value, false, false);
    }

    @SuppressWarnings({"rawtypes","unchecked"})
    final Node<K,V>[] presize(int targetCap) {
        int cap = tableSizeFor(targetCap);
        threshold = (int) Math.min(cap * loadFactor, MAXIMUM_CAPACITY + 1);
        return table = (Node<K,V>[])new Node[cap];
    }

    /**
     * Rehashes the contents of this map into a new array with a
     * larger capacity.  This method is called automatically when the
     * number of keys in this map reaches its threshold.
     *
     * If current capacity is MAXIMUM_CAPACITY, this method does not
     * resize the map, but sets threshold to Integer.MAX_VALUE.
     * This has the effect of preventing future calls.
     *
     * @param newCapacity the new capacity, MUST be a power of two;
     *        must be greater than current capacity unless current
     *        capacity is MAXIMUM_CAPACITY (in which case value
     *        is irrelevant).
     */
    @SuppressWarnings({"rawtypes","unchecked"})
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int n = oldTab.length;
        if (n == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        int newCap = n << 1;
        threshold = (int)Math.min(newCap * loadFactor, MAXIMUM_CAPACITY + 1);
        Node<K,V>[] newTab = table = (Node<K,V>[])new Node[newCap];
        int newMask = newCap - 1;
        for (int j = 0; j < n; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                if (e instanceof TreeNode) {
                    TreeNode<K,V> t = (TreeNode<K,V>)e;
                    TreeNode<K,V> lf = null;
                    TreeNode<K,V> hf = null;
                    TreeNode<K,V> r, lr, rr; int lh;
                    for (r = t; r.parent != null; r = r.parent);
                    for (lr = r; lr.left != null; lr = lr.left);
                    for (rr = r; rr.right != null; rr = rr.right);
                    if ((lh = lr.hash) == rr.hash) { // move entire tree
                        if ((lh & n) == 0)
                            lf = t;
                        else
                            hf = t;
                    }
                    else {
                        for (;;) {
                            Node<K,V> next = e.next;
                            TreeNode<K,V> p = (TreeNode<K,V>)e;
                            p.parent = p.left = p.right = p.prev = null;
                            TreeNode<K,V> f = (e.hash & n) == 0 ? lf : hf;
                            if ((p.next = f) != null)
                                f.prev = p;
                            insertTreeNode(f, p);
                            if (f == lf)
                                lf = p;
                            else
                                hf = p;
                            if ((e = next) == null)
                                break;
                        }
                    }
                    newTab[j] = lf;
                    newTab[j + n] = hf;
                }
                else {
                    for (;;) {
                        Node<K,V> next = e.next;
                        int i = e.hash & newMask;
                        e.next = newTab[i];
                        newTab[i] = e;
                        if ((e = next) == null)
                            break;
                    }
                }
            }
        }
        return newTab;
    }

    /**
     * Copies all of the mappings from the specified map to this map.
     * These mappings will replace any mappings that this map had for
     * any of the keys currently in the specified map.
     *
     * @param m mappings to be stored in this map
     * @throws NullPointerException if the specified map is null
     */
    public void putAll(Map<? extends K, ? extends V> m) {
        internalPutAll(m, true);
    }

    /**
     * Removes the mapping for the specified key from this map if present.
     *
     * @param  key key whose mapping is to be removed from the map
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V remove(Object key) {
        Node<K,V> e = internalRemove(key, null, false);
        return (e == null ? null : e.value);
    }

    public V putIfAbsent(K key, V value) {
        return internalPut(key, value, true, false);
    }

    public boolean remove(Object key, Object value) {
        return internalRemove(key, value, true) != null;
    }

    public boolean replace(K key, V oldValue, V newValue) {
        Node<K,V> e = getNode(key);
        if (e != null &&  Objects.equals(e.value, oldValue)) {
            e.value = newValue;
            return true;
        }
        return false;
    }

    public V replace(K key, V value) {
        Node<K,V> e = getNode(key);
        if (e != null) {
            V oldValue = e.value;
            e.value = value;
            return oldValue;
        }
        return null;
    }

    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
        Node<K,V> e = getNode(key);
        if (e != null)
            return e.value;
        V value = mappingFunction.apply(key);
        internalPut(key, value, true, false);
        return value;
    }

    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        Node<K,V> e = getNode(key);
        if (e != null) {
            V newValue = remappingFunction.apply(key, e.value);
            e.value = newValue;
            return newValue;
        }
        return null;
    }

    //    public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

    //    public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)

    /**
     * Removes all of the mappings from this map.
     * The map will be empty after this call returns.
     */
    public void clear() {
        modCount++;
        size = 0;
        if (table != null)
            Arrays.fill(table, null);
    }

    /**
     * Returns <tt>true</tt> if this map maps one or more keys to the
     * specified value.
     *
     * @param value value whose presence in this map is to be tested
     * @return <tt>true</tt> if this map maps one or more keys to the
     *         specified value
     */
    public boolean containsValue(Object value) {
        if (value == null)
            return containsNullValue();
        Node<K,V>[] tab;
        if ((tab = table) != null) {
            for (int i = 0; i < tab.length; i++)
                for (Node<K,V> e = tab[i]; e != null; e = e.next)
                    if (value.equals(e.value))
                        return true;
        }
        return false;
    }

    /**
     * Special-case code for containsValue with null argument
     */
    private boolean containsNullValue() {
        Node<K,V>[] tab;
        if ((tab = table) != null) {
            for (int i = 0; i < tab.length; i++)
                for (Node<K,V> e = tab[i]; e != null; e = e.next)
                    if (e.value == null)
                        return true;
        }
        return false;
    }

    /**
     * Returns a shallow copy of this <tt>SHM</tt> instance: the keys and
     * values themselves are not cloned.
     *
     * @return a shallow copy of this map
     */
    @SuppressWarnings("unchecked")
    public Object clone() {
        SHM<K,V> result = null;
        try {
            result = (SHM<K,V>)super.clone();
        } catch (CloneNotSupportedException e) {
            // assert false;
        }
        result.table = null;
        result.entrySet = null;
        result.keySet = null;
        result.values = null;
        result.modCount = 0;
        result.size = 0;
        result.init();
        result.internalPutAll(this, false);
        return result;
    }

    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int h, K k, V v, Node<K,V> n) {
            hash = h;
            key = k;
            value = v;
            next = n;
        }

        public final K getKey() { return key; }
        public final V getValue() { return value; }
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
            }
            return false;
        }

        public final int hashCode() {
            return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
        }

        public final String toString() {
            return getKey() + "=" + getValue();
        }

        TreeNode<K,V> toTreeNode() {
            return new TreeNode<K,V>(hash, key, value, null);
        }
    }

    static final class TreeNode<K,V> extends Node<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;

        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }
    }

    abstract class HashIterator {
        Node<K,V> next;        // next entry to return
        Node<K,V> current;     // current entry
        int expectedModCount;  // For fast-fail
        int index;             // current slot

        HashIterator() {
            expectedModCount = modCount;
            index = 0;
            Node<K,V>[] t;
            if ((t = table) != null && size > 0) { // advance to first entry
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Node<K,V> nextNode() {
            Node<K,V> e; Node<K,V>[] t;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if ((e = next) == null)
                throw new NoSuchElementException();
            if ((next = e.next) == null && (t = table) != null) {
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
            return current = e;
        }

        public void remove() {
            if (current == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            internalRemove(current.key, null, false);
            current = null;
            expectedModCount = modCount;
        }

    }

    final class ValueIterator extends HashIterator implements Iterator<V> {
        public V next() { return nextNode().value; }
    }

    final class KeyIterator extends HashIterator implements Iterator<K> {
        public K next() { return nextNode().key; }
    }

    final class EntryIterator extends HashIterator implements Iterator<Map.Entry<K,V>> {
        public Map.Entry<K,V> next() { return nextNode(); }
    }

    // Views

    final class KeySet extends AbstractSet<K> {
        public int size() {
            return size;
        }
        public boolean contains(Object o) {
            return containsKey(o);
        }
        public boolean remove(Object o) {
            return internalRemove(o, null, false) != null;
        }
        public void clear() {
            SHM.this.clear();
        }
        public Iterator<K> iterator() {
            return new KeyIterator();
        }
        public Spliterator<K> spliterator() {
            return new KeySpliterator<K,V>(SHM.this, 0, -1, 0, 0);
        }
    }

    final class Values extends AbstractCollection<V> {
        public int size() {
            return size;
        }
        public boolean contains(Object o) {
            return containsValue(o);
        }
        public void clear() {
            SHM.this.clear();
        }
        public Iterator<V> iterator() {
            return new ValueIterator();
        }
        public Spliterator<V> spliterator() {
            return new ValueSpliterator<K,V>(SHM.this, 0, -1, 0, 0);
        }
    }

    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public boolean contains(Object o) {
            Map.Entry<?,?> e = (Map.Entry<?,?>) o;
            Node<K,V> candidate = getNode(e.getKey());
            return candidate != null && candidate.equals(e);
        }
        public boolean remove(Object o) {
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>) o;
                return internalRemove(e.getKey(), e.getValue(), true) != null;
            }
            return false;
        }
        public int size() {
            return size;
        }
        public void clear() {
            SHM.this.clear();
        }
        public Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
        public Spliterator<Map.Entry<K,V>> spliterator() {
            return new EntrySpliterator<K,V>(SHM.this, 0, -1, 0, 0);
        }
    }

    /**
     * Returns a {@link Set} view of the keys contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own <tt>remove</tt> operation), the results of
     * the iteration are undefined.  The set supports element removal,
     * which removes the corresponding mapping from the map, via the
     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
     * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
     * operations.
     */
    public Set<K> keySet() {
        Set<K> ks = keySet;
        return (ks != null ? ks : (keySet = new KeySet()));
    }

    /**
     * Returns a {@link Collection} view of the values contained in this map.
     * The collection is backed by the map, so changes to the map are
     * reflected in the collection, and vice-versa.  If the map is
     * modified while an iteration over the collection is in progress
     * (except through the iterator's own <tt>remove</tt> operation),
     * the results of the iteration are undefined.  The collection
     * supports element removal, which removes the corresponding
     * mapping from the map, via the <tt>Iterator.remove</tt>,
     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
     * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
     * support the <tt>add</tt> or <tt>addAll</tt> operations.
     */
    public Collection<V> values() {
        Collection<V> vs = values;
        return (vs != null ? vs : (values = new Values()));
    }

    /**
     * Returns a {@link Set} view of the mappings contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own <tt>remove</tt> operation, or through the
     * <tt>setValue</tt> operation on a map entry returned by the
     * iterator) the results of the iteration are undefined.  The set
     * supports element removal, which removes the corresponding
     * mapping from the map, via the <tt>Iterator.remove</tt>,
     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
     * <tt>clear</tt> operations.  It does not support the
     * <tt>add</tt> or <tt>addAll</tt> operations.
     *
     * @return a set view of the mappings contained in this map
     */
    public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es = entrySet;
        return es != null ? es : (entrySet = new EntrySet());
    }

    /**
     * Save the state of the <tt>SHM</tt> instance to a stream (i.e.,
     * serialize it).
     *
     * @serialData The <i>capacity</i> of the SHM (the length of the
     *             bucket array) is emitted (int), followed by the
     *             <i>size</i> (an int, the number of key-value
     *             mappings), followed by the key (Object) and value (Object)
     *             for each key-value mapping.  The key-value mappings are
     *             emitted in no particular order.
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws IOException
    {
        // Write out the threshold, loadfactor, and any hidden stuff
        s.defaultWriteObject();

        // Write out number of buckets
        if (table == null) {
            s.writeInt(tableSizeFor(threshold));
        } else {
           s.writeInt(table.length);
        }

        // Write out size (number of Mappings)
        s.writeInt(size);

        // Write out keys and values (alternating)
        if (size > 0) {
            for(Map.Entry<K,V> e : new EntrySet()) {
                s.writeObject(e.getKey());
                s.writeObject(e.getValue());
            }
        }
    }

    private static final long serialVersionUID = 362498820763181265L;

    /**
     * Reconstitute the {@code SHM} instance from a stream (i.e.,
     * deserialize it).
     */
    private void readObject(java.io.ObjectInputStream s)
         throws IOException, ClassNotFoundException
    {
        // Read in the threshold (ignored), loadfactor, and any hidden stuff
        s.defaultReadObject();
        if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
            throw new InvalidObjectException("Illegal load factor: " +
                                               loadFactor);
        }

        // set other fields that need values
        table = null;

        // Read in number of buckets
        s.readInt(); // ignored.

        // Read number of mappings
        int mappings = s.readInt();
        if (mappings < 0)
            throw new InvalidObjectException("Illegal mappings count: " +
                                               mappings);

        // capacity chosen by number of mappings and desired load (if >= 0.25)
        int capacity = (int) Math.min(
                mappings * Math.min(1 / loadFactor, 4.0f),
                // we have limits...
                SHM.MAXIMUM_CAPACITY);

        // allocate the bucket array;
        if (mappings > 0) {
            presize(capacity);
        } else {
            threshold = capacity;
        }

        init();  // Give subclass a chance to do its thing.

        // Read the keys and values, and put the mappings in the SHM
        for (int i=0; i<mappings; i++) {
            @SuppressWarnings("unchecked")
                K key = (K) s.readObject();
            @SuppressWarnings("unchecked")
                V value = (V) s.readObject();
            internalPut(key, value, false, false);
        }
    }

    // These methods are used when serializing HashSets
    int   capacity()     { return table.length; }
    float loadFactor()   { return loadFactor;   }

    static class SHMSpliterator<K,V> {
        final SHM<K,V> map;
        SHM.Node<K,V> current; // current node
        int index;                  // current index, modified on advance/split
        int fence;                  // one past last index
        int est;                    // size estimate
        int expectedModCount;       // for comodification checks

        SHMSpliterator(SHM<K,V> m, int origin,
                               int fence, int est,
                               int expectedModCount) {
            this.map = m;
            this.index = origin;
            this.fence = fence;
            this.est = est;
            this.expectedModCount = expectedModCount;
        }

        final int getFence() { // initialize fence and size on first use
            int hi;
            if ((hi = fence) < 0) {
                SHM<K,V> m = map;
                est = m.size;
                expectedModCount = m.modCount;
                hi = fence = m.table.length;
            }
            return hi;
        }

        public final long estimateSize() {
            getFence(); // force init
            return (long) est;
        }
    }

    static final class KeySpliterator<K,V>
        extends SHMSpliterator<K,V>
        implements Spliterator<K> {
        KeySpliterator(SHM<K,V> m, int origin, int fence, int est,
                       int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public KeySpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                new KeySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
                                        expectedModCount);
        }

        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super K> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            SHM<K,V> m = map;
            SHM.Node<K,V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = tab.length;
            }
            else
                mc = expectedModCount;
            if (tab.length >= hi && (i = index) >= 0 && i < (index = hi)) {
                SHM.Node<K,V> p = current;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p.getKey());
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        @SuppressWarnings("unchecked")
        public boolean tryAdvance(Consumer<? super K> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            SHM.Node<K,V>[] tab = map.table;
            if (tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        K k = current.getKey();
                        current = current.next;
                        action.accept(k);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                Spliterator.DISTINCT;
        }
    }

    static final class ValueSpliterator<K,V>
        extends SHMSpliterator<K,V>
        implements Spliterator<V> {
        ValueSpliterator(SHM<K,V> m, int origin, int fence, int est,
                         int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public ValueSpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                new ValueSpliterator<K,V>(map, lo, index = mid, est >>>= 1,
                                          expectedModCount);
        }

        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super V> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            SHM<K,V> m = map;
            SHM.Node<K,V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = tab.length;
            }
            else
                mc = expectedModCount;
            if (tab.length >= hi && (i = index) >= 0 && i < (index = hi)) {
                SHM.Node<K,V> p = current;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p.getValue());
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        @SuppressWarnings("unchecked")
        public boolean tryAdvance(Consumer<? super V> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            SHM.Node<K,V>[] tab = map.table;
            if (tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        V v = current.getValue();
                        current = current.next;
                        action.accept(v);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0);
        }
    }

    static final class EntrySpliterator<K,V>
        extends SHMSpliterator<K,V>
        implements Spliterator<Map.Entry<K,V>> {
        EntrySpliterator(SHM<K,V> m, int origin, int fence, int est,
                         int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public EntrySpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                new EntrySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
                                          expectedModCount);
        }

        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            SHM<K,V> m = map;
            SHM.Node<K,V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = tab.length;
            }
            else
                mc = expectedModCount;
            if (tab.length >= hi && (i = index) >= 0 && i < (index = hi)) {
                SHM.Node<K,V> p = current;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        @SuppressWarnings("unchecked")
        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            SHM.Node<K,V>[] tab = map.table;
            if (tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        SHM.Node<K,V> e = current;
                        current = current.next;
                        action.accept(e);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                Spliterator.DISTINCT;
        }
    }

    private TreeNode<K,V> rotateLeft(TreeNode<K,V> root, TreeNode<K,V> p) {
        if (p != null) {
            TreeNode<K,V> r = p.right, pp, rl;
            if ((rl = p.right = r.left) != null)
                rl.parent = p;
            if ((pp = r.parent = p.parent) == null) 
                root = r;
            else if (pp.left == p)
                pp.left = r;
            else
                pp.right = r;
            r.left = p;
            p.parent = r;
        }
        return root;
    }

    /** From CLR */
    private TreeNode<K,V> rotateRight(TreeNode<K,V> root, TreeNode<K,V> p) {
        if (p != null) {
            TreeNode<K,V> l = p.left, pp, lr;
            if ((lr = p.left = l.right) != null)
                lr.parent = p;
            if ((pp = l.parent = p.parent) == null)
                root = l;
            else if (pp.right == p)
                pp.right = l;
            else
                pp.left = l;
            l.right = p;
            p.parent = l;
        }
        return root;
    }

    final TreeNode<K,V> getTreeNode(TreeNode<K,V> p, int h, Object k) {
        Class<?> cc = comparableClassFor(k);
        if (p != null) {
            while (p.parent != null)
                p = p.parent;
        }
        return treeGet(p, h, k, cc);
    }

    @SuppressWarnings({"rawtypes","unchecked"})
    static <K,V> TreeNode<K,V> treeGet(TreeNode<K,V> p, int h, Object k, 
                                        Class<?> cc) {
        while (p != null) {
            int dir, ph; Object pk;
            if ((ph = p.hash) != h)
                dir = (h < ph) ? -1 : 1;
            else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                return p;
            else if (k == null || cc == null || 
                     comparableClassFor(pk) != cc ||
                     (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
                TreeNode<K,V> r, pr; // check both sides
                if ((pr = p.right) != null &&
                    (r = treeGet(pr, h, k, cc)) != null)
                    return r;
                else
                    dir = -1; // continue left
            }
            p = (dir > 0) ? p.right : p.left;
        }
        return null;
    }

    /**
     * Finds or adds a node.
     * @return null if added
     */
    @SuppressWarnings({"rawtypes","unchecked"})
    final TreeNode<K,V> treePut(Node<K,V>[] tab, int h, K k, V v, boolean evict) {
        Class<?> cc = comparableClassFor(k);
        int index = h & (tab.length - 1);
        TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
        TreeNode<K,V> root = first;
        if (root != null) {
            while (root.parent != null) root = root.parent;
        }
        TreeNode<K,V> pp = root, p = null;
        int dir = 0;
        while (pp != null) { // find existing node or leaf to insert at
            int ph; Object pk;
            p = pp;
            if ((ph = p.hash) != h)
                dir = (h < ph) ? -1 : 1;
            else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                return p;
            else if (k == null || cc == null || comparableClassFor(pk) != cc ||
                     (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
                TreeNode<K,V> r, pr;
                if ((pr = p.right) != null &&
                    (r = treeGet(pr, h, k, cc)) != null)
                    return r;
                else // continue left
                    dir = -1;
            }
            pp = (dir > 0) ? p.right : p.left;
        }
        ++modCount;
        ++size;
        TreeNode<K,V> x = new TreeNode<K,V>(h, k, v, first);
        tab[index] = x;
        if (first != null)
            first.prev = x;
        if ((x.parent = p) != null) {
            if (dir <= 0)
                p.left = x;
            else
                p.right = x;
            balanceInsertion(root, x);
        }
        return null;
    }

    /**
     * Inserts existing node
     */
    @SuppressWarnings({"rawtypes","unchecked"})
    final void insertTreeNode(TreeNode<K,V> first, TreeNode<K,V> x) {
        int h = x.hash;
        K k = x.key;
        if (first == null) {
            x.red = false;
            return;
        }
        Class<?> cc = comparableClassFor(k);
        TreeNode<K,V> root = first;
        while (root.parent != null) root = root.parent;
        TreeNode<K,V> pp = root, p = null;
        int dir = 0;
        while (pp != null) {
            int ph; Object pk;
            p = pp;
            if ((ph = p.hash) != h)
                dir = (h < ph) ? -1 : 1;
            else if (k == null || cc == null || (pk = p.key) == null ||
                     comparableClassFor(pk) != cc ||
                     (dir = ((Comparable<Object>)k).compareTo(pk)) == 0)
                dir = -1;
            pp = (dir > 0) ? p.right : p.left;
        }
        x.parent = p;
        if (dir <= 0)
            p.left = x;
        else
            p.right = x;
        balanceInsertion(root, x);
    }

    final void balanceInsertion(TreeNode<K,V> root, TreeNode<K,V> x) {
        x.red = true;
        for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
            if ((xp = x.parent) == null) {
                x.red = false;
                break;
            }
            if (!xp.red || (xpp = xp.parent) == null) {
                if (root != null)
                    root.red = false;
                break;
            }
            if (xp == (xppl = xpp.left)) {
                if ((xppr = xpp.right) != null && xppr.red) {
                    xppr.red = false;
                    xp.red = false;
                    xpp.red = true;
                    x = xpp;
                }
                else {
                    if (x == xp.right) {
                        root = rotateLeft(root, x = xp);
                        xpp = (xp = x.parent) == null ? null : xp.parent;
                    }
                    if (xp != null) {
                        xp.red = false;
                        if (xpp != null) {
                            xpp.red = true;
                            root = rotateRight(root, xpp);
                        }
                    }
                }
            }
            else {
                if (xppl != null && xppl.red) {
                    xppl.red = false;
                    xp.red = false;
                    xpp.red = true;
                    x = xpp;
                }
                else {
                    if (x == xp.left) {
                        root = rotateRight(root, x = xp);
                        xpp = (xp = x.parent) == null ? null : xp.parent;
                    }
                    if (xp != null) {
                        xp.red = false;
                        if (xpp != null) {
                            xpp.red = true;
                            root = rotateLeft(root, xpp);
                        }
                    }
                }
            }
        }
    }

    final void convertToTree(Node<K,V>[] tab, int index, Object key) {
        if (comparableClassFor(key) != null) {
            Node<K,V> e = tab[index];
            TreeNode<K,V> first = null;
            while (e != null) {
                Node<K,V> next = e.next;
                TreeNode<K,V> p = e.toTreeNode();
                p.next = first;
                if (first != null)
                    first.prev = p;
                insertTreeNode(first, p);
                first = p;
                e = next;
            }
            tab[index] = first;
        }
    }

    /**
     * Removes the given node, that must be present before this
     * call.  This is messier than typical red-black deletion code
     * because we cannot swap the contents of an interior node
     * with a leaf successor that is pinned by "next" pointers
     * that are accessible independently of lock. So instead we
     * swap the tree linkages.
     */

    final void treeDelete(Node<K,V>[] tab, int index, TreeNode<K,V> p) {
        TreeNode<K,V> next = (TreeNode<K,V>)p.next;
        TreeNode<K,V> pred = p.prev;
        if (pred == null)
            tab[index] = next;
        else 
            pred.next = next;
        if (next != null)
            next.prev = pred;
        else if (pred == null)
            return;
        TreeNode<K,V> root = p;
        while (root.parent != null) root = root.parent;
        TreeNode<K,V> replacement;
        TreeNode<K,V> pl = p.left;
        TreeNode<K,V> pr = p.right;
        if (pl != null && pr != null) {
            TreeNode<K,V> s = pr, sl;
            while ((sl = s.left) != null) // find successor
                s = sl;
            boolean c = s.red; s.red = p.red; p.red = c; // swap colors
            TreeNode<K,V> sr = s.right;
            TreeNode<K,V> pp = p.parent;
            if (s == pr) { // p was s's direct parent
                p.parent = s;
                s.right = p;
            }
            else {
                TreeNode<K,V> sp = s.parent;
                if ((p.parent = sp) != null) {
                    if (s == sp.left)
                        sp.left = p;
                    else
                        sp.right = p;
                }
                if ((s.right = pr) != null)
                    pr.parent = s;
            }
            p.left = null;
            if ((p.right = sr) != null)
                sr.parent = p;
            if ((s.left = pl) != null)
                pl.parent = s;
            if ((s.parent = pp) == null)
                root = s;
            else if (p == pp.left)
                pp.left = s;
            else
                pp.right = s;
            replacement = sr;
        }
        else 
            replacement = (pl != null) ? pl : pr;
        TreeNode<K,V> pp = p.parent;
        if (replacement == null) {
            if (pp == null)
                return;
            replacement = p;
        }
        else {
            replacement.parent = pp;
            if (pp == null) {
                replacement.red = false;
                return;
            }
            else if (p == pp.left)
                pp.left = replacement;
            else
                pp.right = replacement;
            p.left = p.right = p.parent = null;

        }

        for (TreeNode<K,V> x = replacement; x != null; ) {
            TreeNode<K,V> xp, xpl;
            if (x.red || (xp = x.parent) == null) {
                x.red = false;
                break;
            }

            if (x == (xpl = xp.left)) {
                TreeNode<K,V> sib = xp.right;
                if (sib == null)
                    x = xp;
                else if (sib.red) {
                    sib.red = false;
                    xp.red = true;
                    root = rotateLeft(root, xp);
                    sib = (xp = x.parent) == null ? null : xp.right;
                }
                else {
                    TreeNode<K,V> sl = sib.left, sr = sib.right;
                    if ((sr == null || !sr.red) &&
                        (sl == null || !sl.red)) {
                        sib.red = true;
                        x = xp;
                    }
                    else {
                        if (sr == null || !sr.red) {
                            if (sl != null)
                                sl.red = false;
                            sib.red = true;
                            root = rotateRight(root, sib);
                            sib = (xp = x.parent) == null ?
                                null : xp.right;
                        }
                        if (sib != null) {
                            sib.red = (xp == null) ? false : xp.red;
                            if ((sr = sib.right) != null)
                                sr.red = false;
                        }
                        if (xp != null) {
                            xp.red = false;
                            root = rotateLeft(root, xp);
                        }
                        x = root;
                    }
                }
            }
            else { // symmetric
                TreeNode<K,V> sib = xpl;
                if (sib == null)
                    x = xp;
                else if (sib.red) {
                    sib.red = false;
                    xp.red = true;
                    root = rotateRight(root, xp);
                    sib = (xp = x.parent) == null ? null : xp.left;
                }
                else {
                    TreeNode<K,V> sl = sib.left, sr = sib.right;
                    if ((sl == null || !sl.red) &&
                        (sr == null || !sr.red)) {
                        sib.red = true;
                        x = xp;
                    }
                    else {
                        if (sl == null || !sl.red) {
                            if (sr != null)
                                sr.red = false;
                            sib.red = true;
                            root = rotateLeft(root, sib);
                            sib = (xp = x.parent) == null ?
                                null : xp.left;
                        }
                        if (sib != null) {
                            sib.red = (xp == null) ? false : xp.red;
                            if ((sl = sib.left) != null)
                                sl.red = false;
                        }
                        if (xp != null) {
                            xp.red = false;
                            root = rotateRight(root, xp);
                        }
                        x = root;
                    }
                }
            }
        }
        if (root != null)
            root.red = false;
        if (p == replacement && (pp = p.parent) != null) {
            if (p == pp.left) // detach pointers
                pp.left = null;
            else if (p == pp.right)
                pp.right = null;
            p.parent = null;
        }
    }

    /**
     * Checks linkage and balance invariants at root
     */
    final boolean checkInvariants(Node<K,V> p) {
        if (p instanceof TreeNode) {
            TreeNode<K,V> r = (TreeNode<K,V>)p;
            while (r.parent != null) r = r.parent;
            return checkTreeNode(r);
        }
        return true;
    }
    
    /**
     * Recursive invariant check
     */
    final boolean checkTreeNode(TreeNode<K,V> t) {
        TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
            tb = t.prev, tn = (TreeNode<K,V>)t.next;
        if (tb != null && tb.next != t)
            return false;
        if (tn != null && tn.prev != t)
            return false;
        if (tp != null && t != tp.left && t != tp.right)
            return false;
        if (tl != null && (tl.parent != t || tl.hash > t.hash))
            return false;
        if (tr != null && (tr.parent != t || tr.hash < t.hash))
            return false;
        if (t.red && tl != null && tl.red && tr != null && tr.red)
            return false;
        if (tl != null && !checkTreeNode(tl))
            return false;
        if (tr != null && !checkTreeNode(tr))
            return false;
        return true;
    }

}
