/*
 * 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.base.Preconditions.checkState;
import static com.google.common.base.Predicates.instanceOf;
import static com.google.common.collect.CollectPreconditions.checkRemove;

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * This class contains static utility methods that operate on or return objects of type {@link
 * Iterator}. Except as noted, each method has a corresponding {@link Iterable}-based method in the
 * {@link Iterables} class.
 *
 *
Performance notes: Unless otherwise noted, all of the iterators produced in this class
 * are lazy, which means that they only advance the backing iteration when absolutely
 * necessary.
 *
 *
See the Guava User Guide section on  {@code
 * Iterators}.
 *
 * @author Kevin Bourrillion
 * @author Jared Levy
 * @since 2.0
 */
@GwtCompatible(emulated = true)
public final class Iterators {
  private Iterators() {}

  /**
   * Returns the empty iterator.
   *
   *
The {@link Iterable} equivalent of this method is {@link ImmutableSet#of()}.
   */
  static <T> UnmodifiableIterator<T> emptyIterator() {
    return emptyListIterator();
  }

  /**
   * Returns the empty iterator.
   *
   *
The {@link Iterable} equivalent of this method is {@link ImmutableSet#of()}.
   */
  // Casting to any type is safe since there are no actual elements.
  @SuppressWarnings("unchecked")
  static <T> UnmodifiableListIterator<T> emptyListIterator() {
    return (UnmodifiableListIterator<T>) ArrayItr.EMPTY;
  }

  /**
   * This is an enum singleton rather than an anonymous class so ProGuard can figure out it's only
   * referenced by emptyModifiableIterator().
   */
  private enum EmptyModifiableIterator implements Iterator<Object> {
    INSTANCE;

    @Override
    public boolean hasNext() {
      return false;
    }

    @Override
    public Object next() {
      throw new NoSuchElementException();
    }

    @Override
    public void remove() {
      checkRemove(false);
    }
  }

  /**
   * Returns the empty {@code Iterator} that throws {@link IllegalStateException} instead of {@link
   * UnsupportedOperationException} on a call to {@link Iterator#remove()}.
   */
  // Casting to any type is safe since there are no actual elements.
  @SuppressWarnings("unchecked")
  static <T> Iterator<T> emptyModifiableIterator() {
    return (Iterator<T>) EmptyModifiableIterator.INSTANCE;
  }

  /** Returns an unmodifiable view of {@code iterator}. */
  public static <T> UnmodifiableIterator<T> unmodifiableIterator(
      final Iterator<? extends T> iterator) {
    checkNotNull(iterator);
    if (iterator instanceof UnmodifiableIterator) {
      @SuppressWarnings("unchecked") // Since it's unmodifiable, the covariant cast is safe
      UnmodifiableIterator<T> result = (UnmodifiableIterator<T>) iterator;
      return result;
    }
    return new UnmodifiableIterator<T>() {
      @Override
      public boolean hasNext() {
        return iterator.hasNext();
      }

      @Override
      public T next() {
        return iterator.next();
      }
    };
  }

  /**
   * Simply returns its argument.
   *
   * @deprecated no need to use this
   * @since 10.0
   */
  @Deprecated
  public static <T> UnmodifiableIterator<T> unmodifiableIterator(UnmodifiableIterator<T> iterator) {
    return checkNotNull(iterator);
  }

  /**
   * Returns the number of elements remaining in {@code iterator}. The iterator will be left
   * exhausted: its {@code hasNext()} method will return {@code false}.
   */
  public static int size(Iterator<?> iterator) {
    long count = 0L;
    while (iterator.hasNext()) {
      iterator.next();
      count++;
    }
    return Ints.saturatedCast(count);
  }

  /** Returns {@code true} if {@code iterator} contains {@code element}. */
  public static boolean contains(Iterator<?> iterator, @Nullable Object element) {
    if (element == null) {
      while (iterator.hasNext()) {
        if (iterator.next() == null) {
          return true;
        }
      }
    } else {
      while (iterator.hasNext()) {
        if (element.equals(iterator.next())) {
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Traverses an iterator and removes every element that belongs to the provided collection. The
   * iterator will be left exhausted: its {@code hasNext()} method will return {@code false}.
   *
   * @param removeFrom the iterator to (potentially) remove elements from
   * @param elementsToRemove the elements to remove
   * @return {@code true} if any element was removed from {@code iterator}
   */
  @CanIgnoreReturnValue
  public static boolean removeAll(Iterator<?> removeFrom, Collection<?> elementsToRemove) {
    checkNotNull(elementsToRemove);
    boolean result = false;
    while (removeFrom.hasNext()) {
      if (elementsToRemove.contains(removeFrom.next())) {
        removeFrom.remove();
        result = true;
      }
    }
    return result;
  }

  /**
   * Removes every element that satisfies the provided predicate from the iterator. The iterator
   * will be left exhausted: its {@code hasNext()} method will return {@code false}.
   *
   * @param removeFrom the iterator to (potentially) remove elements from
   * @param predicate a predicate that determines whether an element should be removed
   * @return {@code true} if any elements were removed from the iterator
   * @since 2.0
   */
  @CanIgnoreReturnValue
  public static <T> boolean removeIf(Iterator<T> removeFrom, Predicate<? super T> predicate) {
    checkNotNull(predicate);
    boolean modified = false;
    while (removeFrom.hasNext()) {
      if (predicate.apply(removeFrom.next())) {
        removeFrom.remove();
        modified = true;
      }
    }
    return modified;
  }

  /**
   * Traverses an iterator and removes every element that does not belong to the provided
   * collection. The iterator will be left exhausted: its {@code hasNext()} method will return
   * {@code false}.
   *
   * @param removeFrom the iterator to (potentially) remove elements from
   * @param elementsToRetain the elements to retain
   * @return {@code true} if any element was removed from {@code iterator}
   */
  @CanIgnoreReturnValue
  public static boolean retainAll(Iterator<?> removeFrom, Collection<?> elementsToRetain) {
    checkNotNull(elementsToRetain);
    boolean result = false;
    while (removeFrom.hasNext()) {
      if (!elementsToRetain.contains(removeFrom.next())) {
        removeFrom.remove();
        result = true;
      }
    }
    return result;
  }

  /**
   * Determines whether two iterators contain equal elements in the same order. More specifically,
   * this method returns {@code true} if {@code iterator1} and {@code iterator2} contain the same
   * number of elements and every element of {@code iterator1} is equal to the corresponding element
   * of {@code iterator2}.
   *
   *
Note that this will modify the supplied iterators, since they will have been advanced some
   * number of elements forward.
   */
  public static boolean elementsEqual(Iterator<?> iterator1, Iterator<?> iterator2) {
    while (iterator1.hasNext()) {
      if (!iterator2.hasNext()) {
        return false;
      }
      Object o1 = iterator1.next();
      Object o2 = iterator2.next();
      if (!Objects.equal(o1, o2)) {
        return false;
      }
    }
    return !iterator2.hasNext();
  }

  /**
   * Returns a string representation of {@code iterator}, with the format {@code [e1, e2, ..., en]}.
   * The iterator will be left exhausted: its {@code hasNext()} method will return {@code false}.
   */
  public static String toString(Iterator<?> iterator) {
    StringBuilder sb = new StringBuilder().append('[');
    boolean first = true;
    while (iterator.hasNext()) {
      if (!first) {
        sb.append(", ");
      }
      first = false;
      sb.append(iterator.next());
    }
    return sb.append(']').toString();
  }

  /**
   * Returns the single element contained in {@code iterator}.
   *
   * @throws NoSuchElementException if the iterator is empty
   * @throws IllegalArgumentException if the iterator contains multiple elements. The state of the
   *     iterator is unspecified.
   */
  public static <T> T getOnlyElement(Iterator<T> iterator) {
    T first = iterator.next();
    if (!iterator.hasNext()) {
      return first;
    }

    StringBuilder sb = new StringBuilder().append("expected one element but was: <").append(first);
    for (int i = 0; i < 4 && iterator.hasNext(); i++) {
      sb.append(", ").append(iterator.next());
    }
    if (iterator.hasNext()) {
      sb.append(", ...");
    }
    sb.append('>');

    throw new IllegalArgumentException(sb.toString());
  }

  /**
   * Returns the single element contained in {@code iterator}, or {@code defaultValue} if the
   * iterator is empty.
   *
   * @throws IllegalArgumentException if the iterator contains multiple elements. The state of the
   *     iterator is unspecified.
   */
  public static <T> @Nullable T getOnlyElement(
      Iterator<? extends T> iterator, @Nullable T defaultValue) {
    return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue;
  }

  /**
   * Copies an iterator's elements into an array. The iterator will be left exhausted: its {@code
   * hasNext()} method will return {@code false}.
   *
   * @param iterator the iterator to copy
   * @param type the type of the elements
   * @return a newly-allocated array into which all the elements of the iterator have been copied
   */
  @GwtIncompatible // Array.newInstance(Class, int)
  public static <T> T[] toArray(Iterator<? extends T> iterator, Class<T> type) {
    List<T> list = Lists.newArrayList(iterator);
    return Iterables.toArray(list, type);
  }

  /**
   * Adds all elements in {@code iterator} to {@code collection}. The iterator will be left
   * exhausted: its {@code hasNext()} method will return {@code false}.
   *
   * @return {@code true} if {@code collection} was modified as a result of this operation
   */
  @CanIgnoreReturnValue
  public static <T> boolean addAll(Collection<T> addTo, Iterator<? extends T> iterator) {
    checkNotNull(addTo);
    checkNotNull(iterator);
    boolean wasModified = false;
    while (iterator.hasNext()) {
      wasModified |= addTo.add(iterator.next());
    }
    return wasModified;
  }

  /**
   * Returns the number of elements in the specified iterator that equal the specified object. The
   * iterator will be left exhausted: its {@code hasNext()} method will return {@code false}.
   *
   * @see Collections#frequency
   */
  public static int frequency(Iterator<?> iterator, @Nullable Object element) {
    int count = 0;
    while (contains(iterator, element)) {
      // Since it lives in the same class, we know contains gets to the element and then stops,
      // though that isn't currently publicly documented.
      count++;
    }
    return count;
  }

  /**
   * Returns an iterator that cycles indefinitely over the elements of {@code iterable}.
   *
   *
The returned iterator supports {@code remove()} if the provided iterator does. After {@code
   * remove()} is called, subsequent cycles omit the removed element, which is no longer in {@code
   * iterable}. The iterator's {@code hasNext()} method returns {@code true} until {@code iterable}
   * is empty.
   *
   *
Warning: Typical uses of the resulting iterator may produce an infinite loop. You
   * should use an explicit {@code break} or be certain that you will eventually remove all the
   * elements.
   */
  public static <T> Iterator<T> cycle(final Iterable<T> iterable) {
    checkNotNull(iterable);
    return new Iterator<T>() {
      Iterator<T> iterator = emptyModifiableIterator();

      @Override
      public boolean hasNext() {
        /*
         * Don't store a new Iterator until we know the user can't remove() the last returned
         * element anymore. Otherwise, when we remove from the old iterator, we may be invalidating
         * the new one. The result is a ConcurrentModificationException or other bad behavior.
         *
         * (If we decide that we really, really hate allocating two Iterators per cycle instead of
         * one, we can optimistically store the new Iterator and then be willing to throw it out if
         * the user calls remove().)
         */
        return iterator.hasNext() || iterable.iterator().hasNext();
      }

      @Override
      public T next() {
        if (!iterator.hasNext()) {
          iterator = iterable.iterator();
          if (!iterator.hasNext()) {
            throw new NoSuchElementException();
          }
        }
        return iterator.next();
      }

      @Override
      public void remove() {
        iterator.remove();
      }
    };
  }

  /**
   * Returns an iterator that cycles indefinitely over the provided elements.
   *
   *
The returned iterator supports {@code remove()}. After {@code remove()} is called,
   * subsequent cycles omit the removed element, but {@code elements} does not change. The
   * iterator's {@code hasNext()} method returns {@code true} until all of the original elements
   * have been removed.
   *
   *
Warning: Typical uses of the resulting iterator may produce an infinite loop. You
   * should use an explicit {@code break} or be certain that you will eventually remove all the
   * elements.
   */
  @SafeVarargs
  public static <T> Iterator<T> cycle(T... elements) {
    return cycle(Lists.newArrayList(elements));
  }

  /**
   * Returns an Iterator that walks the specified array, nulling out elements behind it. This can
   * avoid memory leaks when an element is no longer necessary.
   *
   *
This is mainly just to avoid the intermediate ArrayDeque in ConsumingQueueIterator.
   */
  private static <T> Iterator<T> consumingForArray(final T... elements) {
    return new UnmodifiableIterator<T>() {
      int index = 0;

      @Override
      public boolean hasNext() {
        return index < elements.length;
      }

      @Override
      public T next() {
        if (!hasNext()) {
          throw new NoSuchElementException();
        }
        T result = elements[index];
        elements[index] = null;
        index++;
        return result;
      }
    };
  }

  /**
   * Combines two iterators into a single iterator. The returned iterator iterates across the
   * elements in {@code a}, followed by the elements in {@code b}. The source iterators are not
   * polled until necessary.
   *
   *
The returned iterator supports {@code remove()} when the corresponding input iterator
   * supports it.
   */
  public static <T> Iterator<T> concat(Iterator<? extends T> a, Iterator<? extends T> b) {
    checkNotNull(a);
    checkNotNull(b);
    return concat(consumingForArray(a, b));
  }

  /**
   * Combines three iterators into a single iterator. The returned iterator iterates across the
   * elements in {@code a}, followed by the elements in {@code b}, followed by the elements in
   * {@code c}. The source iterators are not polled until necessary.
   *
   *
The returned iterator supports {@code remove()} when the corresponding input iterator
   * supports it.
   */
  public static <T> Iterator<T> concat(
      Iterator<? extends T> a, Iterator<? extends T> b, Iterator<? extends T> c) {
    checkNotNull(a);
    checkNotNull(b);
    checkNotNull(c);
    return concat(consumingForArray(a, b, c));
  }

  /**
   * Combines four iterators into a single iterator. The returned iterator iterates across the
   * elements in {@code a}, followed by the elements in {@code b}, followed by the elements in
   * {@code c}, followed by the elements in {@code d}. The source iterators are not polled until
   * necessary.
   *
   *
The returned iterator supports {@code remove()} when the corresponding input iterator
   * supports it.
   */
  public static <T> Iterator<T> concat(
      Iterator<? extends T> a,
      Iterator<? extends T> b,
      Iterator<? extends T> c,
      Iterator<? extends T> d) {
    checkNotNull(a);
    checkNotNull(b);
    checkNotNull(c);
    checkNotNull(d);
    return concat(consumingForArray(a, b, c, d));
  }

  /**
   * Combines multiple iterators into a single iterator. The returned iterator iterates across the
   * elements of each iterator in {@code inputs}. The input iterators are not polled until
   * necessary.
   *
   *
The returned iterator supports {@code remove()} when the corresponding input iterator
   * supports it.
   *
   * @throws NullPointerException if any of the provided iterators is null
   */
  public static <T> Iterator<T> concat(Iterator<? extends T>... inputs) {
    return concatNoDefensiveCopy(Arrays.copyOf(inputs, inputs.length));
  }

  /**
   * Combines multiple iterators into a single iterator. The returned iterator iterates across the
   * elements of each iterator in {@code inputs}. The input iterators are not polled until
   * necessary.
   *
   *
The returned iterator supports {@code remove()} when the corresponding input iterator
   * supports it. The methods of the returned iterator may throw {@code NullPointerException} if any
   * of the input iterators is null.
   */
  public static <T> Iterator<T> concat(Iterator<? extends Iterator<? extends T>> inputs) {
    return new ConcatenatedIterator<T>(inputs);
  }

  /** Concats a varargs array of iterators without making a defensive copy of the array. */
  static <T> Iterator<T> concatNoDefensiveCopy(Iterator<? extends T>... inputs) {
    for (Iterator<? extends T> input : checkNotNull(inputs)) {
      checkNotNull(input);
    }
    return concat(consumingForArray(inputs));
  }

  /**
   * Divides an iterator into unmodifiable sublists of the given size (the final list may be
   * smaller). For example, partitioning an iterator containing {@code [a, b, c, d, e]} with a
   * partition size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer iterator containing two
   * inner lists of three and two elements, all in the original order.
   *
   *
The returned lists implement {@link java.util.RandomAccess}.
   *
   * @param iterator the iterator to return a partitioned view of
   * @param size the desired size of each partition (the last may be smaller)
   * @return an iterator of immutable lists containing the elements of {@code iterator} divided into
   *     partitions
   * @throws IllegalArgumentException if {@code size} is nonpositive
   */
  public static <T> UnmodifiableIterator<List<T>> partition(Iterator<T> iterator, int size) {
    return partitionImpl(iterator, size, false);
  }

  /**
   * Divides an iterator into unmodifiable sublists of the given size, padding the final iterator
   * with null values if necessary. For example, partitioning an iterator containing {@code [a, b,
   * c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e, null]]} -- an outer
   * iterator containing two inner lists of three elements each, all in the original order.
   *
   *
The returned lists implement {@link java.util.RandomAccess}.
   *
   * @param iterator the iterator to return a partitioned view of
   * @param size the desired size of each partition
   * @return an iterator of immutable lists containing the elements of {@code iterator} divided into
   *     partitions (the final iterable may have trailing null elements)
   * @throws IllegalArgumentException if {@code size} is nonpositive
   */
  public static <T> UnmodifiableIterator<List<T>> paddedPartition(Iterator<T> iterator, int size) {
    return partitionImpl(iterator, size, true);
  }

  private static <T> UnmodifiableIterator<List<T>> partitionImpl(
      final Iterator<T> iterator, final int size, final boolean pad) {
    checkNotNull(iterator);
    checkArgument(size > 0);
    return new UnmodifiableIterator<List<T>>() {
      @Override
      public boolean hasNext() {
        return iterator.hasNext();
      }

      @Override
      public List<T> next() {
        if (!hasNext()) {
          throw new NoSuchElementException();
        }
        Object[] array = new Object[size];
        int count = 0;
        for (; count < size && iterator.hasNext(); count++) {
          array[count] = iterator.next();
        }
        for (int i = count; i < size; i++) {
          array[i] = null; // for GWT
        }

        @SuppressWarnings("unchecked") // we only put Ts in it
        List<T> list = Collections.unmodifiableList((List<T>) Arrays.asList(array));
        return (pad || count == size) ? list : list.subList(0, count);
      }
    };
  }

  /**
   * Returns a view of {@code unfiltered} containing all elements that satisfy the input predicate
   * {@code retainIfTrue}.
   */
  public static <T> UnmodifiableIterator<T> filter(
      final Iterator<T> unfiltered, final Predicate<? super T> retainIfTrue) {
    checkNotNull(unfiltered);
    checkNotNull(retainIfTrue);
    return new AbstractIterator<T>() {
      @Override
      protected T computeNext() {
        while (unfiltered.hasNext()) {
          T element = unfiltered.next();
          if (retainIfTrue.apply(element)) {
            return element;
          }
        }
        return endOfData();
      }
    };
  }

  /**
   * Returns a view of {@code unfiltered} containing all elements that are of the type {@code
   * desiredType}.
   */
  @SuppressWarnings("unchecked") // can cast to <T> because non-Ts are removed
  @GwtIncompatible // Class.isInstance
  public static <T> UnmodifiableIterator<T> filter(Iterator<?> unfiltered, Class<T> desiredType) {
    return (UnmodifiableIterator<T>) filter(unfiltered, instanceOf(desiredType));
  }

  /**
   * Returns {@code true} if one or more elements returned by {@code iterator} satisfy the given
   * predicate.
   */
  public static <T> boolean any(Iterator<T> iterator, Predicate<? super T> predicate) {
    return indexOf(iterator, predicate) != -1;
  }

  /**
   * Returns {@code true} if every element returned by {@code iterator} satisfies the given
   * predicate. If {@code iterator} is empty, {@code true} is returned.
   */
  public static <T> boolean all(Iterator<T> iterator, Predicate<? super T> predicate) {
    checkNotNull(predicate);
    while (iterator.hasNext()) {
      T element = iterator.next();
      if (!predicate.apply(element)) {
        return false;
      }
    }
    return true;
  }

  /**
   * Returns the first element in {@code iterator} that satisfies the given predicate; use this
   * method only when such an element is known to exist. If no such element is found, the iterator
   * will be left exhausted: its {@code hasNext()} method will return {@code false}. If it is
   * possible that no element will match, use {@link #tryFind} or {@link #find(Iterator,
   * Predicate, Object)} instead.
   *
   * @throws NoSuchElementException if no element in {@code iterator} matches the given predicate
   */
  public static <T> T find(Iterator<T> iterator, Predicate<? super T> predicate) {
    checkNotNull(iterator);
    checkNotNull(predicate);
    while (iterator.hasNext()) {
      T t = iterator.next();
      if (predicate.apply(t)) {
        return t;
      }
    }
    throw new NoSuchElementException();
  }

  /**
   * Returns the first element in {@code iterator} that satisfies the given predicate. If no such
   * element is found, {@code defaultValue} will be returned from this method and the iterator will
   * be left exhausted: its {@code hasNext()} method will return {@code false}. Note that this can
   * usually be handled more naturally using {@code tryFind(iterator, predicate).or(defaultValue)}.
   *
   * @since 7.0
   */
  public static <T> @Nullable T find(
      Iterator<? extends T> iterator, Predicate<? super T> predicate, @Nullable T defaultValue) {
    checkNotNull(iterator);
    checkNotNull(predicate);
    while (iterator.hasNext()) {
      T t = iterator.next();
      if (predicate.apply(t)) {
        return t;
      }
    }
    return defaultValue;
  }

  /**
   * Returns an {@link Optional} containing the first element in {@code iterator} that satisfies the
   * given predicate, if such an element exists. If no such element is found, an empty {@link
   * Optional} will be returned from this method and the iterator will be left exhausted: its {@code
   * hasNext()} method will return {@code false}.
   *
   *
Warning: avoid using a {@code predicate} that matches {@code null}. If {@code null}
   * is matched in {@code iterator}, a NullPointerException will be thrown.
   *
   * @since 11.0
   */
  public static <T> Optional<T> tryFind(Iterator<T> iterator, Predicate<? super T> predicate) {
    checkNotNull(iterator);
    checkNotNull(predicate);
    while (iterator.hasNext()) {
      T t = iterator.next();
      if (predicate.apply(t)) {
        return Optional.of(t);
      }
    }
    return Optional.absent();
  }

  /**
   * Returns the index in {@code iterator} of the first element that satisfies the provided {@code
   * predicate}, or {@code -1} if the Iterator has no such elements.
   *
   *
More formally, returns the lowest index {@code i} such that {@code
   * predicate.apply(Iterators.get(iterator, i))} returns {@code true}, or {@code -1} if there is no
   * such index.
   *
   *
If -1 is returned, the iterator will be left exhausted: its {@code hasNext()} method will
   * return {@code false}. Otherwise, the iterator will be set to the element which satisfies the
   * {@code predicate}.
   *
   * @since 2.0
   */
  public static <T> int indexOf(Iterator<T> iterator, Predicate<? super T> predicate) {
    checkNotNull(predicate, "predicate");
    for (int i = 0; iterator.hasNext(); i++) {
      T current = iterator.next();
      if (predicate.apply(current)) {
        return i;
      }
    }
    return -1;
  }

  /**
   * Returns a view containing the result of applying {@code function} to each element of {@code
   * fromIterator}.
   *
   *
The returned iterator supports {@code remove()} if {@code fromIterator} does. After a
   * successful {@code remove()} call, {@code fromIterator} no longer contains the corresponding
   * element.
   */
  public static <F, T> Iterator<T> transform(
      final Iterator<F> fromIterator, final Function<? super F, ? extends T> function) {
    checkNotNull(function);
    return new TransformedIterator<F, T>(fromIterator) {
      @Override
      T transform(F from) {
        return function.apply(from);
      }
    };
  }

  /**
   * Advances {@code iterator} {@code position + 1} times, returning the element at the {@code
   * position}th position.
   *
   * @param position position of the element to return
   * @return the element at the specified position in {@code iterator}
   * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to
   *     the number of elements remaining in {@code iterator}
   */
  public static <T> T get(Iterator<T> iterator, int position) {
    checkNonnegative(position);
    int skipped = advance(iterator, position);
    if (!iterator.hasNext()) {
      throw new IndexOutOfBoundsException(
          "position ("
              + position
              + ") must be less than the number of elements that remained ("
              + skipped
              + ")");
    }
    return iterator.next();
  }

  /**
   * Advances {@code iterator} {@code position + 1} times, returning the element at the {@code
   * position}th position or {@code defaultValue} otherwise.
   *
   * @param position position of the element to return
   * @param defaultValue the default value to return if the iterator is empty or if {@code position}
   *     is greater than the number of elements remaining in {@code iterator}
   * @return the element at the specified position in {@code iterator} or {@code defaultValue} if
   *     {@code iterator} produces fewer than {@code position + 1} elements.
   * @throws IndexOutOfBoundsException if {@code position} is negative
   * @since 4.0
   */
  public static <T> @Nullable T get(
      Iterator<? extends T> iterator, int position, @Nullable T defaultValue) {
    checkNonnegative(position);
    advance(iterator, position);
    return getNext(iterator, defaultValue);
  }

  static void checkNonnegative(int position) {
    if (position < 0) {
      throw new IndexOutOfBoundsException("position (" + position + ") must not be negative");
    }
  }

  /**
   * Returns the next element in {@code iterator} or {@code defaultValue} if the iterator is empty.
   * The {@link Iterables} analog to this method is {@link Iterables#getFirst}.
   *
   * @param defaultValue the default value to return if the iterator is empty
   * @return the next element of {@code iterator} or the default value
   * @since 7.0
   */
  public static <T> @Nullable T getNext(Iterator<? extends T> iterator, @Nullable T defaultValue) {
    return iterator.hasNext() ? iterator.next() : defaultValue;
  }

  /**
   * Advances {@code iterator} to the end, returning the last element.
   *
   * @return the last element of {@code iterator}
   * @throws NoSuchElementException if the iterator is empty
   */
  public static <T> T getLast(Iterator<T> iterator) {
    while (true) {
      T current = iterator.next();
      if (!iterator.hasNext()) {
        return current;
      }
    }
  }

  /**
   * Advances {@code iterator} to the end, returning the last element or {@code defaultValue} if the
   * iterator is empty.
   *
   * @param defaultValue the default value to return if the iterator is empty
   * @return the last element of {@code iterator}
   * @since 3.0
   */
  public static <T> @Nullable T getLast(Iterator<? extends T> iterator, @Nullable T defaultValue) {
    return iterator.hasNext() ? getLast(iterator) : defaultValue;
  }

  /**
   * Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} times or until {@code
   * hasNext()} returns {@code false}, whichever comes first.
   *
   * @return the number of elements the iterator was advanced
   * @since 13.0 (since 3.0 as {@code Iterators.skip})
   */
  @CanIgnoreReturnValue
  public static int advance(Iterator<?> iterator, int numberToAdvance) {
    checkNotNull(iterator);
    checkArgument(numberToAdvance >= 0, "numberToAdvance must be nonnegative");

    int i;
    for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) {
      iterator.next();
    }
    return i;
  }

  /**
   * Returns a view containing the first {@code limitSize} elements of {@code iterator}. If {@code
   * iterator} contains fewer than {@code limitSize} elements, the returned view contains all of its
   * elements. The returned iterator supports {@code remove()} if {@code iterator} does.
   *
   * @param iterator the iterator to limit
   * @param limitSize the maximum number of elements in the returned iterator
   * @throws IllegalArgumentException if {@code limitSize} is negative
   * @since 3.0
   */
  public static <T> Iterator<T> limit(final Iterator<T> iterator, final int limitSize) {
    checkNotNull(iterator);
    checkArgument(limitSize >= 0, "limit is negative");
    return new Iterator<T>() {
      private int count;

      @Override
      public boolean hasNext() {
        return count < limitSize && iterator.hasNext();
      }

      @Override
      public T next() {
        if (!hasNext()) {
          throw new NoSuchElementException();
        }
        count++;
        return iterator.next();
      }

      @Override
      public void remove() {
        iterator.remove();
      }
    };
  }

  /**
   * Returns a view of the supplied {@code iterator} that removes each element from the supplied
   * {@code iterator} as it is returned.
   *
   *
The provided iterator must support {@link Iterator#remove()} or else the returned iterator
   * will fail on the first call to {@code next}.
   *
   * @param iterator the iterator to remove and return elements from
   * @return an iterator that removes and returns elements from the supplied iterator
   * @since 2.0
   */
  public static <T> Iterator<T> consumingIterator(final Iterator<T> iterator) {
    checkNotNull(iterator);
    return new UnmodifiableIterator<T>() {
      @Override
      public boolean hasNext() {
        return iterator.hasNext();
      }

      @Override
      public T next() {
        T next = iterator.next();
        iterator.remove();
        return next;
      }

      @Override
      public String toString() {
        return "Iterators.consumingIterator(...)";
      }
    };
  }

  /**
   * Deletes and returns the next value from the iterator, or returns {@code null} if there is no
   * such value.
   */
  static <T> @Nullable T pollNext(Iterator<T> iterator) {
    if (iterator.hasNext()) {
      T result = iterator.next();
      iterator.remove();
      return result;
    } else {
      return null;
    }
  }

  // Methods only in Iterators, not in Iterables

  /** Clears the iterator using its remove method. */
  static void clear(Iterator<?> iterator) {
    checkNotNull(iterator);
    while (iterator.hasNext()) {
      iterator.next();
      iterator.remove();
    }
  }

  /**
   * Returns an iterator containing the elements of {@code array} in order. The returned iterator is
   * a view of the array; subsequent changes to the array will be reflected in the iterator.
   *
   *
Note: It is often preferable to represent your data using a collection type, for
   * example using {@link Arrays#asList(Object[])}, making this method unnecessary.
   *
   *
The {@code Iterable} equivalent of this method is either {@link Arrays#asList(Object[])},
   * {@link ImmutableList#copyOf(Object[])}}, or {@link ImmutableList#of}.
   */
  @SafeVarargs
  public static <T> UnmodifiableIterator<T> forArray(final T... array) {
    return forArray(array, 0, array.length, 0);
  }

  /**
   * Returns a list iterator containing the elements in the specified range of {@code array} in
   * order, starting at the specified index.
   *
   *
The {@code Iterable} equivalent of this method is {@code
   * Arrays.asList(array).subList(offset, offset + length).listIterator(index)}.
   */
  static <T> UnmodifiableListIterator<T> forArray(
      final T[] array, final int offset, int length, int index) {
    checkArgument(length >= 0);
    int end = offset + length;

    // Technically we should give a slightly more descriptive error on overflow
    Preconditions.checkPositionIndexes(offset, end, array.length);
    Preconditions.checkPositionIndex(index, length);
    if (length == 0) {
      return emptyListIterator();
    }
    return new ArrayItr<T>(array, offset, length, index);
  }

  private static final class ArrayItr<T> extends AbstractIndexedListIterator<T> {
    static final UnmodifiableListIterator<Object> EMPTY = new ArrayItr<>(new Object[0], 0, 0, 0);

    private final T[] array;
    private final int offset;

    ArrayItr(T[] array, int offset, int length, int index) {
      super(length, index);
      this.array = array;
      this.offset = offset;
    }

    @Override
    protected T get(int index) {
      return array[offset + index];
    }
  }

  /**
   * Returns an iterator containing only {@code value}.
   *
   *
The {@link Iterable} equivalent of this method is {@link Collections#singleton}.
   */
  public static <T> UnmodifiableIterator<T> singletonIterator(final @Nullable T value) {
    return new UnmodifiableIterator<T>() {
      boolean done;

      @Override
      public boolean hasNext() {
        return !done;
      }

      @Override
      public T next() {
        if (done) {
          throw new NoSuchElementException();
        }
        done = true;
        return value;
      }
    };
  }

  /**
   * Adapts an {@code Enumeration} to the {@code Iterator} interface.
   *
   *
This method has no equivalent in {@link Iterables} because viewing an {@code Enumeration} as
   * an {@code Iterable} is impossible. However, the contents can be copied into a collection
   * using {@link Collections#list}.
   */
  public static <T> UnmodifiableIterator<T> forEnumeration(final Enumeration<T> enumeration) {
    checkNotNull(enumeration);
    return new UnmodifiableIterator<T>() {
      @Override
      public boolean hasNext() {
        return enumeration.hasMoreElements();
      }

      @Override
      public T next() {
        return enumeration.nextElement();
      }
    };
  }

  /**
   * Adapts an {@code Iterator} to the {@code Enumeration} interface.
   *
   *
The {@code Iterable} equivalent of this method is either {@link Collections#enumeration} (if
   * you have a {@link Collection}), or {@code Iterators.asEnumeration(collection.iterator())}.
   */
  public static <T> Enumeration<T> asEnumeration(final Iterator<T> iterator) {
    checkNotNull(iterator);
    return new Enumeration<T>() {
      @Override
      public boolean hasMoreElements() {
        return iterator.hasNext();
      }

      @Override
      public T nextElement() {
        return iterator.next();
      }
    };
  }

  /** Implementation of PeekingIterator that avoids peeking unless necessary. */
  private static class PeekingImpl<E> implements PeekingIterator<E> {

    private final Iterator<? extends E> iterator;
    private boolean hasPeeked;
    private @Nullable E peekedElement;

    public PeekingImpl(Iterator<? extends E> iterator) {
      this.iterator = checkNotNull(iterator);
    }

    @Override
    public boolean hasNext() {
      return hasPeeked || iterator.hasNext();
    }

    @Override
    public E next() {
      if (!hasPeeked) {
        return iterator.next();
      }
      E result = peekedElement;
      hasPeeked = false;
      peekedElement = null;
      return result;
    }

    @Override
    public void remove() {
      checkState(!hasPeeked, "Can't remove after you've peeked at next");
      iterator.remove();
    }

    @Override
    public E peek() {
      if (!hasPeeked) {
        peekedElement = iterator.next();
        hasPeeked = true;
      }
      return peekedElement;
    }
  }

  /**
   * Returns a {@code PeekingIterator} backed by the given iterator.
   *
   *
Calls to the {@code peek} method with no intervening calls to {@code next} do not affect the
   * iteration, and hence return the same object each time. A subsequent call to {@code next} is
   * guaranteed to return the same object again. For example:
   *
   *
{@code
   * PeekingIterator<String> peekingIterator =
   *     Iterators.peekingIterator(Iterators.forArray("a", "b"));
   * String a1 = peekingIterator.peek(); // returns "a"
   * String a2 = peekingIterator.peek(); // also returns "a"
   * String a3 = peekingIterator.next(); // also returns "a"
   * }

   *
   *
Any structural changes to the underlying iteration (aside from those performed by the
   * iterator's own {@link PeekingIterator#remove()} method) will leave the iterator in an undefined
   * state.
   *
   *
The returned iterator does not support removal after peeking, as explained by {@link
   * PeekingIterator#remove()}.
   *
   *
Note: If the given iterator is already a {@code PeekingIterator}, it might be
   * returned to the caller, although this is neither guaranteed to occur nor required to be
   * consistent. For example, this method might choose to pass through recognized
   * implementations of {@code PeekingIterator} when the behavior of the implementation is known to
   * meet the contract guaranteed by this method.
   *
   *
There is no {@link Iterable} equivalent to this method, so use this method to wrap each
   * individual iterator as it is generated.
   *
   * @param iterator the backing iterator. The {@link PeekingIterator} assumes ownership of this
   *     iterator, so users should cease making direct calls to it after calling this method.
   * @return a peeking iterator backed by that iterator. Apart from the additional {@link
   *     PeekingIterator#peek()} method, this iterator behaves exactly the same as {@code iterator}.
   */
  public static <T> PeekingIterator<T> peekingIterator(Iterator<? extends T> iterator) {
    if (iterator instanceof PeekingImpl) {
      // Safe to cast <? extends T> to <T> because PeekingImpl only uses T
      // covariantly (and cannot be subclassed to add non-covariant uses).
      @SuppressWarnings("unchecked")
      PeekingImpl<T> peeking = (PeekingImpl<T>) iterator;
      return peeking;
    }
    return new PeekingImpl<T>(iterator);
  }

  /**
   * Simply returns its argument.
   *
   * @deprecated no need to use this
   * @since 10.0
   */
  @Deprecated
  public static <T> PeekingIterator<T> peekingIterator(PeekingIterator<T> iterator) {
    return checkNotNull(iterator);
  }

  /**
   * Returns an iterator over the merged contents of all given {@code iterators}, traversing every
   * element of the input iterators. Equivalent entries will not be de-duplicated.
   *
   *
Callers must ensure that the source {@code iterators} are in non-descending order as this
   * method does not sort its input.
   *
   *
For any equivalent elements across all {@code iterators}, it is undefined which element is
   * returned first.
   *
   * @since 11.0
   */
  @Beta
  public static <T> UnmodifiableIterator<T> mergeSorted(
      Iterable<? extends Iterator<? extends T>> iterators, Comparator<? super T> comparator) {
    checkNotNull(iterators, "iterators");
    checkNotNull(comparator, "comparator");

    return new MergingIterator<T>(iterators, comparator);
  }

  /**
   * An iterator that performs a lazy N-way merge, calculating the next value each time the iterator
   * is polled. This amortizes the sorting cost over the iteration and requires less memory than
   * sorting all elements at once.
   *
   *
Retrieving a single element takes approximately O(log(M)) time, where M is the number of
   * iterators. (Retrieving all elements takes approximately O(N*log(M)) time, where N is the total
   * number of elements.)
   */
  private static class MergingIterator<T> extends UnmodifiableIterator<T> {
    final Queue<PeekingIterator<T>> queue;

    public MergingIterator(
        Iterable<? extends Iterator<? extends T>> iterators,
        final Comparator<? super T> itemComparator) {
      // A comparator that's used by the heap, allowing the heap
      // to be sorted based on the top of each iterator.
      Comparator<PeekingIterator<T>> heapComparator =
          new Comparator<PeekingIterator<T>>() {
            @Override
            public int compare(PeekingIterator<T> o1, PeekingIterator<T> o2) {
              return itemComparator.compare(o1.peek(), o2.peek());
            }
          };

      queue = new PriorityQueue<>(2, heapComparator);

      for (Iterator<? extends T> iterator : iterators) {
        if (iterator.hasNext()) {
          queue.add(Iterators.peekingIterator(iterator));
        }
      }
    }

    @Override
    public boolean hasNext() {
      return !queue.isEmpty();
    }

    @Override
    public T next() {
      PeekingIterator<T> nextIter = queue.remove();
      T next = nextIter.next();
      if (nextIter.hasNext()) {
        queue.add(nextIter);
      }
      return next;
    }
  }

  private static class ConcatenatedIterator<T> implements Iterator<T> {
    /* The last iterator to return an element.  Calls to remove() go to this iterator. */
    private @Nullable Iterator<? extends T> toRemove;

    /* The iterator currently returning elements. */
    private Iterator<? extends T> iterator;

    /*
     * We track the "meta iterators," the iterators-of-iterators, below.  Usually, topMetaIterator
     * is the only one in use, but if we encounter nested concatenations, we start a deque of
     * meta-iterators rather than letting the nesting get arbitrarily deep.  This keeps each
     * operation O(1).
     */

    private Iterator<? extends Iterator<? extends T>> topMetaIterator;

    // Only becomes nonnull if we encounter nested concatenations.
    private @Nullable Deque<Iterator<? extends Iterator<? extends T>>> metaIterators;

    ConcatenatedIterator(Iterator<? extends Iterator<? extends T>> metaIterator) {
      iterator = emptyIterator();
      topMetaIterator = checkNotNull(metaIterator);
    }

    // Returns a nonempty meta-iterator or, if all meta-iterators are empty, null.
    private @Nullable Iterator<? extends Iterator<? extends T>> getTopMetaIterator() {
      while (topMetaIterator == null || !topMetaIterator.hasNext()) {
        if (metaIterators != null && !metaIterators.isEmpty()) {
          topMetaIterator = metaIterators.removeFirst();
        } else {
          return null;
        }
      }
      return topMetaIterator;
    }

    @Override
    public boolean hasNext() {
      while (!checkNotNull(iterator).hasNext()) {
        // this weird checkNotNull positioning appears required by our tests, which expect
        // both hasNext and next to throw NPE if an input iterator is null.

        topMetaIterator = getTopMetaIterator();
        if (topMetaIterator == null) {
          return false;
        }

        iterator = topMetaIterator.next();

        if (iterator instanceof ConcatenatedIterator) {
          // Instead of taking linear time in the number of nested concatenations, unpack
          // them into the queue
          @SuppressWarnings("unchecked")
          ConcatenatedIterator<T> topConcat = (ConcatenatedIterator<T>) iterator;
          iterator = topConcat.iterator;

          // topConcat.topMetaIterator, then topConcat.metaIterators, then this.topMetaIterator,
          // then this.metaIterators

          if (this.metaIterators == null) {
            this.metaIterators = new ArrayDeque<>();
          }
          this.metaIterators.addFirst(this.topMetaIterator);
          if (topConcat.metaIterators != null) {
            while (!topConcat.metaIterators.isEmpty()) {
              this.metaIterators.addFirst(topConcat.metaIterators.removeLast());
            }
          }
          this.topMetaIterator = topConcat.topMetaIterator;
        }
      }
      return true;
    }

    @Override
    public T next() {
      if (hasNext()) {
        toRemove = iterator;
        return iterator.next();
      } else {
        throw new NoSuchElementException();
      }
    }

    @Override
    public void remove() {
      CollectPreconditions.checkRemove(toRemove != null);
      toRemove.remove();
      toRemove = null;
    }
  }

  /** Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */
  static <T> ListIterator<T> cast(Iterator<T> iterator) {
    return (ListIterator<T>) iterator;
  }
}


/*
 * 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.reflect;

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

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Captures the actual type of {@code T}.
 *
 * @author Ben Yu
 */
abstract class TypeCapture<T> {

  /** Returns the captured type. */
  final Type capture() {
    Type superclass = getClass().getGenericSuperclass();
    checkArgument(superclass instanceof ParameterizedType, "%s isn't parameterized", superclass);
    return ((ParameterizedType) superclass).getActualTypeArguments()[0];
  }
}


/*
 * 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.collect.CollectPreconditions.checkNonnegative;
import static com.google.common.collect.CollectPreconditions.checkRemove;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
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.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * Implementation of {@code Multimap} that does not allow duplicate key-value entries and that
 * returns collections whose iterators follow the ordering in which the data was added to the
 * multimap.
 *
 *
The collections returned by {@code keySet}, {@code keys}, and {@code asMap} iterate through
 * the keys in the order they were first added to the multimap. Similarly, {@code get}, {@code
 * removeAll}, and {@code replaceValues} return collections that iterate through the values in the
 * order they were added. The collections generated by {@code entries} and {@code values} iterate
 * across the key-value mappings in the order they were added to the multimap.
 *
 *
The iteration ordering of the collections generated by {@code keySet}, {@code keys}, and
 * {@code asMap} has a few subtleties. As long as the set of keys remains unchanged, adding or
 * removing mappings does not affect the key iteration order. However, if you remove all values
 * associated with a key and then add the key back to the multimap, that key will come last in the
 * key iteration order.
 *
 *
The multimap does not store duplicate key-value pairs. Adding a new key-value pair equal to an
 * existing key-value pair has no effect.
 *
 *
Keys and values may be null. All optional multimap methods are supported, and all returned
 * views are modifiable.
 *
 *
This class is not threadsafe when any concurrent operations update the multimap. Concurrent
 * read operations will work correctly. To allow concurrent update operations, wrap your multimap
 * with a call to {@link Multimaps#synchronizedSetMultimap}.
 *
 *
See the Guava User Guide article on  {@code
 * Multimap}.
 *
 * @author Jared Levy
 * @author Louis Wasserman
 * @since 2.0
 */
@GwtCompatible(serializable = true, emulated = true)
public final class LinkedHashMultimap<K, V>
    extends LinkedHashMultimapGwtSerializationDependencies<K, V> {

  /** Creates a new, empty {@code LinkedHashMultimap} with the default initial capacities. */
  public static <K, V> LinkedHashMultimap<K, V> create() {
    return new LinkedHashMultimap<>(DEFAULT_KEY_CAPACITY, DEFAULT_VALUE_SET_CAPACITY);
  }

  /**
   * Constructs an empty {@code LinkedHashMultimap} with enough capacity to hold the specified
   * numbers of keys and values without rehashing.
   *
   * @param expectedKeys the expected number of distinct keys
   * @param expectedValuesPerKey the expected average number of values per key
   * @throws IllegalArgumentException if {@code expectedKeys} or {@code expectedValuesPerKey} is
   *     negative
   */
  public static <K, V> LinkedHashMultimap<K, V> create(int expectedKeys, int expectedValuesPerKey) {
    return new LinkedHashMultimap<>(
        Maps.capacity(expectedKeys), Maps.capacity(expectedValuesPerKey));
  }

  /**
   * Constructs a {@code LinkedHashMultimap} with the same mappings as the specified multimap. If a
   * key-value mapping appears multiple times in the input multimap, it only appears once in the
   * constructed multimap. The new multimap has the same {@link Multimap#entries()} iteration order
   * as the input multimap, except for excluding duplicate mappings.
   *
   * @param multimap the multimap whose contents are copied to this multimap
   */
  public static <K, V> LinkedHashMultimap<K, V> create(
      Multimap<? extends K, ? extends V> multimap) {
    LinkedHashMultimap<K, V> result = create(multimap.keySet().size(), DEFAULT_VALUE_SET_CAPACITY);
    result.putAll(multimap);
    return result;
  }

  private interface ValueSetLink<K, V> {
    ValueSetLink<K, V> getPredecessorInValueSet();

    ValueSetLink<K, V> getSuccessorInValueSet();

    void setPredecessorInValueSet(ValueSetLink<K, V> entry);

    void setSuccessorInValueSet(ValueSetLink<K, V> entry);
  }

  private static <K, V> void succeedsInValueSet(ValueSetLink<K, V> pred, ValueSetLink<K, V> succ) {
    pred.setSuccessorInValueSet(succ);
    succ.setPredecessorInValueSet(pred);
  }

  private static <K, V> void succeedsInMultimap(ValueEntry<K, V> pred, ValueEntry<K, V> succ) {
    pred.setSuccessorInMultimap(succ);
    succ.setPredecessorInMultimap(pred);
  }

  private static <K, V> void deleteFromValueSet(ValueSetLink<K, V> entry) {
    succeedsInValueSet(entry.getPredecessorInValueSet(), entry.getSuccessorInValueSet());
  }

  private static <K, V> void deleteFromMultimap(ValueEntry<K, V> entry) {
    succeedsInMultimap(entry.getPredecessorInMultimap(), entry.getSuccessorInMultimap());
  }

  /**
   * LinkedHashMultimap entries are in no less than three coexisting linked lists: a bucket in the
   * hash table for a {@code Set<V>} associated with a key, the linked list of insertion-ordered
   * entries in that {@code Set<V>}, and the linked list of entries in the LinkedHashMultimap as a
   * whole.
   */
  @VisibleForTesting
  static final class ValueEntry<K, V> extends ImmutableEntry<K, V> implements ValueSetLink<K, V> {
    final int smearedValueHash;

    @NullableDecl ValueEntry<K, V> nextInValueBucket;

    @NullableDecl ValueSetLink<K, V> predecessorInValueSet;
    @NullableDecl ValueSetLink<K, V> successorInValueSet;

    @NullableDecl ValueEntry<K, V> predecessorInMultimap;
    @NullableDecl ValueEntry<K, V> successorInMultimap;

    ValueEntry(
        @NullableDecl K key,
        @NullableDecl V value,
        int smearedValueHash,
        @NullableDecl ValueEntry<K, V> nextInValueBucket) {
      super(key, value);
      this.smearedValueHash = smearedValueHash;
      this.nextInValueBucket = nextInValueBucket;
    }

    boolean matchesValue(@NullableDecl Object v, int smearedVHash) {
      return smearedValueHash == smearedVHash && Objects.equal(getValue(), v);
    }

    @Override
    public ValueSetLink<K, V> getPredecessorInValueSet() {
      return predecessorInValueSet;
    }

    @Override
    public ValueSetLink<K, V> getSuccessorInValueSet() {
      return successorInValueSet;
    }

    @Override
    public void setPredecessorInValueSet(ValueSetLink<K, V> entry) {
      predecessorInValueSet = entry;
    }

    @Override
    public void setSuccessorInValueSet(ValueSetLink<K, V> entry) {
      successorInValueSet = entry;
    }

    public ValueEntry<K, V> getPredecessorInMultimap() {
      return predecessorInMultimap;
    }

    public ValueEntry<K, V> getSuccessorInMultimap() {
      return successorInMultimap;
    }

    public void setSuccessorInMultimap(ValueEntry<K, V> multimapSuccessor) {
      this.successorInMultimap = multimapSuccessor;
    }

    public void setPredecessorInMultimap(ValueEntry<K, V> multimapPredecessor) {
      this.predecessorInMultimap = multimapPredecessor;
    }
  }

  private static final int DEFAULT_KEY_CAPACITY = 16;
  private static final int DEFAULT_VALUE_SET_CAPACITY = 2;
  @VisibleForTesting static final double VALUE_SET_LOAD_FACTOR = 1.0;

  @VisibleForTesting transient int valueSetCapacity = DEFAULT_VALUE_SET_CAPACITY;
  private transient ValueEntry<K, V> multimapHeaderEntry;

  private LinkedHashMultimap(int keyCapacity, int valueSetCapacity) {
    super(Platform.<K, Collection<V>>newLinkedHashMapWithExpectedSize(keyCapacity));
    checkNonnegative(valueSetCapacity, "expectedValuesPerKey");

    this.valueSetCapacity = valueSetCapacity;
    this.multimapHeaderEntry = new ValueEntry<>(null, null, 0, null);
    succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry);
  }

  /**
   * {@inheritDoc}
   *
   *
Creates an empty {@code LinkedHashSet} for a collection of values for one key.
   *
   * @return a new {@code LinkedHashSet} containing a collection of values for one key
   */
  @Override
  Set<V> createCollection() {
    return Platform.newLinkedHashSetWithExpectedSize(valueSetCapacity);
  }

  /**
   * {@inheritDoc}
   *
   *
Creates a decorated insertion-ordered set that also keeps track of the order in which
   * key-value pairs are added to the multimap.
   *
   * @param key key to associate with values in the collection
   * @return a new decorated set containing a collection of values for one key
   */
  @Override
  Collection<V> createCollection(K key) {
    return new ValueSet(key, valueSetCapacity);
  }

  /**
   * {@inheritDoc}
   *
   *
If {@code values} is not empty and the multimap already contains a mapping for {@code key},
   * the {@code keySet()} ordering is unchanged. However, the provided values always come last in
   * the {@link #entries()} and {@link #values()} iteration orderings.
   */
  @CanIgnoreReturnValue
  @Override
  public Set<V> replaceValues(@NullableDecl K key, Iterable<? extends V> values) {
    return super.replaceValues(key, values);
  }

  /**
   * Returns a set of all key-value pairs. Changes to the returned set will update the underlying
   * multimap, and vice versa. The entries set does not support the {@code add} or {@code addAll}
   * operations.
   *
   *
The iterator generated by the returned set traverses the entries in the order they were
   * added to the multimap.
   *
   *
Each entry is an immutable snapshot of a key-value mapping in the multimap, taken at the
   * time the entry is returned by a method call to the collection or its iterator.
   */
  @Override
  public Set<Entry<K, V>> entries() {
    return super.entries();
  }

  /**
   * Returns a view collection of all distinct keys contained in this multimap. Note that the
   * key set contains a key if and only if this multimap maps that key to at least one value.
   *
   *
The iterator generated by the returned set traverses the keys in the order they were first
   * added to the multimap.
   *
   *
Changes to the returned set will update the underlying multimap, and vice versa. However,
   * adding to the returned set is not possible.
   */
  @Override
  public Set<K> keySet() {
    return super.keySet();
  }

  /**
   * Returns a collection of all values in the multimap. Changes to the returned collection will
   * update the underlying multimap, and vice versa.
   *
   *
The iterator generated by the returned collection traverses the values in the order they
   * were added to the multimap.
   */
  @Override
  public Collection<V> values() {
    return super.values();
  }

  @VisibleForTesting
  @WeakOuter
  final class ValueSet extends Sets.ImprovedAbstractSet<V> implements ValueSetLink<K, V> {
    /*
     * We currently use a fixed load factor of 1.0, a bit higher than normal to reduce memory
     * consumption.
     */

    private final K key;
    @VisibleForTesting ValueEntry<K, V>[] hashTable;
    private int size = 0;
    private int modCount = 0;

    // We use the set object itself as the end of the linked list, avoiding an unnecessary
    // entry object per key.
    private ValueSetLink<K, V> firstEntry;
    private ValueSetLink<K, V> lastEntry;

    ValueSet(K key, int expectedValues) {
      this.key = key;
      this.firstEntry = this;
      this.lastEntry = this;
      // Round expected values up to a power of 2 to get the table size.
      int tableSize = Hashing.closedTableSize(expectedValues, VALUE_SET_LOAD_FACTOR);

      @SuppressWarnings("unchecked")
      ValueEntry<K, V>[] hashTable = new ValueEntry[tableSize];
      this.hashTable = hashTable;
    }

    private int mask() {
      return hashTable.length - 1;
    }

    @Override
    public ValueSetLink<K, V> getPredecessorInValueSet() {
      return lastEntry;
    }

    @Override
    public ValueSetLink<K, V> getSuccessorInValueSet() {
      return firstEntry;
    }

    @Override
    public void setPredecessorInValueSet(ValueSetLink<K, V> entry) {
      lastEntry = entry;
    }

    @Override
    public void setSuccessorInValueSet(ValueSetLink<K, V> entry) {
      firstEntry = entry;
    }

    @Override
    public Iterator<V> iterator() {
      return new Iterator<V>() {
        ValueSetLink<K, V> nextEntry = firstEntry;
        @NullableDecl ValueEntry<K, V> toRemove;
        int expectedModCount = modCount;

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

        @Override
        public boolean hasNext() {
          checkForComodification();
          return nextEntry != ValueSet.this;
        }

        @Override
        public V next() {
          if (!hasNext()) {
            throw new NoSuchElementException();
          }
          ValueEntry<K, V> entry = (ValueEntry<K, V>) nextEntry;
          V result = entry.getValue();
          toRemove = entry;
          nextEntry = entry.getSuccessorInValueSet();
          return result;
        }

        @Override
        public void remove() {
          checkForComodification();
          checkRemove(toRemove != null);
          ValueSet.this.remove(toRemove.getValue());
          expectedModCount = modCount;
          toRemove = null;
        }
      };
    }

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

    @Override
    public boolean contains(@NullableDecl Object o) {
      int smearedHash = Hashing.smearedHash(o);
      for (ValueEntry<K, V> entry = hashTable[smearedHash & mask()];
          entry != null;
          entry = entry.nextInValueBucket) {
        if (entry.matchesValue(o, smearedHash)) {
          return true;
        }
      }
      return false;
    }

    @Override
    public boolean add(@NullableDecl V value) {
      int smearedHash = Hashing.smearedHash(value);
      int bucket = smearedHash & mask();
      ValueEntry<K, V> rowHead = hashTable[bucket];
      for (ValueEntry<K, V> entry = rowHead; entry != null; entry = entry.nextInValueBucket) {
        if (entry.matchesValue(value, smearedHash)) {
          return false;
        }
      }

      ValueEntry<K, V> newEntry = new ValueEntry<>(key, value, smearedHash, rowHead);
      succeedsInValueSet(lastEntry, newEntry);
      succeedsInValueSet(newEntry, this);
      succeedsInMultimap(multimapHeaderEntry.getPredecessorInMultimap(), newEntry);
      succeedsInMultimap(newEntry, multimapHeaderEntry);
      hashTable[bucket] = newEntry;
      size++;
      modCount++;
      rehashIfNecessary();
      return true;
    }

    private void rehashIfNecessary() {
      if (Hashing.needsResizing(size, hashTable.length, VALUE_SET_LOAD_FACTOR)) {
        @SuppressWarnings("unchecked")
        ValueEntry<K, V>[] hashTable = new ValueEntry[this.hashTable.length * 2];
        this.hashTable = hashTable;
        int mask = hashTable.length - 1;
        for (ValueSetLink<K, V> entry = firstEntry;
            entry != this;
            entry = entry.getSuccessorInValueSet()) {
          ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry;
          int bucket = valueEntry.smearedValueHash & mask;
          valueEntry.nextInValueBucket = hashTable[bucket];
          hashTable[bucket] = valueEntry;
        }
      }
    }

    @CanIgnoreReturnValue
    @Override
    public boolean remove(@NullableDecl Object o) {
      int smearedHash = Hashing.smearedHash(o);
      int bucket = smearedHash & mask();
      ValueEntry<K, V> prev = null;
      for (ValueEntry<K, V> entry = hashTable[bucket];
          entry != null;
          prev = entry, entry = entry.nextInValueBucket) {
        if (entry.matchesValue(o, smearedHash)) {
          if (prev == null) {
            // first entry in the bucket
            hashTable[bucket] = entry.nextInValueBucket;
          } else {
            prev.nextInValueBucket = entry.nextInValueBucket;
          }
          deleteFromValueSet(entry);
          deleteFromMultimap(entry);
          size--;
          modCount++;
          return true;
        }
      }
      return false;
    }

    @Override
    public void clear() {
      Arrays.fill(hashTable, null);
      size = 0;
      for (ValueSetLink<K, V> entry = firstEntry;
          entry != this;
          entry = entry.getSuccessorInValueSet()) {
        ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry;
        deleteFromMultimap(valueEntry);
      }
      succeedsInValueSet(this, this);
      modCount++;
    }
  }

  @Override
  Iterator<Entry<K, V>> entryIterator() {
    return new Iterator<Entry<K, V>>() {
      ValueEntry<K, V> nextEntry = multimapHeaderEntry.successorInMultimap;
      @NullableDecl ValueEntry<K, V> toRemove;

      @Override
      public boolean hasNext() {
        return nextEntry != multimapHeaderEntry;
      }

      @Override
      public Entry<K, V> next() {
        if (!hasNext()) {
          throw new NoSuchElementException();
        }
        ValueEntry<K, V> result = nextEntry;
        toRemove = result;
        nextEntry = nextEntry.successorInMultimap;
        return result;
      }

      @Override
      public void remove() {
        checkRemove(toRemove != null);
        LinkedHashMultimap.this.remove(toRemove.getKey(), toRemove.getValue());
        toRemove = null;
      }
    };
  }

  @Override
  Iterator<V> valueIterator() {
    return Maps.valueIterator(entryIterator());
  }

  @Override
  public void clear() {
    super.clear();
    succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry);
  }

  /**
   * @serialData the expected values per key, the number of distinct keys, the number of entries,
   *     and the entries in order
   */
  @GwtIncompatible // java.io.ObjectOutputStream
  private void writeObject(ObjectOutputStream stream) throws IOException {
    stream.defaultWriteObject();
    stream.writeInt(keySet().size());
    for (K key : keySet()) {
      stream.writeObject(key);
    }
    stream.writeInt(size());
    for (Entry<K, V> entry : entries()) {
      stream.writeObject(entry.getKey());
      stream.writeObject(entry.getValue());
    }
  }

  @GwtIncompatible // java.io.ObjectInputStream
  private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    multimapHeaderEntry = new ValueEntry<>(null, null, 0, null);
    succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry);
    valueSetCapacity = DEFAULT_VALUE_SET_CAPACITY;
    int distinctKeys = stream.readInt();
    Map<K, Collection<V>> map = Platform.newLinkedHashMapWithExpectedSize(12);
    for (int i = 0; i < distinctKeys; i++) {
      @SuppressWarnings("unchecked")
      K key = (K) stream.readObject();
      map.put(key, createCollection(key));
    }
    int entries = stream.readInt();
    for (int i = 0; i < entries; i++) {
      @SuppressWarnings("unchecked")
      K key = (K) stream.readObject();
      @SuppressWarnings("unchecked")
      V value = (V) stream.readObject();
      map.get(key).add(value);
    }
    setMap(map);
  }

  @GwtIncompatible // java serialization not supported
  private static final long serialVersionUID = 1;
}


/*
 * Copyright (C) 2011 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.cache;

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

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;

/**
 * Computes or retrieves values, based on a key, for use in populating a {@link LoadingCache}.
 *
 *
Most implementations will only need to implement {@link #load}. Other methods may be
 * overridden as desired.
 *
 *
Usage example:
 *
 *
{@code
 * CacheLoader<Key, Graph> loader = new CacheLoader<Key, Graph>() {
 *   public Graph load(Key key) throws AnyException {
 *     return createExpensiveGraph(key);
 *   }
 * };
 * LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().build(loader);
 * }

 *
 *
Since this example doesn't support reloading or bulk loading, if you're able to use lambda
 * expressions it can be specified even more easily:
 *
 *
{@code
 * CacheLoader<Key, Graph> loader = CacheLoader.from(key -> createExpensiveGraph(key));
 * }

 *
 * @author Charles Fry
 * @since 10.0
 */
@GwtCompatible(emulated = true)
public abstract class CacheLoader<K, V> {
  /** Constructor for use by subclasses. */
  protected CacheLoader() {}

  /**
   * Computes or retrieves the value corresponding to {@code key}.
   *
   * @param key the non-null key whose value should be loaded
   * @return the value associated with {@code key}; must not be null
   * @throws Exception if unable to load the result
   * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
   *     treated like any other {@code Exception} in all respects except that, when it is caught,
   *     the thread's interrupt status is set
   */
  public abstract V load(K key) throws Exception;

  /**
   * Computes or retrieves a replacement value corresponding to an already-cached {@code key}. This
   * method is called when an existing cache entry is refreshed by {@link
   * CacheBuilder#refreshAfterWrite}, or through a call to {@link LoadingCache#refresh}.
   *
   *
This implementation synchronously delegates to {@link #load}. It is recommended that it be
   * overridden with an asynchronous implementation when using {@link
   * CacheBuilder#refreshAfterWrite}.
   *
   *
Note: all exceptions thrown by this method will be logged and then swallowed.
   *
   * @param key the non-null key whose value should be loaded
   * @param oldValue the non-null old value corresponding to {@code key}
   * @return the future new value associated with {@code key}; must not be null, must not return
   *     null
   * @throws Exception if unable to reload the result
   * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
   *     treated like any other {@code Exception} in all respects except that, when it is caught,
   *     the thread's interrupt status is set
   * @since 11.0
   */
  @GwtIncompatible // Futures
  public ListenableFuture<V> reload(K key, V oldValue) throws Exception {
    checkNotNull(key);
    checkNotNull(oldValue);
    return Futures.immediateFuture(load(key));
  }

  /**
   * Computes or retrieves the values corresponding to {@code keys}. This method is called by {@link
   * LoadingCache#getAll}.
   *
   *
If the returned map doesn't contain all requested {@code keys} then the entries it does
   * contain will be cached, but {@code getAll} will throw an exception. If the returned map
   * contains extra keys not present in {@code keys} then all returned entries will be cached, but
   * only the entries for {@code keys} will be returned from {@code getAll}.
   *
   *
This method should be overridden when bulk retrieval is significantly more efficient than
   * many individual lookups. Note that {@link LoadingCache#getAll} will defer to individual calls
   * to {@link LoadingCache#get} if this method is not overridden.
   *
   * @param keys the unique, non-null keys whose values should be loaded
   * @return a map from each key in {@code keys} to the value associated with that key; may not
   *     contain null values
   * @throws Exception if unable to load the result
   * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
   *     treated like any other {@code Exception} in all respects except that, when it is caught,
   *     the thread's interrupt status is set
   * @since 11.0
   */
  public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
    // This will be caught by getAll(), causing it to fall back to multiple calls to
    // LoadingCache.get
    throw new UnsupportedLoadingOperationException();
  }

  /**
   * Returns a cache loader that uses {@code function} to load keys, and without supporting either
   * reloading or bulk loading. This is most useful when you can pass a lambda expression. Otherwise
   * it is useful mostly when you already have an existing function instance.
   *
   * @param function the function to be used for loading values; must never return {@code null}
   * @return a cache loader that loads values by passing each key to {@code function}
   */
  public static <K, V> CacheLoader<K, V> from(Function<K, V> function) {
    return new FunctionToCacheLoader<>(function);
  }

  /**
   * Returns a cache loader based on an existing supplier instance. Note that there's no need
   * to create a new supplier just to pass it in here; just subclass {@code CacheLoader} and
   * implement {@link #load load} instead.
   *
   * @param supplier the supplier to be used for loading values; must never return {@code null}
   * @return a cache loader that loads values by calling {@link Supplier#get}, irrespective of the
   *     key
   */
  public static <V> CacheLoader<Object, V> from(Supplier<V> supplier) {
    return new SupplierToCacheLoader<V>(supplier);
  }

  private static final class FunctionToCacheLoader<K, V> extends CacheLoader<K, V>
      implements Serializable {
    private final Function<K, V> computingFunction;

    public FunctionToCacheLoader(Function<K, V> computingFunction) {
      this.computingFunction = checkNotNull(computingFunction);
    }

    @Override
    public V load(K key) {
      return computingFunction.apply(checkNotNull(key));
    }

    private static final long serialVersionUID = 0;
  }

  /**
   * Returns a {@code CacheLoader} which wraps {@code loader}, executing calls to {@link
   * CacheLoader#reload} using {@code executor}.
   *
   *
This method is useful only when {@code loader.reload} has a synchronous implementation, such
   * as {@linkplain #reload the default implementation}.
   *
   * @since 17.0
   */
  @GwtIncompatible // Executor + Futures
  public static <K, V> CacheLoader<K, V> asyncReloading(
      final CacheLoader<K, V> loader, final Executor executor) {
    checkNotNull(loader);
    checkNotNull(executor);
    return new CacheLoader<K, V>() {
      @Override
      public V load(K key) throws Exception {
        return loader.load(key);
      }

      @Override
      public ListenableFuture<V> reload(final K key, final V oldValue) throws Exception {
        ListenableFutureTask<V> task =
            ListenableFutureTask.create(
                new Callable<V>() {
                  @Override
                  public V call() throws Exception {
                    return loader.reload(key, oldValue).get();
                  }
                });
        executor.execute(task);
        return task;
      }

      @Override
      public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
        return loader.loadAll(keys);
      }
    };
  }

  private static final class SupplierToCacheLoader<V> extends CacheLoader<Object, V>
      implements Serializable {
    private final Supplier<V> computingSupplier;

    public SupplierToCacheLoader(Supplier<V> computingSupplier) {
      this.computingSupplier = checkNotNull(computingSupplier);
    }

    @Override
    public V load(Object key) {
      checkNotNull(key);
      return computingSupplier.get();
    }

    private static final long serialVersionUID = 0;
  }

  /**
   * Exception thrown by {@code loadAll()} to indicate that it is not supported.
   *
   * @since 19.0
   */
  public static final class UnsupportedLoadingOperationException
      extends UnsupportedOperationException {
    // Package-private because this should only be thrown by loadAll() when it is not overridden.
    // Cache implementors may want to catch it but should not need to be able to throw it.
    UnsupportedLoadingOperationException() {}
  }

  /**
   * Thrown to indicate that an invalid response was returned from a call to {@link CacheLoader}.
   *
   * @since 11.0
   */
  public static final class InvalidCacheLoadException extends RuntimeException {
    public InvalidCacheLoadException(String message) {
      super(message);
    }
  }
}