/*
 * Copyright (C) 2007 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.collect;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.CollectPreconditions.checkRemove;

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Serialization.FieldSetter;
import com.google.common.math.IntMath;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * A multiset that supports concurrent modifications and that provides atomic versions of most
 * {@code Multiset} operations (exceptions where noted). Null elements are not supported.
 *
 *
See the Guava User Guide article on  {@code
 * Multiset}.
 *
 * @author Cliff L. Biffle
 * @author mike nonemacher
 * @since 2.0
 */
@GwtIncompatible
public final class ConcurrentHashMultiset<E> extends AbstractMultiset<E> implements Serializable {

  /*
   * The ConcurrentHashMultiset's atomic operations are implemented primarily in terms of
   * AtomicInteger's atomic operations, with some help from ConcurrentMap's atomic operations on
   * creation and removal (including automatic removal of zeroes). If the modification of an
   * AtomicInteger results in zero, we compareAndSet the value to zero; if that succeeds, we remove
   * the entry from the Map. If another operation sees a zero in the map, it knows that the entry is
   * about to be removed, so this operation may remove it (often by replacing it with a new
   * AtomicInteger).
   */

  /** The number of occurrences of each element. */
  private final transient ConcurrentMap<E, AtomicInteger> countMap;

  // This constant allows the deserialization code to set a final field. This holder class
  // makes sure it is not initialized unless an instance is deserialized.
  private static class FieldSettersHolder {
    static final FieldSetter<ConcurrentHashMultiset> COUNT_MAP_FIELD_SETTER =
        Serialization.getFieldSetter(ConcurrentHashMultiset.class, "countMap");
  }

  /**
   * Creates a new, empty {@code ConcurrentHashMultiset} using the default initial capacity, load
   * factor, and concurrency settings.
   */
  public static <E> ConcurrentHashMultiset<E> create() {
    // TODO(schmoe): provide a way to use this class with other (possibly arbitrary)
    // ConcurrentMap implementors. One possibility is to extract most of this class into
    // an AbstractConcurrentMapMultiset.
    return new ConcurrentHashMultiset<E>(new ConcurrentHashMap<E, AtomicInteger>());
  }

  /**
   * Creates a new {@code ConcurrentHashMultiset} containing the specified elements, using the
   * default initial capacity, load factor, and concurrency settings.
   *
   *
This implementation is highly efficient when {@code elements} is itself a {@link Multiset}.
   *
   * @param elements the elements that the multiset should contain
   */
  public static <E> ConcurrentHashMultiset<E> create(Iterable<? extends E> elements) {
    ConcurrentHashMultiset<E> multiset = ConcurrentHashMultiset.create();
    Iterables.addAll(multiset, elements);
    return multiset;
  }

  /**
   * Creates a new, empty {@code ConcurrentHashMultiset} using {@code countMap} as the internal
   * backing map.
   *
   *
This instance will assume ownership of {@code countMap}, and other code should not maintain
   * references to the map or modify it in any way.
   *
   *
The returned multiset is serializable if the input map is.
   *
   * @param countMap backing map for storing the elements in the multiset and their counts. It must
   *     be empty.
   * @throws IllegalArgumentException if {@code countMap} is not empty
   * @since 20.0
   */
  @Beta
  public static <E> ConcurrentHashMultiset<E> create(ConcurrentMap<E, AtomicInteger> countMap) {
    return new ConcurrentHashMultiset<E>(countMap);
  }

  @VisibleForTesting
  ConcurrentHashMultiset(ConcurrentMap<E, AtomicInteger> countMap) {
    checkArgument(countMap.isEmpty(), "the backing map (%s) must be empty", countMap);
    this.countMap = countMap;
  }

  // Query Operations

  /**
   * Returns the number of occurrences of {@code element} in this multiset.
   *
   * @param element the element to look for
   * @return the nonnegative number of occurrences of the element
   */
  @Override
  public int count(@NullableDecl Object element) {
    AtomicInteger existingCounter = Maps.safeGet(countMap, element);
    return (existingCounter == null) ? 0 : existingCounter.get();
  }

  /**
   * {@inheritDoc}
   *
   *
If the data in the multiset is modified by any other threads during this method, it is
   * undefined which (if any) of these modifications will be reflected in the result.
   */
  @Override
  public int size() {
    long sum = 0L;
    for (AtomicInteger value : countMap.values()) {
      sum += value.get();
    }
    return Ints.saturatedCast(sum);
  }

  /*
   * Note: the superclass toArray() methods assume that size() gives a correct
   * answer, which ours does not.
   */

  @Override
  public Object[] toArray() {
    return snapshot().toArray();
  }

  @Override
  public <T> T[] toArray(T[] array) {
    return snapshot().toArray(array);
  }

  /*
   * We'd love to use 'new ArrayList(this)' or 'list.addAll(this)', but
   * either of these would recurse back to us again!
   */
  private List<E> snapshot() {
    List<E> list = Lists.newArrayListWithExpectedSize(size());
    for (Multiset.Entry<E> entry : entrySet()) {
      E element = entry.getElement();
      for (int i = entry.getCount(); i > 0; i--) {
        list.add(element);
      }
    }
    return list;
  }

  // Modification Operations

  /**
   * Adds a number of occurrences of the specified element to this multiset.
   *
   * @param element the element to add
   * @param occurrences the number of occurrences to add
   * @return the previous count of the element before the operation; possibly zero
   * @throws IllegalArgumentException if {@code occurrences} is negative, or if the resulting amount
   *     would exceed {@link Integer#MAX_VALUE}
   */
  @CanIgnoreReturnValue
  @Override
  public int add(E element, int occurrences) {
    checkNotNull(element);
    if (occurrences == 0) {
      return count(element);
    }
    CollectPreconditions.checkPositive(occurrences, "occurences");

    while (true) {
      AtomicInteger existingCounter = Maps.safeGet(countMap, element);
      if (existingCounter == null) {
        existingCounter = countMap.putIfAbsent(element, new AtomicInteger(occurrences));
        if (existingCounter == null) {
          return 0;
        }
        // existingCounter != null: fall through to operate against the existing AtomicInteger
      }

      while (true) {
        int oldValue = existingCounter.get();
        if (oldValue != 0) {
          try {
            int newValue = IntMath.checkedAdd(oldValue, occurrences);
            if (existingCounter.compareAndSet(oldValue, newValue)) {
              // newValue can't == 0, so no need to check & remove
              return oldValue;
            }
          } catch (ArithmeticException overflow) {
            throw new IllegalArgumentException(
                "Overflow adding " + occurrences + " occurrences to a count of " + oldValue);
          }
        } else {
          // In the case of a concurrent remove, we might observe a zero value, which means another
          // thread is about to remove (element, existingCounter) from the map. Rather than wait,
          // we can just do that work here.
          AtomicInteger newCounter = new AtomicInteger(occurrences);
          if ((countMap.putIfAbsent(element, newCounter) == null)
              || countMap.replace(element, existingCounter, newCounter)) {
            return 0;
          }
          break;
        }
      }

      // If we're still here, there was a race, so just try again.
    }
  }

  /**
   * Removes a number of occurrences of the specified element from this multiset. If the multiset
   * contains fewer than this number of occurrences to begin with, all occurrences will be removed.
   *
   * @param element the element whose occurrences should be removed
   * @param occurrences the number of occurrences of the element to remove
   * @return the count of the element before the operation; possibly zero
   * @throws IllegalArgumentException if {@code occurrences} is negative
   */
  /*
   * TODO(cpovirk): remove and removeExactly currently accept null inputs only
   * if occurrences == 0. This satisfies both NullPointerTester and
   * CollectionRemoveTester.testRemove_nullAllowed, but it's not clear that it's
   * a good policy, especially because, in order for the test to pass, the
   * parameter must be misleadingly annotated as @NullableDecl. I suspect that
   * we'll want to remove @NullableDecl, add an eager checkNotNull, and loosen up
   * testRemove_nullAllowed.
   */
  @CanIgnoreReturnValue
  @Override
  public int remove(@NullableDecl Object element, int occurrences) {
    if (occurrences == 0) {
      return count(element);
    }
    CollectPreconditions.checkPositive(occurrences, "occurences");

    AtomicInteger existingCounter = Maps.safeGet(countMap, element);
    if (existingCounter == null) {
      return 0;
    }
    while (true) {
      int oldValue = existingCounter.get();
      if (oldValue != 0) {
        int newValue = Math.max(0, oldValue - occurrences);
        if (existingCounter.compareAndSet(oldValue, newValue)) {
          if (newValue == 0) {
            // Just CASed to 0; remove the entry to clean up the map. If the removal fails,
            // another thread has already replaced it with a new counter, which is fine.
            countMap.remove(element, existingCounter);
          }
          return oldValue;
        }
      } else {
        return 0;
      }
    }
  }

  /**
   * Removes exactly the specified number of occurrences of {@code element}, or makes no change if
   * this is not possible.
   *
   *
This method, in contrast to {@link #remove(Object, int)}, has no effect when the element
   * count is smaller than {@code occurrences}.
   *
   * @param element the element to remove
   * @param occurrences the number of occurrences of {@code element} to remove
   * @return {@code true} if the removal was possible (including if {@code occurrences} is zero)
   * @throws IllegalArgumentException if {@code occurrences} is negative
   */
  @CanIgnoreReturnValue
  public boolean removeExactly(@NullableDecl Object element, int occurrences) {
    if (occurrences == 0) {
      return true;
    }
    CollectPreconditions.checkPositive(occurrences, "occurences");

    AtomicInteger existingCounter = Maps.safeGet(countMap, element);
    if (existingCounter == null) {
      return false;
    }
    while (true) {
      int oldValue = existingCounter.get();
      if (oldValue < occurrences) {
        return false;
      }
      int newValue = oldValue - occurrences;
      if (existingCounter.compareAndSet(oldValue, newValue)) {
        if (newValue == 0) {
          // Just CASed to 0; remove the entry to clean up the map. If the removal fails,
          // another thread has already replaced it with a new counter, which is fine.
          countMap.remove(element, existingCounter);
        }
        return true;
      }
    }
  }

  /**
   * Adds or removes occurrences of {@code element} such that the {@link #count} of the element
   * becomes {@code count}.
   *
   * @return the count of {@code element} in the multiset before this call
   * @throws IllegalArgumentException if {@code count} is negative
   */
  @CanIgnoreReturnValue
  @Override
  public int setCount(E element, int count) {
    checkNotNull(element);
    checkNonnegative(count, "count");
    while (true) {
      AtomicInteger existingCounter = Maps.safeGet(countMap, element);
      if (existingCounter == null) {
        if (count == 0) {
          return 0;
        } else {
          existingCounter = countMap.putIfAbsent(element, new AtomicInteger(count));
          if (existingCounter == null) {
            return 0;
          }
          // existingCounter != null: fall through
        }
      }

      while (true) {
        int oldValue = existingCounter.get();
        if (oldValue == 0) {
          if (count == 0) {
            return 0;
          } else {
            AtomicInteger newCounter = new AtomicInteger(count);
            if ((countMap.putIfAbsent(element, newCounter) == null)
                || countMap.replace(element, existingCounter, newCounter)) {
              return 0;
            }
          }
          break;
        } else {
          if (existingCounter.compareAndSet(oldValue, count)) {
            if (count == 0) {
              // Just CASed to 0; remove the entry to clean up the map. If the removal fails,
              // another thread has already replaced it with a new counter, which is fine.
              countMap.remove(element, existingCounter);
            }
            return oldValue;
          }
        }
      }
    }
  }

  /**
   * Sets the number of occurrences of {@code element} to {@code newCount}, but only if the count is
   * currently {@code expectedOldCount}. If {@code element} does not appear in the multiset exactly
   * {@code expectedOldCount} times, no changes will be made.
   *
   * @return {@code true} if the change was successful. This usually indicates that the multiset has
   *     been modified, but not always: in the case that {@code expectedOldCount == newCount}, the
   *     method will return {@code true} if the condition was met.
   * @throws IllegalArgumentException if {@code expectedOldCount} or {@code newCount} is negative
   */
  @CanIgnoreReturnValue
  @Override
  public boolean setCount(E element, int expectedOldCount, int newCount) {
    checkNotNull(element);
    checkNonnegative(expectedOldCount, "oldCount");
    checkNonnegative(newCount, "newCount");

    AtomicInteger existingCounter = Maps.safeGet(countMap, element);
    if (existingCounter == null) {
      if (expectedOldCount != 0) {
        return false;
      } else if (newCount == 0) {
        return true;
      } else {
        // if our write lost the race, it must have lost to a nonzero value, so we can stop
        return countMap.putIfAbsent(element, new AtomicInteger(newCount)) == null;
      }
    }
    int oldValue = existingCounter.get();
    if (oldValue == expectedOldCount) {
      if (oldValue == 0) {
        if (newCount == 0) {
          // Just observed a 0; try to remove the entry to clean up the map
          countMap.remove(element, existingCounter);
          return true;
        } else {
          AtomicInteger newCounter = new AtomicInteger(newCount);
          return (countMap.putIfAbsent(element, newCounter) == null)
              || countMap.replace(element, existingCounter, newCounter);
        }
      } else {
        if (existingCounter.compareAndSet(oldValue, newCount)) {
          if (newCount == 0) {
            // Just CASed to 0; remove the entry to clean up the map. If the removal fails,
            // another thread has already replaced it with a new counter, which is fine.
            countMap.remove(element, existingCounter);
          }
          return true;
        }
      }
    }
    return false;
  }

  // Views

  @Override
  Set<E> createElementSet() {
    final Set<E> delegate = countMap.keySet();
    return new ForwardingSet<E>() {
      @Override
      protected Set<E> delegate() {
        return delegate;
      }

      @Override
      public boolean contains(@NullableDecl Object object) {
        return object != null && Collections2.safeContains(delegate, object);
      }

      @Override
      public boolean containsAll(Collection<?> collection) {
        return standardContainsAll(collection);
      }

      @Override
      public boolean remove(Object object) {
        return object != null && Collections2.safeRemove(delegate, object);
      }

      @Override
      public boolean removeAll(Collection<?> c) {
        return standardRemoveAll(c);
      }
    };
  }

  @Override
  Iterator<E> elementIterator() {
    throw new AssertionError("should never be called");
  }

  /** @deprecated Internal method, use {@link #entrySet()}. */
  @Deprecated
  @Override
  public Set<Multiset.Entry<E>> createEntrySet() {
    return new EntrySet();
  }

  @Override
  int distinctElements() {
    return countMap.size();
  }

  @Override
  public boolean isEmpty() {
    return countMap.isEmpty();
  }

  @Override
  Iterator<Entry<E>> entryIterator() {
    // AbstractIterator makes this fairly clean, but it doesn't support remove(). To support
    // remove(), we create an AbstractIterator, and then use ForwardingIterator to delegate to it.
    final Iterator<Entry<E>> readOnlyIterator =
        new AbstractIterator<Entry<E>>() {
          private final Iterator<Map.Entry<E, AtomicInteger>> mapEntries =
              countMap.entrySet().iterator();

          @Override
          protected Entry<E> computeNext() {
            while (true) {
              if (!mapEntries.hasNext()) {
                return endOfData();
              }
              Map.Entry<E, AtomicInteger> mapEntry = mapEntries.next();
              int count = mapEntry.getValue().get();
              if (count != 0) {
                return Multisets.immutableEntry(mapEntry.getKey(), count);
              }
            }
          }
        };

    return new ForwardingIterator<Entry<E>>() {
      @NullableDecl private Entry<E> last;

      @Override
      protected Iterator<Entry<E>> delegate() {
        return readOnlyIterator;
      }

      @Override
      public Entry<E> next() {
        last = super.next();
        return last;
      }

      @Override
      public void remove() {
        checkRemove(last != null);
        ConcurrentHashMultiset.this.setCount(last.getElement(), 0);
        last = null;
      }
    };
  }

  @Override
  public Iterator<E> iterator() {
    return Multisets.iteratorImpl(this);
  }

  @Override
  public void clear() {
    countMap.clear();
  }

  @WeakOuter
  private class EntrySet extends AbstractMultiset<E>.EntrySet {
    @Override
    ConcurrentHashMultiset<E> multiset() {
      return ConcurrentHashMultiset.this;
    }

    /*
     * Note: the superclass toArray() methods assume that size() gives a correct
     * answer, which ours does not.
     */

    @Override
    public Object[] toArray() {
      return snapshot().toArray();
    }

    @Override
    public <T> T[] toArray(T[] array) {
      return snapshot().toArray(array);
    }

    private List<Multiset.Entry<E>> snapshot() {
      List<Multiset.Entry<E>> list = Lists.newArrayListWithExpectedSize(size());
      // Not Iterables.addAll(list, this), because that'll forward right back here.
      Iterators.addAll(list, iterator());
      return list;
    }
  }

  /** @serialData the ConcurrentMap of elements and their counts. */
  private void writeObject(ObjectOutputStream stream) throws IOException {
    stream.defaultWriteObject();
    stream.writeObject(countMap);
  }

  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    @SuppressWarnings("unchecked") // reading data stored by writeObject
    ConcurrentMap<E, Integer> deserializedCountMap =
        (ConcurrentMap<E, Integer>) stream.readObject();
    FieldSettersHolder.COUNT_MAP_FIELD_SETTER.set(this, deserializedCountMap);
  }

  private static final long serialVersionUID = 1;
}


/*
 * Copyright (C) 2012 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.collect;

import static com.google.common.collect.CollectPreconditions.checkRemove;
import static com.google.common.collect.Hashing.smearedHash;

import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.checkerframework.checker.nullness.compatqual.MonotonicNonNullDecl;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * CompactHashSet is an implementation of a Set. All optional operations (adding and removing) are
 * supported. The elements can be any objects.
 *
 *
{@code contains(x)}, {@code add(x)} and {@code remove(x)}, are all (expected and amortized)
 * constant time operations. Expected in the hashtable sense (depends on the hash function doing a
 * good job of distributing the elements to the buckets to a distribution not far from uniform), and
 * amortized since some operations can trigger a hash table resize.
 *
 *
Unlike {@code java.util.HashSet}, iteration is only proportional to the actual {@code size()},
 * which is optimal, and not the size of the internal hashtable, which could be much larger
 * than {@code size()}. Furthermore, this structure only depends on a fixed number of arrays; {@code
 * add(x)} operations do not create objects for the garbage collector to deal with, and for
 * every element added, the garbage collector will have to traverse {@code 1.5} references on
 * average, in the marking phase, not {@code 5.0} as in {@code java.util.HashSet}.
 *
 *
If there are no removals, then {@link #iterator iteration} order is the same as insertion
 * order. Any removal invalidates any ordering guarantees.
 *
 *
This class should not be assumed to be universally superior to {@code java.util.HashSet}.
 * Generally speaking, this class reduces object allocation and memory consumption at the price of
 * moderately increased constant factors of CPU. Only use this class when there is a specific reason
 * to prioritize memory over CPU.
 *
 * @author Dimitris Andreou
 */
@GwtIncompatible // not worth using in GWT for now
class CompactHashSet<E> extends AbstractSet<E> implements Serializable {
  // TODO(user): cache all field accesses in local vars

  /** Creates an empty {@code CompactHashSet} instance. */
  public static <E> CompactHashSet<E> create() {
    return new CompactHashSet<>();
  }

  /**
   * Creates a mutable {@code CompactHashSet} instance containing the elements of the given
   * collection in unspecified order.
   *
   * @param collection the elements that the set should contain
   * @return a new {@code CompactHashSet} containing those elements (minus duplicates)
   */
  public static <E> CompactHashSet<E> create(Collection<? extends E> collection) {
    CompactHashSet<E> set = createWithExpectedSize(collection.size());
    set.addAll(collection);
    return set;
  }

  /**
   * Creates a mutable {@code CompactHashSet} instance containing the given elements in
   * unspecified order.
   *
   * @param elements the elements that the set should contain
   * @return a new {@code CompactHashSet} containing those elements (minus duplicates)
   */
  public static <E> CompactHashSet<E> create(E... elements) {
    CompactHashSet<E> set = createWithExpectedSize(elements.length);
    Collections.addAll(set, elements);
    return set;
  }

  /**
   * Creates a {@code CompactHashSet} instance, with a high enough "initial capacity" that it
   * should hold {@code expectedSize} elements without growth.
   *
   * @param expectedSize the number of elements you expect to add to the returned set
   * @return a new, empty {@code CompactHashSet} with enough capacity to hold {@code expectedSize}
   *     elements without resizing
   * @throws IllegalArgumentException if {@code expectedSize} is negative
   */
  public static <E> CompactHashSet<E> createWithExpectedSize(int expectedSize) {
    return new CompactHashSet<>(expectedSize);
  }

  private static final float LOAD_FACTOR = 1.0f;

  /** Bitmask that selects the low 32 bits. */
  private static final long NEXT_MASK = (1L << 32) - 1;

  /** Bitmask that selects the high 32 bits. */
  private static final long HASH_MASK = ~NEXT_MASK;

  // TODO(user): decide default size
  @VisibleForTesting static final int DEFAULT_SIZE = 3;

  // used to indicate blank table entries
  static final int UNSET = -1;

  /**
   * The hashtable. Its values are indexes to the elements and entries arrays.
   *
   *
Currently, the UNSET value means "null pointer", and any non negative value x is the actual
   * index.
   *
   *
Its size must be a power of two.
   */
  @MonotonicNonNullDecl private transient int[] table;

  /**
   * Contains the logical entries, in the range of [0, size()). The high 32 bits of each long is the
   * smeared hash of the element, whereas the low 32 bits is the "next" pointer (pointing to the
   * next entry in the bucket chain). The pointers in [size(), entries.length) are all "null"
   * (UNSET).
   */
  @MonotonicNonNullDecl private transient long[] entries;

  /**
   * The elements contained in the set, in the range of [0, size()). The elements in [size(),
   * elements.length) are all {@code null}.
   */
  @MonotonicNonNullDecl transient Object[] elements;

  /**
   * Keeps track of modifications of this set, to make it possible to throw
   * ConcurrentModificationException in the iterator. Note that we choose not to make this volatile,
   * so we do less of a "best effort" to track such errors, for better performance.
   */
  transient int modCount;

  /** The number of elements contained in the set. */
  private transient int size;

  /** Constructs a new empty instance of {@code CompactHashSet}. */
  CompactHashSet() {
    init(DEFAULT_SIZE);
  }

  /**
   * Constructs a new instance of {@code CompactHashSet} with the specified capacity.
   *
   * @param expectedSize the initial capacity of this {@code CompactHashSet}.
   */
  CompactHashSet(int expectedSize) {
    init(expectedSize);
  }

  /** Pseudoconstructor for serialization support. */
  void init(int expectedSize) {
    Preconditions.checkArgument(expectedSize >= 0, "Initial capacity must be non-negative");
    this.modCount = Math.max(1, expectedSize); // Save expectedSize for use in allocArrays()
  }

  /** Returns whether arrays need to be allocated. */
  boolean needsAllocArrays() {
    return table == null;
  }

  /** Handle lazy allocation of arrays. */
  void allocArrays() {
    Preconditions.checkState(needsAllocArrays(), "Arrays already allocated");

    int expectedSize = modCount;
    int buckets = Hashing.closedTableSize(expectedSize, LOAD_FACTOR);
    this.table = newTable(buckets);

    this.entries = newEntries(expectedSize);
    this.elements = new Object[expectedSize];
  }

  private static int[] newTable(int size) {
    int[] array = new int[size];
    Arrays.fill(array, UNSET);
    return array;
  }

  private static long[] newEntries(int size) {
    long[] array = new long[size];
    Arrays.fill(array, UNSET);
    return array;
  }

  private int hashTableMask() {
    return table.length - 1;
  }

  private static int getHash(long entry) {
    return (int) (entry >>> 32);
  }

  /** Returns the index, or UNSET if the pointer is "null" */
  private static int getNext(long entry) {
    return (int) entry;
  }

  /** Returns a new entry value by changing the "next" index of an existing entry */
  private static long swapNext(long entry, int newNext) {
    return (HASH_MASK & entry) | (NEXT_MASK & newNext);
  }

  @CanIgnoreReturnValue
  @Override
  public boolean add(@NullableDecl E object) {
    if (needsAllocArrays()) {
      allocArrays();
    }
    long[] entries = this.entries;
    Object[] elements = this.elements;

    int hash = smearedHash(object);
    int tableIndex = hash & hashTableMask();
    int newEntryIndex = this.size; // current size, and pointer to the entry to be appended
    int next = table[tableIndex];
    if (next == UNSET) { // uninitialized bucket
      table[tableIndex] = newEntryIndex;
    } else {
      int last;
      long entry;
      do {
        last = next;
        entry = entries[next];
        if (getHash(entry) == hash && Objects.equal(object, elements[next])) {
          return false;
        }
        next = getNext(entry);
      } while (next != UNSET);
      entries[last] = swapNext(entry, newEntryIndex);
    }
    if (newEntryIndex == Integer.MAX_VALUE) {
      throw new IllegalStateException("Cannot contain more than Integer.MAX_VALUE elements!");
    }
    int newSize = newEntryIndex + 1;
    resizeMeMaybe(newSize);
    insertEntry(newEntryIndex, object, hash);
    this.size = newSize;
    int oldCapacity = table.length;
    if (Hashing.needsResizing(newEntryIndex, oldCapacity, LOAD_FACTOR)) {
      resizeTable(2 * oldCapacity);
    }
    modCount++;
    return true;
  }

  /**
   * Creates a fresh entry with the specified object at the specified position in the entry arrays.
   */
  void insertEntry(int entryIndex, E object, int hash) {
    this.entries[entryIndex] = ((long) hash << 32) | (NEXT_MASK & UNSET);
    this.elements[entryIndex] = object;
  }

  /** Resizes the entries storage if necessary. */
  private void resizeMeMaybe(int newSize) {
    int entriesSize = entries.length;
    if (newSize > entriesSize) {
      int newCapacity = entriesSize + Math.max(1, entriesSize >>> 1);
      if (newCapacity < 0) {
        newCapacity = Integer.MAX_VALUE;
      }
      if (newCapacity != entriesSize) {
        resizeEntries(newCapacity);
      }
    }
  }

  /**
   * Resizes the internal entries array to the specified capacity, which may be greater or less than
   * the current capacity.
   */
  void resizeEntries(int newCapacity) {
    this.elements = Arrays.copyOf(elements, newCapacity);
    long[] entries = this.entries;
    int oldCapacity = entries.length;
    entries = Arrays.copyOf(entries, newCapacity);
    if (newCapacity > oldCapacity) {
      Arrays.fill(entries, oldCapacity, newCapacity, UNSET);
    }
    this.entries = entries;
  }

  private void resizeTable(int newCapacity) { // newCapacity always a power of two
    int[] newTable = newTable(newCapacity);
    long[] entries = this.entries;

    int mask = newTable.length - 1;
    for (int i = 0; i < size; i++) {
      long oldEntry = entries[i];
      int hash = getHash(oldEntry);
      int tableIndex = hash & mask;
      int next = newTable[tableIndex];
      newTable[tableIndex] = i;
      entries[i] = ((long) hash << 32) | (NEXT_MASK & next);
    }

    this.table = newTable;
  }

  @Override
  public boolean contains(@NullableDecl Object object) {
    if (needsAllocArrays()) {
      return false;
    }
    int hash = smearedHash(object);
    int next = table[hash & hashTableMask()];
    while (next != UNSET) {
      long entry = entries[next];
      if (getHash(entry) == hash && Objects.equal(object, elements[next])) {
        return true;
      }
      next = getNext(entry);
    }
    return false;
  }

  @CanIgnoreReturnValue
  @Override
  public boolean remove(@NullableDecl Object object) {
    if (needsAllocArrays()) {
      return false;
    }
    return remove(object, smearedHash(object));
  }

  @CanIgnoreReturnValue
  private boolean remove(Object object, int hash) {
    int tableIndex = hash & hashTableMask();
    int next = table[tableIndex];
    if (next == UNSET) {
      return false;
    }
    int last = UNSET;
    do {
      if (getHash(entries[next]) == hash && Objects.equal(object, elements[next])) {
        if (last == UNSET) {
          // we need to update the root link from table[]
          table[tableIndex] = getNext(entries[next]);
        } else {
          // we need to update the link from the chain
          entries[last] = swapNext(entries[last], getNext(entries[next]));
        }

        moveLastEntry(next);
        size--;
        modCount++;
        return true;
      }
      last = next;
      next = getNext(entries[next]);
    } while (next != UNSET);
    return false;
  }

  /**
   * Moves the last entry in the entry array into {@code dstIndex}, and nulls out its old position.
   */
  void moveLastEntry(int dstIndex) {
    int srcIndex = size() - 1;
    if (dstIndex < srcIndex) {
      // move last entry to deleted spot
      elements[dstIndex] = elements[srcIndex];
      elements[srcIndex] = null;

      // move the last entry to the removed spot, just like we moved the element
      long lastEntry = entries[srcIndex];
      entries[dstIndex] = lastEntry;
      entries[srcIndex] = UNSET;

      // also need to update whoever's "next" pointer was pointing to the last entry place
      // reusing "tableIndex" and "next"; these variables were no longer needed
      int tableIndex = getHash(lastEntry) & hashTableMask();
      int lastNext = table[tableIndex];
      if (lastNext == srcIndex) {
        // we need to update the root pointer
        table[tableIndex] = dstIndex;
      } else {
        // we need to update a pointer in an entry
        int previous;
        long entry;
        do {
          previous = lastNext;
          lastNext = getNext(entry = entries[lastNext]);
        } while (lastNext != srcIndex);
        // here, entries[previous] points to the old entry location; update it
        entries[previous] = swapNext(entry, dstIndex);
      }
    } else {
      elements[dstIndex] = null;
      entries[dstIndex] = UNSET;
    }
  }

  int firstEntryIndex() {
    return isEmpty() ? -1 : 0;
  }

  int getSuccessor(int entryIndex) {
    return (entryIndex + 1 < size) ? entryIndex + 1 : -1;
  }

  /**
   * Updates the index an iterator is pointing to after a call to remove: returns the index of the
   * entry that should be looked at after a removal on indexRemoved, with indexBeforeRemove as the
   * index that *was* the next entry that would be looked at.
   */
  int adjustAfterRemove(int indexBeforeRemove, @SuppressWarnings("unused") int indexRemoved) {
    return indexBeforeRemove - 1;
  }

  @Override
  public Iterator<E> iterator() {
    return new Iterator<E>() {
      int expectedModCount = modCount;
      int currentIndex = firstEntryIndex();
      int indexToRemove = -1;

      @Override
      public boolean hasNext() {
        return currentIndex >= 0;
      }

      @Override
      @SuppressWarnings("unchecked")
      public E next() {
        checkForConcurrentModification();
        if (!hasNext()) {
          throw new NoSuchElementException();
        }
        indexToRemove = currentIndex;
        E result = (E) elements[currentIndex];
        currentIndex = getSuccessor(currentIndex);
        return result;
      }

      @Override
      public void remove() {
        checkForConcurrentModification();
        checkRemove(indexToRemove >= 0);
        expectedModCount++;
        CompactHashSet.this.remove(elements[indexToRemove], getHash(entries[indexToRemove]));
        currentIndex = adjustAfterRemove(currentIndex, indexToRemove);
        indexToRemove = -1;
      }

      private void checkForConcurrentModification() {
        if (modCount != expectedModCount) {
          throw new ConcurrentModificationException();
        }
      }
    };
  }

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

  @Override
  public boolean isEmpty() {
    return size == 0;
  }

  @Override
  public Object[] toArray() {
    if (needsAllocArrays()) {
      return new Object[0];
    }
    return Arrays.copyOf(elements, size);
  }

  @CanIgnoreReturnValue
  @Override
  public <T> T[] toArray(T[] a) {
    if (needsAllocArrays()) {
      if (a.length > 0) {
        a[0] = null;
      }
      return a;
    }
    return ObjectArrays.toArrayImpl(elements, 0, size, a);
  }

  /**
   * Ensures that this {@code CompactHashSet} has the smallest representation in memory, given its
   * current size.
   */
  public void trimToSize() {
    if (needsAllocArrays()) {
      return;
    }
    int size = this.size;
    if (size < entries.length) {
      resizeEntries(size);
    }
    int minimumTableSize = Hashing.closedTableSize(size, LOAD_FACTOR);
    if (minimumTableSize < table.length) {
      resizeTable(minimumTableSize);
    }
  }

  @Override
  public void clear() {
    if (needsAllocArrays()) {
      return;
    }
    modCount++;
    Arrays.fill(elements, 0, size, null);
    Arrays.fill(table, UNSET);
    Arrays.fill(entries, 0, size, UNSET);
    this.size = 0;
  }

  /**
   * The serial form currently mimics Android's java.util.HashSet version, e.g. see
   * http://omapzoom.org/?p=platform/libcore.git;a=blob;f=luni/src/main/java/java/util/HashSet.java
   */
  private void writeObject(ObjectOutputStream stream) throws IOException {
    stream.defaultWriteObject();
    stream.writeInt(size);
    for (int i = firstEntryIndex(); i >= 0; i = getSuccessor(i)) {
      stream.writeObject(elements[i]);
    }
  }

  @SuppressWarnings("unchecked")
  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    int elementCount = stream.readInt();
    if (elementCount < 0) {
      throw new InvalidObjectException("Invalid size: " + elementCount);
    }
    init(elementCount);
    for (int i = 0; i < elementCount; i++) {
      E element = (E) stream.readObject();
      add(element);
    }
  }
}


/*
 * Copyright (C) 2008 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.common.net;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.hash.Hashing;
import com.google.common.io.ByteStreams;
import com.google.common.primitives.Ints;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * Static utility methods pertaining to {@link InetAddress} instances.
 *
 *
Important note: Unlike {@code InetAddress.getByName()}, the methods of this class never
 * cause DNS services to be accessed. For this reason, you should prefer these methods as much as
 * possible over their JDK equivalents whenever you are expecting to handle only IP address string
 * literals -- there is no blocking DNS penalty for a malformed string.
 *
 *
When dealing with {@link Inet4Address} and {@link Inet6Address} objects as byte arrays (vis.
 * {@code InetAddress.getAddress()}) they are 4 and 16 bytes in length, respectively, and represent
 * the address in network byte order.
 *
 *
Examples of IP addresses and their byte representations:
 *
 *

 *
The IPv4 loopback address, {@code "127.0.0.1"}.
 *
{@code 7f 00 00 01}
 *
The IPv6 loopback address, {@code "::1"}.
 *
{@code 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01}
 *
From the IPv6 reserved documentation prefix ({@code 2001:db8::/32}), {@code "2001:db8::1"}.
 *
{@code 20 01 0d b8 00 00 00 00 00 00 00 00 00 00 00 01}
 *
An IPv6 "IPv4 compatible" (or "compat") address, {@code "::192.168.0.1"}.
 *
{@code 00 00 00 00 00 00 00 00 00 00 00 00 c0 a8 00 01}
 *
An IPv6 "IPv4 mapped" address, {@code "::ffff:192.168.0.1"}.
 *
{@code 00 00 00 00 00 00 00 00 00 00 ff ff c0 a8 00 01}
 *

 *
 *
A few notes about IPv6 "IPv4 mapped" addresses and their observed use in Java.
 *
 *
"IPv4 mapped" addresses were originally a representation of IPv4 addresses for use on an IPv6
 * socket that could receive both IPv4 and IPv6 connections (by disabling the {@code IPV6_V6ONLY}
 * socket option on an IPv6 socket). Yes, it's confusing. Nevertheless, these "mapped" addresses
 * were never supposed to be seen on the wire. That assumption was dropped, some say mistakenly, in
 * later RFCs with the apparent aim of making IPv4-to-IPv6 transition simpler.
 *
 *
Technically one can create a 128bit IPv6 address with the wire format of a "mapped"
 * address, as shown above, and transmit it in an IPv6 packet header. However, Java's InetAddress
 * creation methods appear to adhere doggedly to the original intent of the "mapped" address: all
 * "mapped" addresses return {@link Inet4Address} objects.
 *
 *
For added safety, it is common for IPv6 network operators to filter all packets where either
 * the source or destination address appears to be a "compat" or "mapped" address. Filtering
 * suggestions usually recommend discarding any packets with source or destination addresses in the
 * invalid range {@code ::/3}, which includes both of these bizarre address formats. For more
 * information on "bogons", including lists of IPv6 bogon space, see:
 *
 *

 *
http://en.wikipedia.
 *       org/wiki/Bogon_filtering
 *
http://www.cymru.com/Bogons/ ipv6.txt
 *
http://www.cymru.com/
 *       Bogons/v6bogon.html
 *
http://www.
 *       space.net/~gert/RIPE/ipv6-filters.html
 *

 *
 * @author Erik Kline
 * @since 5.0
 */
@Beta
@GwtIncompatible
public final class InetAddresses {
  private static final int IPV4_PART_COUNT = 4;
  private static final int IPV6_PART_COUNT = 8;
  private static final Splitter IPV4_SPLITTER = Splitter.on('.').limit(IPV4_PART_COUNT);
  private static final Splitter IPV6_SPLITTER = Splitter.on(':').limit(IPV6_PART_COUNT + 2);
  private static final Inet4Address LOOPBACK4 = (Inet4Address) forString("127.0.0.1");
  private static final Inet4Address ANY4 = (Inet4Address) forString("0.0.0.0");

  private InetAddresses() {}

  /**
   * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.
   *
   * @param bytes byte array representing an IPv4 address (should be of length 4)
   * @return {@link Inet4Address} corresponding to the supplied byte array
   * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created
   */
  private static Inet4Address getInet4Address(byte[] bytes) {
    checkArgument(
        bytes.length == 4,
        "Byte array has invalid length for an IPv4 address: %s != 4.",
        bytes.length);

    // Given a 4-byte array, this cast should always succeed.
    return (Inet4Address) bytesToInetAddress(bytes);
  }

  /**
   * Returns the {@link InetAddress} having the given string representation.
   *
   *
This deliberately avoids all nameservice lookups (e.g. no DNS).
   *
   * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code
   *     "192.168.0.1"} or {@code "2001:db8::1"}
   * @return {@link InetAddress} representing the argument
   * @throws IllegalArgumentException if the argument is not a valid IP string literal
   */
  public static InetAddress forString(String ipString) {
    byte[] addr = ipStringToBytes(ipString);

    // The argument was malformed, i.e. not an IP string literal.
    if (addr == null) {
      throw formatIllegalArgumentException("'%s' is not an IP string literal.", ipString);
    }

    return bytesToInetAddress(addr);
  }

  /**
   * Returns {@code true} if the supplied string is a valid IP string literal, {@code false}
   * otherwise.
   *
   * @param ipString {@code String} to evaluated as an IP string literal
   * @return {@code true} if the argument is a valid IP string literal
   */
  public static boolean isInetAddress(String ipString) {
    return ipStringToBytes(ipString) != null;
  }

  @NullableDecl
  private static byte[] ipStringToBytes(String ipString) {
    // Make a first pass to categorize the characters in this string.
    boolean hasColon = false;
    boolean hasDot = false;
    for (int i = 0; i < ipString.length(); i++) {
      char c = ipString.charAt(i);
      if (c == '.') {
        hasDot = true;
      } else if (c == ':') {
        if (hasDot) {
          return null; // Colons must not appear after dots.
        }
        hasColon = true;
      } else if (Character.digit(c, 16) == -1) {
        return null; // Everything else must be a decimal or hex digit.
      }
    }

    // Now decide which address family to parse.
    if (hasColon) {
      if (hasDot) {
        ipString = convertDottedQuadToHex(ipString);
        if (ipString == null) {
          return null;
        }
      }
      return textToNumericFormatV6(ipString);
    } else if (hasDot) {
      return textToNumericFormatV4(ipString);
    }
    return null;
  }

  @NullableDecl
  private static byte[] textToNumericFormatV4(String ipString) {
    byte[] bytes = new byte[IPV4_PART_COUNT];
    int i = 0;
    try {
      for (String octet : IPV4_SPLITTER.split(ipString)) {
        bytes[i++] = parseOctet(octet);
      }
    } catch (NumberFormatException ex) {
      return null;
    }

    return i == IPV4_PART_COUNT ? bytes : null;
  }

  @NullableDecl
  private static byte[] textToNumericFormatV6(String ipString) {
    // An address can have [2..8] colons, and N colons make N+1 parts.
    List<String> parts = IPV6_SPLITTER.splitToList(ipString);
    if (parts.size() < 3 || parts.size() > IPV6_PART_COUNT + 1) {
      return null;
    }

    // Disregarding the endpoints, find "::" with nothing in between.
    // This indicates that a run of zeroes has been skipped.
    int skipIndex = -1;
    for (int i = 1; i < parts.size() - 1; i++) {
      if (parts.get(i).length() == 0) {
        if (skipIndex >= 0) {
          return null; // Can't have more than one ::
        }
        skipIndex = i;
      }
    }

    int partsHi; // Number of parts to copy from above/before the "::"
    int partsLo; // Number of parts to copy from below/after the "::"
    if (skipIndex >= 0) {
      // If we found a "::", then check if it also covers the endpoints.
      partsHi = skipIndex;
      partsLo = parts.size() - skipIndex - 1;
      if (parts.get(0).length() == 0 && --partsHi != 0) {
        return null; // ^: requires ^::
      }
      if (Iterables.getLast(parts).length() == 0 && --partsLo != 0) {
        return null; // :$ requires ::$
      }
    } else {
      // Otherwise, allocate the entire address to partsHi. The endpoints
      // could still be empty, but parseHextet() will check for that.
      partsHi = parts.size();
      partsLo = 0;
    }

    // If we found a ::, then we must have skipped at least one part.
    // Otherwise, we must have exactly the right number of parts.
    int partsSkipped = IPV6_PART_COUNT - (partsHi + partsLo);
    if (!(skipIndex >= 0 ? partsSkipped >= 1 : partsSkipped == 0)) {
      return null;
    }

    // Now parse the hextets into a byte array.
    ByteBuffer rawBytes = ByteBuffer.allocate(2 * IPV6_PART_COUNT);
    try {
      for (int i = 0; i < partsHi; i++) {
        rawBytes.putShort(parseHextet(parts.get(i)));
      }
      for (int i = 0; i < partsSkipped; i++) {
        rawBytes.putShort((short) 0);
      }
      for (int i = partsLo; i > 0; i--) {
        rawBytes.putShort(parseHextet(parts.get(parts.size() - i)));
      }
    } catch (NumberFormatException ex) {
      return null;
    }
    return rawBytes.array();
  }

  @NullableDecl
  private static String convertDottedQuadToHex(String ipString) {
    int lastColon = ipString.lastIndexOf(':');
    String initialPart = ipString.substring(0, lastColon + 1);
    String dottedQuad = ipString.substring(lastColon + 1);
    byte[] quad = textToNumericFormatV4(dottedQuad);
    if (quad == null) {
      return null;
    }
    String penultimate = Integer.toHexString(((quad[0] & 0xff) << 8) | (quad[1] & 0xff));
    String ultimate = Integer.toHexString(((quad[2] & 0xff) << 8) | (quad[3] & 0xff));
    return initialPart + penultimate + ":" + ultimate;
  }

  private static byte parseOctet(String ipPart) {
    // Note: we already verified that this string contains only hex digits.
    int octet = Integer.parseInt(ipPart);
    // Disallow leading zeroes, because no clear standard exists on
    // whether these should be interpreted as decimal or octal.
    if (octet > 255 || (ipPart.startsWith("0") && ipPart.length() > 1)) {
      throw new NumberFormatException();
    }
    return (byte) octet;
  }

  private static short parseHextet(String ipPart) {
    // Note: we already verified that this string contains only hex digits.
    int hextet = Integer.parseInt(ipPart, 16);
    if (hextet > 0xffff) {
      throw new NumberFormatException();
    }
    return (short) hextet;
  }

  /**
   * Convert a byte array into an InetAddress.
   *
   *
{@link InetAddress#getByAddress} is documented as throwing a checked exception "if IP
   * address is of illegal length." We replace it with an unchecked exception, for use by callers
   * who already know that addr is an array of length 4 or 16.
   *
   * @param addr the raw 4-byte or 16-byte IP address in big-endian order
   * @return an InetAddress object created from the raw IP address
   */
  private static InetAddress bytesToInetAddress(byte[] addr) {
    try {
      return InetAddress.getByAddress(addr);
    } catch (UnknownHostException e) {
      throw new AssertionError(e);
    }
  }

  /**
   * Returns the string representation of an {@link InetAddress}.
   *
   *
For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6
   * addresses, the output follows RFC 5952 section
   * 4. The main difference is that this method uses "::" for zero compression, while Java's version
   * uses the uncompressed form.
   *
   *
This method uses hexadecimal for all IPv6 addresses, including IPv4-mapped IPv6 addresses
   * such as "::c000:201". The output does not include a Scope ID.
   *
   * @param ip {@link InetAddress} to be converted to an address string
   * @return {@code String} containing the text-formatted IP address
   * @since 10.0
   */
  public static String toAddrString(InetAddress ip) {
    checkNotNull(ip);
    if (ip instanceof Inet4Address) {
      // For IPv4, Java's formatting is good enough.
      return ip.getHostAddress();
    }
    checkArgument(ip instanceof Inet6Address);
    byte[] bytes = ip.getAddress();
    int[] hextets = new int[IPV6_PART_COUNT];
    for (int i = 0; i < hextets.length; i++) {
      hextets[i] = Ints.fromBytes((byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]);
    }
    compressLongestRunOfZeroes(hextets);
    return hextetsToIPv6String(hextets);
  }

  /**
   * Identify and mark the longest run of zeroes in an IPv6 address.
   *
   *
Only runs of two or more hextets are considered. In case of a tie, the leftmost run wins. If
   * a qualifying run is found, its hextets are replaced by the sentinel value -1.
   *
   * @param hextets {@code int[]} mutable array of eight 16-bit hextets
   */
  private static void compressLongestRunOfZeroes(int[] hextets) {
    int bestRunStart = -1;
    int bestRunLength = -1;
    int runStart = -1;
    for (int i = 0; i < hextets.length + 1; i++) {
      if (i < hextets.length && hextets[i] == 0) {
        if (runStart < 0) {
          runStart = i;
        }
      } else if (runStart >= 0) {
        int runLength = i - runStart;
        if (runLength > bestRunLength) {
          bestRunStart = runStart;
          bestRunLength = runLength;
        }
        runStart = -1;
      }
    }
    if (bestRunLength >= 2) {
      Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1);
    }
  }

  /**
   * Convert a list of hextets into a human-readable IPv6 address.
   *
   *
In order for "::" compression to work, the input should contain negative sentinel values in
   * place of the elided zeroes.
   *
   * @param hextets {@code int[]} array of eight 16-bit hextets, or -1s
   */
  private static String hextetsToIPv6String(int[] hextets) {
    // While scanning the array, handle these state transitions:
    //   start->num => "num"     start->gap => "::"
    //   num->num   => ":num"    num->gap   => "::"
    //   gap->num   => "num"     gap->gap   => ""
    StringBuilder buf = new StringBuilder(39);
    boolean lastWasNumber = false;
    for (int i = 0; i < hextets.length; i++) {
      boolean thisIsNumber = hextets[i] >= 0;
      if (thisIsNumber) {
        if (lastWasNumber) {
          buf.append(':');
        }
        buf.append(Integer.toHexString(hextets[i]));
      } else {
        if (i == 0 || lastWasNumber) {
          buf.append("::");
        }
      }
      lastWasNumber = thisIsNumber;
    }
    return buf.toString();
  }

  /**
   * Returns the string representation of an {@link InetAddress} suitable for inclusion in a URI.
   *
   *
For IPv4 addresses, this is identical to {@link InetAddress#getHostAddress()}, but for IPv6
   * addresses it compresses zeroes and surrounds the text with square brackets; for example {@code
   * "[2001:db8::1]"}.
   *
   *
Per section 3.2.2 of RFC 3986, a URI containing an IPv6
   * string literal is of the form {@code "http://[2001:db8::1]:8888/index.html"}.
   *
   *
Use of either {@link InetAddresses#toAddrString}, {@link InetAddress#getHostAddress()}, or
   * this method is recommended over {@link InetAddress#toString()} when an IP address string
   * literal is desired. This is because {@link InetAddress#toString()} prints the hostname and the
   * IP address string joined by a "/".
   *
   * @param ip {@link InetAddress} to be converted to URI string literal
   * @return {@code String} containing URI-safe string literal
   */
  public static String toUriString(InetAddress ip) {
    if (ip instanceof Inet6Address) {
      return "[" + toAddrString(ip) + "]";
    }
    return toAddrString(ip);
  }

  /**
   * Returns an InetAddress representing the literal IPv4 or IPv6 host portion of a URL, encoded in
   * the format specified by RFC 3986 section 3.2.2.
   *
   *
This function is similar to {@link InetAddresses#forString(String)}, however, it requires
   * that IPv6 addresses are surrounded by square brackets.
   *
   *
This function is the inverse of {@link InetAddresses#toUriString(java.net.InetAddress)}.
   *
   * @param hostAddr A RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address
   * @return an InetAddress representing the address in {@code hostAddr}
   * @throws IllegalArgumentException if {@code hostAddr} is not a valid IPv4 address, or IPv6
   *     address surrounded by square brackets
   */
  public static InetAddress forUriString(String hostAddr) {
    InetAddress addr = forUriStringNoThrow(hostAddr);
    if (addr == null) {
      throw formatIllegalArgumentException("Not a valid URI IP literal: '%s'", hostAddr);
    }

    return addr;
  }

  @NullableDecl
  private static InetAddress forUriStringNoThrow(String hostAddr) {
    checkNotNull(hostAddr);

    // Decide if this should be an IPv6 or IPv4 address.
    String ipString;
    int expectBytes;
    if (hostAddr.startsWith("[") && hostAddr.endsWith("]")) {
      ipString = hostAddr.substring(1, hostAddr.length() - 1);
      expectBytes = 16;
    } else {
      ipString = hostAddr;
      expectBytes = 4;
    }

    // Parse the address, and make sure the length/version is correct.
    byte[] addr = ipStringToBytes(ipString);
    if (addr == null || addr.length != expectBytes) {
      return null;
    }

    return bytesToInetAddress(addr);
  }

  /**
   * Returns {@code true} if the supplied string is a valid URI IP string literal, {@code false}
   * otherwise.
   *
   * @param ipString {@code String} to evaluated as an IP URI host string literal
   * @return {@code true} if the argument is a valid IP URI host
   */
  public static boolean isUriInetAddress(String ipString) {
    return forUriStringNoThrow(ipString) != null;
  }

  /**
   * Evaluates whether the argument is an IPv6 "compat" address.
   *
   *
An "IPv4 compatible", or "compat", address is one with 96 leading bits of zero, with the
   * remaining 32 bits interpreted as an IPv4 address. These are conventionally represented in
   * string literals as {@code "::192.168.0.1"}, though {@code "::c0a8:1"} is also considered an
   * IPv4 compatible address (and equivalent to {@code "::192.168.0.1"}).
   *
   *
For more on IPv4 compatible addresses see section 2.5.5.1 of RFC 4291.
   *
   *
NOTE: This method is different from {@link Inet6Address#isIPv4CompatibleAddress} in that it
   * more correctly classifies {@code "::"} and {@code "::1"} as proper IPv6 addresses (which they
   * are), NOT IPv4 compatible addresses (which they are generally NOT considered to be).
   *
   * @param ip {@link Inet6Address} to be examined for embedded IPv4 compatible address format
   * @return {@code true} if the argument is a valid "compat" address
   */
  public static boolean isCompatIPv4Address(Inet6Address ip) {
    if (!ip.isIPv4CompatibleAddress()) {
      return false;
    }

    byte[] bytes = ip.getAddress();
    if ((bytes[12] == 0)
        && (bytes[13] == 0)
        && (bytes[14] == 0)
        && ((bytes[15] == 0) || (bytes[15] == 1))) {
      return false;
    }

    return true;
  }

  /**
   * Returns the IPv4 address embedded in an IPv4 compatible address.
   *
   * @param ip {@link Inet6Address} to be examined for an embedded IPv4 address
   * @return {@link Inet4Address} of the embedded IPv4 address
   * @throws IllegalArgumentException if the argument is not a valid IPv4 compatible address
   */
  public static Inet4Address getCompatIPv4Address(Inet6Address ip) {
    checkArgument(
        isCompatIPv4Address(ip), "Address '%s' is not IPv4-compatible.", toAddrString(ip));

    return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16));
  }

  /**
   * Evaluates whether the argument is a 6to4 address.
   *
   *
6to4 addresses begin with the {@code "2002::/16"} prefix. The next 32 bits are the IPv4
   * address of the host to which IPv6-in-IPv4 tunneled packets should be routed.
   *
   *
For more on 6to4 addresses see section 2 of RFC 3056.
   *
   * @param ip {@link Inet6Address} to be examined for 6to4 address format
   * @return {@code true} if the argument is a 6to4 address
   */
  public static boolean is6to4Address(Inet6Address ip) {
    byte[] bytes = ip.getAddress();
    return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x02);
  }

  /**
   * Returns the IPv4 address embedded in a 6to4 address.
   *
   * @param ip {@link Inet6Address} to be examined for embedded IPv4 in 6to4 address
   * @return {@link Inet4Address} of embedded IPv4 in 6to4 address
   * @throws IllegalArgumentException if the argument is not a valid IPv6 6to4 address
   */
  public static Inet4Address get6to4IPv4Address(Inet6Address ip) {
    checkArgument(is6to4Address(ip), "Address '%s' is not a 6to4 address.", toAddrString(ip));

    return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 2, 6));
  }

  /**
   * A simple immutable data class to encapsulate the information to be found in a Teredo address.
   *
   *
All of the fields in this class are encoded in various portions of the IPv6 address as part
   * of the protocol. More protocols details can be found at: http://en.wikipedia.
   * org/wiki/Teredo_tunneling.
   *
   *
The RFC can be found here: RFC
   * 4380.
   *
   * @since 5.0
   */
  @Beta
  public static final class TeredoInfo {
    private final Inet4Address server;
    private final Inet4Address client;
    private final int port;
    private final int flags;

    /**
     * Constructs a TeredoInfo instance.
     *
     *
Both server and client can be {@code null}, in which case the value {@code "0.0.0.0"} will
     * be assumed.
     *
     * @throws IllegalArgumentException if either of the {@code port} or the {@code flags} arguments
     *     are out of range of an unsigned short
     */
    // TODO: why is this public?
    public TeredoInfo(
        @NullableDecl Inet4Address server, @NullableDecl Inet4Address client, int port, int flags) {
      checkArgument(
          (port >= 0) && (port <= 0xffff), "port '%s' is out of range (0 <= port <= 0xffff)", port);
      checkArgument(
          (flags >= 0) && (flags <= 0xffff),
          "flags '%s' is out of range (0 <= flags <= 0xffff)",
          flags);

      this.server = MoreObjects.firstNonNull(server, ANY4);
      this.client = MoreObjects.firstNonNull(client, ANY4);
      this.port = port;
      this.flags = flags;
    }

    public Inet4Address getServer() {
      return server;
    }

    public Inet4Address getClient() {
      return client;
    }

    public int getPort() {
      return port;
    }

    public int getFlags() {
      return flags;
    }
  }

  /**
   * Evaluates whether the argument is a Teredo address.
   *
   *
Teredo addresses begin with the {@code "2001::/32"} prefix.
   *
   * @param ip {@link Inet6Address} to be examined for Teredo address format
   * @return {@code true} if the argument is a Teredo address
   */
  public static boolean isTeredoAddress(Inet6Address ip) {
    byte[] bytes = ip.getAddress();
    return (bytes[0] == (byte) 0x20)
        && (bytes[1] == (byte) 0x01)
        && (bytes[2] == 0)
        && (bytes[3] == 0);
  }

  /**
   * Returns the Teredo information embedded in a Teredo address.
   *
   * @param ip {@link Inet6Address} to be examined for embedded Teredo information
   * @return extracted {@code TeredoInfo}
   * @throws IllegalArgumentException if the argument is not a valid IPv6 Teredo address
   */
  public static TeredoInfo getTeredoInfo(Inet6Address ip) {
    checkArgument(isTeredoAddress(ip), "Address '%s' is not a Teredo address.", toAddrString(ip));

    byte[] bytes = ip.getAddress();
    Inet4Address server = getInet4Address(Arrays.copyOfRange(bytes, 4, 8));

    int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff;

    // Teredo obfuscates the mapped client port, per section 4 of the RFC.
    int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff;

    byte[] clientBytes = Arrays.copyOfRange(bytes, 12, 16);
    for (int i = 0; i < clientBytes.length; i++) {
      // Teredo obfuscates the mapped client IP, per section 4 of the RFC.
      clientBytes[i] = (byte) ~clientBytes[i];
    }
    Inet4Address client = getInet4Address(clientBytes);

    return new TeredoInfo(server, client, port, flags);
  }

  /**
   * Evaluates whether the argument is an ISATAP address.
   *
   *
From RFC 5214: "ISATAP interface identifiers are constructed in Modified EUI-64 format [...]
   * by concatenating the 24-bit IANA OUI (00-00-5E), the 8-bit hexadecimal value 0xFE, and a 32-bit
   * IPv4 address in network byte order [...]"
   *
   *
For more on ISATAP addresses see section 6.1 of RFC 5214.
   *
   * @param ip {@link Inet6Address} to be examined for ISATAP address format
   * @return {@code true} if the argument is an ISATAP address
   */
  public static boolean isIsatapAddress(Inet6Address ip) {

    // If it's a Teredo address with the right port (41217, or 0xa101)
    // which would be encoded as 0x5efe then it can't be an ISATAP address.
    if (isTeredoAddress(ip)) {
      return false;
    }

    byte[] bytes = ip.getAddress();

    if ((bytes[8] | (byte) 0x03) != (byte) 0x03) {

      // Verify that high byte of the 64 bit identifier is zero, modulo
      // the U/L and G bits, with which we are not concerned.
      return false;
    }

    return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e) && (bytes[11] == (byte) 0xfe);
  }

  /**
   * Returns the IPv4 address embedded in an ISATAP address.
   *
   * @param ip {@link Inet6Address} to be examined for embedded IPv4 in ISATAP address
   * @return {@link Inet4Address} of embedded IPv4 in an ISATAP address
   * @throws IllegalArgumentException if the argument is not a valid IPv6 ISATAP address
   */
  public static Inet4Address getIsatapIPv4Address(Inet6Address ip) {
    checkArgument(isIsatapAddress(ip), "Address '%s' is not an ISATAP address.", toAddrString(ip));

    return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16));
  }

  /**
   * Examines the Inet6Address to determine if it is an IPv6 address of one of the specified address
   * types that contain an embedded IPv4 address.
   *
   *
NOTE: ISATAP addresses are explicitly excluded from this method due to their trivial
   * spoofability. With other transition addresses spoofing involves (at least) infection of one's
   * BGP routing table.
   *
   * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
   * @return {@code true} if there is an embedded IPv4 client address
   * @since 7.0
   */
  public static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip) {
    return isCompatIPv4Address(ip) || is6to4Address(ip) || isTeredoAddress(ip);
  }

  /**
   * Examines the Inet6Address to extract the embedded IPv4 client address if the InetAddress is an
   * IPv6 address of one of the specified address types that contain an embedded IPv4 address.
   *
   *
NOTE: ISATAP addresses are explicitly excluded from this method due to their trivial
   * spoofability. With other transition addresses spoofing involves (at least) infection of one's
   * BGP routing table.
   *
   * @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
   * @return {@link Inet4Address} of embedded IPv4 client address
   * @throws IllegalArgumentException if the argument does not have a valid embedded IPv4 address
   */
  public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) {
    if (isCompatIPv4Address(ip)) {
      return getCompatIPv4Address(ip);
    }

    if (is6to4Address(ip)) {
      return get6to4IPv4Address(ip);
    }

    if (isTeredoAddress(ip)) {
      return getTeredoInfo(ip).getClient();
    }

    throw formatIllegalArgumentException("'%s' has no embedded IPv4 address.", toAddrString(ip));
  }

  /**
   * Evaluates whether the argument is an "IPv4 mapped" IPv6 address.
   *
   *
An "IPv4 mapped" address is anything in the range ::ffff:0:0/96 (sometimes written as
   * ::ffff:0.0.0.0/96), with the last 32 bits interpreted as an IPv4 address.
   *
   *
For more on IPv4 mapped addresses see section 2.5.5.2 of RFC 4291.
   *
   *
Note: This method takes a {@code String} argument because {@link InetAddress} automatically
   * collapses mapped addresses to IPv4. (It is actually possible to avoid this using one of the
   * obscure {@link Inet6Address} methods, but it would be unwise to depend on such a
   * poorly-documented feature.)
   *
   * @param ipString {@code String} to be examined for embedded IPv4-mapped IPv6 address format
   * @return {@code true} if the argument is a valid "mapped" address
   * @since 10.0
   */
  public static boolean isMappedIPv4Address(String ipString) {
    byte[] bytes = ipStringToBytes(ipString);
    if (bytes != null && bytes.length == 16) {
      for (int i = 0; i < 10; i++) {
        if (bytes[i] != 0) {
          return false;
        }
      }
      for (int i = 10; i < 12; i++) {
        if (bytes[i] != (byte) 0xff) {
          return false;
        }
      }
      return true;
    }
    return false;
  }

  /**
   * Coerces an IPv6 address into an IPv4 address.
   *
   *
HACK: As long as applications continue to use IPv4 addresses for indexing into tables,
   * accounting, et cetera, it may be necessary to coerce IPv6 addresses into IPv4 addresses.
   * This function does so by hashing the upper 64 bits into {@code 224.0.0.0/3} (64 bits into 29
   * bits).
   *
   *
A "coerced" IPv4 address is equivalent to itself.
   *
   *
NOTE: This function is failsafe for security purposes: ALL IPv6 addresses (except localhost
   * (::1)) are hashed to avoid the security risk associated with extracting an embedded IPv4
   * address that might permit elevated privileges.
   *
   * @param ip {@link InetAddress} to "coerce"
   * @return {@link Inet4Address} represented "coerced" address
   * @since 7.0
   */
  public static Inet4Address getCoercedIPv4Address(InetAddress ip) {
    if (ip instanceof Inet4Address) {
      return (Inet4Address) ip;
    }

    // Special cases:
    byte[] bytes = ip.getAddress();
    boolean leadingBytesOfZero = true;
    for (int i = 0; i < 15; ++i) {
      if (bytes[i] != 0) {
        leadingBytesOfZero = false;
        break;
      }
    }
    if (leadingBytesOfZero && (bytes[15] == 1)) {
      return LOOPBACK4; // ::1
    } else if (leadingBytesOfZero && (bytes[15] == 0)) {
      return ANY4; // ::0
    }

    Inet6Address ip6 = (Inet6Address) ip;
    long addressAsLong = 0;
    if (hasEmbeddedIPv4ClientAddress(ip6)) {
      addressAsLong = getEmbeddedIPv4ClientAddress(ip6).hashCode();
    } else {

      // Just extract the high 64 bits (assuming the rest is user-modifiable).
      addressAsLong = ByteBuffer.wrap(ip6.getAddress(), 0, 8).getLong();
    }

    // Many strategies for hashing are possible. This might suffice for now.
    int coercedHash = Hashing.murmur3_32().hashLong(addressAsLong).asInt();

    // Squash into 224/4 Multicast and 240/4 Reserved space (i.e. 224/3).
    coercedHash |= 0xe0000000;

    // Fixup to avoid some "illegal" values. Currently the only potential
    // illegal value is 255.255.255.255.
    if (coercedHash == 0xffffffff) {
      coercedHash = 0xfffffffe;
    }

    return getInet4Address(Ints.toByteArray(coercedHash));
  }

  /**
   * Returns an integer representing an IPv4 address regardless of whether the supplied argument is
   * an IPv4 address or not.
   *
   *
IPv6 addresses are coerced to IPv4 addresses before being converted to integers.
   *
   *
As long as there are applications that assume that all IP addresses are IPv4 addresses and
   * can therefore be converted safely to integers (for whatever purpose) this function can be used
   * to handle IPv6 addresses as well until the application is suitably fixed.
   *
   *
NOTE: an IPv6 address coerced to an IPv4 address can only be used for such purposes as
   * rudimentary identification or indexing into a collection of real {@link InetAddress}es. They
   * cannot be used as real addresses for the purposes of network communication.
   *
   * @param ip {@link InetAddress} to convert
   * @return {@code int}, "coerced" if ip is not an IPv4 address
   * @since 7.0
   */
  public static int coerceToInteger(InetAddress ip) {
    return ByteStreams.newDataInput(getCoercedIPv4Address(ip).getAddress()).readInt();
  }

  /**
   * Returns an Inet4Address having the integer value specified by the argument.
   *
   * @param address {@code int}, the 32bit integer address to be converted
   * @return {@link Inet4Address} equivalent of the argument
   */
  public static Inet4Address fromInteger(int address) {
    return getInet4Address(Ints.toByteArray(address));
  }

  /**
   * Returns an address from a little-endian ordered byte array (the opposite of what {@link
   * InetAddress#getByAddress} expects).
   *
   *
IPv4 address byte array must be 4 bytes long and IPv6 byte array must be 16 bytes long.
   *
   * @param addr the raw IP address in little-endian byte order
   * @return an InetAddress object created from the raw IP address
   * @throws UnknownHostException if IP address is of illegal length
   */
  public static InetAddress fromLittleEndianByteArray(byte[] addr) throws UnknownHostException {
    byte[] reversed = new byte[addr.length];
    for (int i = 0; i < addr.length; i++) {
      reversed[i] = addr[addr.length - i - 1];
    }
    return InetAddress.getByAddress(reversed);
  }

  /**
   * Returns a new InetAddress that is one less than the passed in address. This method works for
   * both IPv4 and IPv6 addresses.
   *
   * @param address the InetAddress to decrement
   * @return a new InetAddress that is one less than the passed in address
   * @throws IllegalArgumentException if InetAddress is at the beginning of its range
   * @since 18.0
   */
  public static InetAddress decrement(InetAddress address) {
    byte[] addr = address.getAddress();
    int i = addr.length - 1;
    while (i >= 0 && addr[i] == (byte) 0x00) {
      addr[i] = (byte) 0xff;
      i--;
    }

    checkArgument(i >= 0, "Decrementing %s would wrap.", address);

    addr[i]--;
    return bytesToInetAddress(addr);
  }

  /**
   * Returns a new InetAddress that is one more than the passed in address. This method works for
   * both IPv4 and IPv6 addresses.
   *
   * @param address the InetAddress to increment
   * @return a new InetAddress that is one more than the passed in address
   * @throws IllegalArgumentException if InetAddress is at the end of its range
   * @since 10.0
   */
  public static InetAddress increment(InetAddress address) {
    byte[] addr = address.getAddress();
    int i = addr.length - 1;
    while (i >= 0 && addr[i] == (byte) 0xff) {
      addr[i] = 0;
      i--;
    }

    checkArgument(i >= 0, "Incrementing %s would wrap.", address);

    addr[i]++;
    return bytesToInetAddress(addr);
  }

  /**
   * Returns true if the InetAddress is either 255.255.255.255 for IPv4 or
   * ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6.
   *
   * @return true if the InetAddress is either 255.255.255.255 for IPv4 or
   *     ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6
   * @since 10.0
   */
  public static boolean isMaximum(InetAddress address) {
    byte[] addr = address.getAddress();
    for (int i = 0; i < addr.length; i++) {
      if (addr[i] != (byte) 0xff) {
        return false;
      }
    }
    return true;
  }

  private static IllegalArgumentException formatIllegalArgumentException(
      String format, Object... args) {
    return new IllegalArgumentException(String.format(Locale.ROOT, format, args));
  }
}


/*
 * Copyright (C) 2018 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.collect;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.RegularImmutableMap.makeImmutable;

import com.google.common.annotations.GwtCompatible;
import java.util.Map;
import java.util.function.BiConsumer;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * Implementation of ImmutableMap backed by a JDK HashMap, which has smartness protecting against
 * hash flooding.
 */
@GwtCompatible(emulated = true)
final class JdkBackedImmutableMap<K, V> extends ImmutableMap<K, V> {
  /**
   * Creates an {@code ImmutableMap} backed by a JDK HashMap. Used when probable hash flooding is
   * detected. This implementation may replace the entries in entryArray with its own entry objects
   * (though they will have the same key/value contents), and will take ownership of entryArray.
   */
  static <K, V> ImmutableMap<K, V> create(int n, Entry<K, V>[] entryArray) {
    Map<K, V> delegateMap = Maps.newHashMapWithExpectedSize(n);
    for (int i = 0; i < n; i++) {
      entryArray[i] = makeImmutable(entryArray[i]);
      V oldValue = delegateMap.putIfAbsent(entryArray[i].getKey(), entryArray[i].getValue());
      if (oldValue != null) {
        throw conflictException("key", entryArray[i], entryArray[i].getKey() + "=" + oldValue);
      }
    }
    return new JdkBackedImmutableMap<>(delegateMap, ImmutableList.asImmutableList(entryArray, n));
  }

  private final transient Map<K, V> delegateMap;
  private final transient ImmutableList<Entry<K, V>> entries;

  JdkBackedImmutableMap(Map<K, V> delegateMap, ImmutableList<Entry<K, V>> entries) {
    this.delegateMap = delegateMap;
    this.entries = entries;
  }

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

  @Override
  public V get(@Nullable Object key) {
    return delegateMap.get(key);
  }

  @Override
  ImmutableSet<Entry<K, V>> createEntrySet() {
    return new ImmutableMapEntrySet.RegularEntrySet<K, V>(this, entries);
  }

  @Override
  public void forEach(BiConsumer<? super K, ? super V> action) {
    checkNotNull(action);
    entries.forEach(e -> action.accept(e.getKey(), e.getValue()));
  }

  @Override
  ImmutableSet<K> createKeySet() {
    return new ImmutableMapKeySet<K, V>(this);
  }

  @Override
  ImmutableCollection<V> createValues() {
    return new ImmutableMapValues<K, V>(this);
  }

  @Override
  boolean isPartialView() {
    return false;
  }
}