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

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

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.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.stream.Stream;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A discouraged (but not deprecated) precursor to Java's superior {@link Stream} library.
 *
 *
The following types of methods are provided:
 *
 *

 *
chaining methods which return a new {@code FluentIterable} based in some way on the
 *       contents of the current one (for example {@link #transform})
 *
element extraction methods which facilitate the retrieval of certain elements (for example
 *       {@link #last})
 *
query methods which answer questions about the {@code FluentIterable}'s contents (for
 *       example {@link #anyMatch})
 *
conversion methods which copy the {@code FluentIterable}'s contents into a new collection
 *       or array (for example {@link #toList})
 *

 *
 *
Several lesser-used features are currently available only as static methods on the {@link
 * Iterables} class.
 *
 *

 *
 *
Comparison to streams

 *
 *
{@link Stream} is similar to this class, but generally more powerful, and certainly more
 * standard. Key differences include:
 *
 *

 *
A stream is single-use; it becomes invalid as soon as any "terminal operation" such
 *       as {@code findFirst()} or {@code iterator()} is invoked. (Even though {@code Stream}
 *       contains all the right method signatures to implement {@link Iterable}, it does not
 *       actually do so, to avoid implying repeat-iterability.) {@code FluentIterable}, on the other
 *       hand, is multiple-use, and does implement {@link Iterable}.
 *
Streams offer many features not found here, including {@code min/max}, {@code distinct},
 *       {@code reduce}, {@code sorted}, the very powerful {@code collect}, and built-in support for
 *       parallelizing stream operations.
 *
{@code FluentIterable} contains several features not available on {@code Stream}, which are
 *       noted in the method descriptions below.
 *
Streams include primitive-specialized variants such as {@code IntStream}, the use of which
 *       is strongly recommended.
 *
Streams are standard Java, not requiring a third-party dependency.
 *

 *
 *
Example

 *
 *
Here is an example that accepts a list from a database call, filters it based on a predicate,
 * transforms it by invoking {@code toString()} on each element, and returns the first 10 elements
 * as a {@code List}:
 *
 *
{@code
 * ImmutableList<String> results =
 *     FluentIterable.from(database.getClientList())
 *         .filter(Client::isActiveInLastMonth)
 *         .transform(Object::toString)
 *         .limit(10)
 *         .toList();
 * }

 *
 * The approximate stream equivalent is:
 *
 *
{@code
 * List<String> results =
 *     database.getClientList()
 *         .stream()
 *         .filter(Client::isActiveInLastMonth)
 *         .map(Object::toString)
 *         .limit(10)
 *         .collect(Collectors.toList());
 * }

 *
 * @author Marcin Mikosik
 * @since 12.0
 */
@GwtCompatible(emulated = true)
public abstract class FluentIterable<E> implements Iterable<E> {
  // We store 'iterable' and use it instead of 'this' to allow Iterables to perform instanceof
  // checks on the _original_ iterable when FluentIterable.from is used.
  // To avoid a self retain cycle under j2objc, we store Optional.absent() instead of
  // Optional.of(this). To access the iterator delegate, call #getDelegate(), which converts to
  // absent() back to 'this'.
  private final Optional<Iterable<E>> iterableDelegate;

  /** Constructor for use by subclasses. */
  protected FluentIterable() {
    this.iterableDelegate = Optional.absent();
  }

  FluentIterable(Iterable<E> iterable) {
    checkNotNull(iterable);
    this.iterableDelegate = Optional.fromNullable(this != iterable ? iterable : null);
  }

  private Iterable<E> getDelegate() {
    return iterableDelegate.or(this);
  }

  /**
   * Returns a fluent iterable that wraps {@code iterable}, or {@code iterable} itself if it is
   * already a {@code FluentIterable}.
   *
   *
{@code Stream} equivalent: {@link Collection#stream} if {@code iterable} is a {@link
   * Collection}; {@link Streams#stream(Iterable)} otherwise.
   */
  public static <E> FluentIterable<E> from(final Iterable<E> iterable) {
    return (iterable instanceof FluentIterable)
        ? (FluentIterable<E>) iterable
        : new FluentIterable<E>(iterable) {
          @Override
          public Iterator<E> iterator() {
            return iterable.iterator();
          }
        };
  }

  /**
   * Returns a fluent iterable containing {@code elements} in the specified order.
   *
   *
The returned iterable is an unmodifiable view of the input array.
   *
   *
{@code Stream} equivalent: {@link java.util.stream.Stream#of(Object[])
   * Stream.of(T...)}.
   *
   * @since 20.0 (since 18.0 as an overload of {@code of})
   */
  @Beta
  public static <E> FluentIterable<E> from(E[] elements) {
    return from(Arrays.asList(elements));
  }

  /**
   * Construct a fluent iterable from another fluent iterable. This is obviously never necessary,
   * but is intended to help call out cases where one migration from {@code Iterable} to {@code
   * FluentIterable} has obviated the need to explicitly convert to a {@code FluentIterable}.
   *
   * @deprecated instances of {@code FluentIterable} don't need to be converted to {@code
   *     FluentIterable}
   */
  @Deprecated
  public static <E> FluentIterable<E> from(FluentIterable<E> iterable) {
    return checkNotNull(iterable);
  }

  /**
   * Returns a fluent iterable that combines two iterables. The returned iterable has an iterator
   * that traverses the elements in {@code a}, followed by the elements in {@code b}. The source
   * iterators are not polled until necessary.
   *
   *
The returned iterable's iterator supports {@code remove()} when the corresponding input
   * iterator supports it.
   *
   *
{@code Stream} equivalent: {@link Stream#concat}.
   *
   * @since 20.0
   */
  @Beta
  public static <T> FluentIterable<T> concat(Iterable<? extends T> a, Iterable<? extends T> b) {
    return concatNoDefensiveCopy(a, b);
  }

  /**
   * Returns a fluent iterable that combines three iterables. The returned iterable has an iterator
   * that traverses 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 iterable's iterator supports {@code remove()} when the corresponding input
   * iterator supports it.
   *
   *
{@code Stream} equivalent: use nested calls to {@link Stream#concat}, or see the
   * advice in {@link #concat(Iterable...)}.
   *
   * @since 20.0
   */
  @Beta
  public static <T> FluentIterable<T> concat(
      Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) {
    return concatNoDefensiveCopy(a, b, c);
  }

  /**
   * Returns a fluent iterable that combines four iterables. The returned iterable has an iterator
   * that traverses 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 iterable's iterator supports {@code remove()} when the corresponding input
   * iterator supports it.
   *
   *
{@code Stream} equivalent: use nested calls to {@link Stream#concat}, or see the
   * advice in {@link #concat(Iterable...)}.
   *
   * @since 20.0
   */
  @Beta
  public static <T> FluentIterable<T> concat(
      Iterable<? extends T> a,
      Iterable<? extends T> b,
      Iterable<? extends T> c,
      Iterable<? extends T> d) {
    return concatNoDefensiveCopy(a, b, c, d);
  }

  /**
   * Returns a fluent iterable that combines several iterables. The returned iterable has an
   * iterator that traverses the elements of each iterable in {@code inputs}. The input iterators
   * are not polled until necessary.
   *
   *
The returned iterable's iterator supports {@code remove()} when the corresponding input
   * iterator supports it.
   *
   *
{@code Stream} equivalent: to concatenate an arbitrary number of streams, use {@code
   * Stream.of(stream1, stream2, ...).flatMap(s -> s)}. If the sources are iterables, use {@code
   * Stream.of(iter1, iter2, ...).flatMap(Streams::stream)}.
   *
   * @throws NullPointerException if any of the provided iterables is {@code null}
   * @since 20.0
   */
  @Beta
  public static <T> FluentIterable<T> concat(Iterable<? extends T>... inputs) {
    return concatNoDefensiveCopy(Arrays.copyOf(inputs, inputs.length));
  }

  /**
   * Returns a fluent iterable that combines several iterables. The returned iterable has an
   * iterator that traverses the elements of each iterable in {@code inputs}. The input iterators
   * are not polled until necessary.
   *
   *
The returned iterable's iterator supports {@code remove()} when the corresponding input
   * iterator supports it. The methods of the returned iterable may throw {@code
   * NullPointerException} if any of the input iterators is {@code null}.
   *
   *
{@code Stream} equivalent: {@code streamOfStreams.flatMap(s -> s)} or {@code
   * streamOfIterables.flatMap(Streams::stream)}. (See {@link Streams#stream}.)
   *
   * @since 20.0
   */
  @Beta
  public static <T> FluentIterable<T> concat(
      final Iterable<? extends Iterable<? extends T>> inputs) {
    checkNotNull(inputs);
    return new FluentIterable<T>() {
      @Override
      public Iterator<T> iterator() {
        return Iterators.concat(Iterators.transform(inputs.iterator(), Iterables.<T>toIterator()));
      }
    };
  }

  /** Concatenates a varargs array of iterables without making a defensive copy of the array. */
  private static <T> FluentIterable<T> concatNoDefensiveCopy(
      final Iterable<? extends T>... inputs) {
    for (Iterable<? extends T> input : inputs) {
      checkNotNull(input);
    }
    return new FluentIterable<T>() {
      @Override
      public Iterator<T> iterator() {
        return Iterators.concat(
            /* lazily generate the iterators on each input only as needed */
            new AbstractIndexedListIterator<Iterator<? extends T>>(inputs.length) {
              @Override
              public Iterator<? extends T> get(int i) {
                return inputs[i].iterator();
              }
            });
      }
    };
  }

  /**
   * Returns a fluent iterable containing no elements.
   *
   *
{@code Stream} equivalent: {@link Stream#empty}.
   *
   * @since 20.0
   */
  @Beta
  public static <E> FluentIterable<E> of() {
    return FluentIterable.from(ImmutableList.<E>of());
  }

  /**
   * Returns a fluent iterable containing the specified elements in order.
   *
   *
{@code Stream} equivalent: {@link java.util.stream.Stream#of(Object[])
   * Stream.of(T...)}.
   *
   * @since 20.0
   */
  @Beta
  public static <E> FluentIterable<E> of(@Nullable E element, E... elements) {
    return from(Lists.asList(element, elements));
  }

  /**
   * Returns a string representation of this fluent iterable, with the format {@code [e1, e2, ...,
   * en]}.
   *
   *
{@code Stream} equivalent: {@code stream.collect(Collectors.joining(", ", "[", "]"))}
   * or (less efficiently) {@code stream.collect(Collectors.toList()).toString()}.
   */
  @Override
  public String toString() {
    return Iterables.toString(getDelegate());
  }

  /**
   * Returns the number of elements in this fluent iterable.
   *
   *
{@code Stream} equivalent: {@link Stream#count}.
   */
  public final int size() {
    return Iterables.size(getDelegate());
  }

  /**
   * Returns {@code true} if this fluent iterable contains any object for which {@code
   * equals(target)} is true.
   *
   *
{@code Stream} equivalent: {@code stream.anyMatch(Predicate.isEqual(target))}.
   */
  public final boolean contains(@Nullable Object target) {
    return Iterables.contains(getDelegate(), target);
  }

  /**
   * Returns a fluent iterable whose {@code Iterator} cycles indefinitely over the elements of this
   * fluent iterable.
   *
   *
That iterator supports {@code remove()} if {@code iterable.iterator()} does. After {@code
   * remove()} is called, subsequent cycles omit the removed element, which is no longer in this
   * fluent iterable. The iterator's {@code hasNext()} method returns {@code true} until this fluent
   * 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.
   *
   *
{@code Stream} equivalent: if the source iterable has only a single element {@code
   * e}, use {@code Stream.generate(() -> e)}. Otherwise, collect your stream into a collection and
   * use {@code Stream.generate(() -> collection).flatMap(Collection::stream)}.
   */
  public final FluentIterable<E> cycle() {
    return from(Iterables.cycle(getDelegate()));
  }

  /**
   * Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable,
   * followed by those of {@code other}. The iterators are not polled until necessary.
   *
   *
The returned iterable's {@code Iterator} supports {@code remove()} when the corresponding
   * {@code Iterator} supports it.
   *
   *
{@code Stream} equivalent: {@link Stream#concat}.
   *
   * @since 18.0
   */
  @Beta
  public final FluentIterable<E> append(Iterable<? extends E> other) {
    return FluentIterable.concat(getDelegate(), other);
  }

  /**
   * Returns a fluent iterable whose iterators traverse first the elements of this fluent iterable,
   * followed by {@code elements}.
   *
   *
{@code Stream} equivalent: {@code Stream.concat(thisStream, Stream.of(elements))}.
   *
   * @since 18.0
   */
  @Beta
  public final FluentIterable<E> append(E... elements) {
    return FluentIterable.concat(getDelegate(), Arrays.asList(elements));
  }

  /**
   * Returns the elements from this fluent iterable that satisfy a predicate. The resulting fluent
   * iterable's iterator does not support {@code remove()}.
   *
   *
{@code Stream} equivalent: {@link Stream#filter} (same).
   */
  public final FluentIterable<E> filter(Predicate<? super E> predicate) {
    return from(Iterables.filter(getDelegate(), predicate));
  }

  /**
   * Returns the elements from this fluent iterable that are instances of class {@code type}.
   *
   *
{@code Stream} equivalent: {@code stream.filter(type::isInstance).map(type::cast)}.
   * This does perform a little more work than necessary, so another option is to insert an
   * unchecked cast at some later point:
   *
   *

   * {@code @SuppressWarnings("unchecked") // safe because of ::isInstance check
   * ImmutableList<NewType> result =
   *     (ImmutableList) stream.filter(NewType.class::isInstance).collect(toImmutableList());}
   *

   */
  @GwtIncompatible // Class.isInstance
  public final <T> FluentIterable<T> filter(Class<T> type) {
    return from(Iterables.filter(getDelegate(), type));
  }

  /**
   * Returns {@code true} if any element in this fluent iterable satisfies the predicate.
   *
   *
{@code Stream} equivalent: {@link Stream#anyMatch} (same).
   */
  public final boolean anyMatch(Predicate<? super E> predicate) {
    return Iterables.any(getDelegate(), predicate);
  }

  /**
   * Returns {@code true} if every element in this fluent iterable satisfies the predicate. If this
   * fluent iterable is empty, {@code true} is returned.
   *
   *
{@code Stream} equivalent: {@link Stream#allMatch} (same).
   */
  public final boolean allMatch(Predicate<? super E> predicate) {
    return Iterables.all(getDelegate(), predicate);
  }

  /**
   * Returns an {@link Optional} containing the first element in this fluent iterable that satisfies
   * the given predicate, if such an element exists.
   *
   *
Warning: avoid using a {@code predicate} that matches {@code null}. If {@code null}
   * is matched in this fluent iterable, a {@link NullPointerException} will be thrown.
   *
   *
{@code Stream} equivalent: {@code stream.filter(predicate).findFirst()}.
   */
  public final Optional<E> firstMatch(Predicate<? super E> predicate) {
    return Iterables.tryFind(getDelegate(), predicate);
  }

  /**
   * Returns a fluent iterable that applies {@code function} to each element of this fluent
   * iterable.
   *
   *
The returned fluent iterable's iterator supports {@code remove()} if this iterable's
   * iterator does. After a successful {@code remove()} call, this fluent iterable no longer
   * contains the corresponding element.
   *
   *
{@code Stream} equivalent: {@link Stream#map}.
   */
  public final <T> FluentIterable<T> transform(Function<? super E, T> function) {
    return from(Iterables.transform(getDelegate(), function));
  }

  /**
   * Applies {@code function} to each element of this fluent iterable and returns a fluent iterable
   * with the concatenated combination of results. {@code function} returns an Iterable of results.
   *
   *
The returned fluent iterable's iterator supports {@code remove()} if this function-returned
   * iterables' iterator does. After a successful {@code remove()} call, the returned fluent
   * iterable no longer contains the corresponding element.
   *
   *
{@code Stream} equivalent: {@link Stream#flatMap} (using a function that produces
   * streams, not iterables).
   *
   * @since 13.0 (required {@code Function<E, Iterable<T>>} until 14.0)
   */
  public <T> FluentIterable<T> transformAndConcat(
      Function<? super E, ? extends Iterable<? extends T>> function) {
    return FluentIterable.concat(transform(function));
  }

  /**
   * Returns an {@link Optional} containing the first element in this fluent iterable. If the
   * iterable is empty, {@code Optional.absent()} is returned.
   *
   *
{@code Stream} equivalent: if the goal is to obtain any element, {@link
   * Stream#findAny}; if it must specifically be the first element, {@code Stream#findFirst}.
   *
   * @throws NullPointerException if the first element is null; if this is a possibility, use {@code
   *     iterator().next()} or {@link Iterables#getFirst} instead.
   */
  public final Optional<E> first() {
    Iterator<E> iterator = getDelegate().iterator();
    return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.<E>absent();
  }

  /**
   * Returns an {@link Optional} containing the last element in this fluent iterable. If the
   * iterable is empty, {@code Optional.absent()} is returned. If the underlying {@code iterable} is
   * a {@link List} with {@link java.util.RandomAccess} support, then this operation is guaranteed
   * to be {@code O(1)}.
   *
   *
{@code Stream} equivalent: {@code stream.reduce((a, b) -> b)}.
   *
   * @throws NullPointerException if the last element is null; if this is a possibility, use {@link
   *     Iterables#getLast} instead.
   */
  public final Optional<E> last() {
    // Iterables#getLast was inlined here so we don't have to throw/catch a NSEE

    // TODO(kevinb): Support a concurrently modified collection?
    Iterable<E> iterable = getDelegate();
    if (iterable instanceof List) {
      List<E> list = (List<E>) iterable;
      if (list.isEmpty()) {
        return Optional.absent();
      }
      return Optional.of(list.get(list.size() - 1));
    }
    Iterator<E> iterator = iterable.iterator();
    if (!iterator.hasNext()) {
      return Optional.absent();
    }

    /*
     * TODO(kevinb): consider whether this "optimization" is worthwhile. Users with SortedSets tend
     * to know they are SortedSets and probably would not call this method.
     */
    if (iterable instanceof SortedSet) {
      SortedSet<E> sortedSet = (SortedSet<E>) iterable;
      return Optional.of(sortedSet.last());
    }

    while (true) {
      E current = iterator.next();
      if (!iterator.hasNext()) {
        return Optional.of(current);
      }
    }
  }

  /**
   * Returns a view of this fluent iterable that skips its first {@code numberToSkip} elements. If
   * this fluent iterable contains fewer than {@code numberToSkip} elements, the returned fluent
   * iterable skips all of its elements.
   *
   *
Modifications to this fluent iterable before a call to {@code iterator()} are reflected in
   * the returned fluent iterable. That is, the its iterator skips the first {@code numberToSkip}
   * elements that exist when the iterator is created, not when {@code skip()} is called.
   *
   *
The returned fluent iterable's iterator supports {@code remove()} if the {@code Iterator} of
   * this fluent iterable supports it. Note that it is not possible to delete the last
   * skipped element by immediately calling {@code remove()} on the returned fluent iterable's
   * iterator, as the {@code Iterator} contract states that a call to {@code * remove()} before a
   * call to {@code next()} will throw an {@link IllegalStateException}.
   *
   *
{@code Stream} equivalent: {@link Stream#skip} (same).
   */
  public final FluentIterable<E> skip(int numberToSkip) {
    return from(Iterables.skip(getDelegate(), numberToSkip));
  }

  /**
   * Creates a fluent iterable with the first {@code size} elements of this fluent iterable. If this
   * fluent iterable does not contain that many elements, the returned fluent iterable will have the
   * same behavior as this fluent iterable. The returned fluent iterable's iterator supports {@code
   * remove()} if this fluent iterable's iterator does.
   *
   *
{@code Stream} equivalent: {@link Stream#limit} (same).
   *
   * @param maxSize the maximum number of elements in the returned fluent iterable
   * @throws IllegalArgumentException if {@code size} is negative
   */
  public final FluentIterable<E> limit(int maxSize) {
    return from(Iterables.limit(getDelegate(), maxSize));
  }

  /**
   * Determines whether this fluent iterable is empty.
   *
   *
{@code Stream} equivalent: {@code !stream.findAny().isPresent()}.
   */
  public final boolean isEmpty() {
    return !getDelegate().iterator().hasNext();
  }

  /**
   * Returns an {@code ImmutableList} containing all of the elements from this fluent iterable in
   * proper sequence.
   *
   *
{@code Stream} equivalent: pass {@link ImmutableList#toImmutableList} to {@code
   * stream.collect()}.
   *
   * @throws NullPointerException if any element is {@code null}
   * @since 14.0 (since 12.0 as {@code toImmutableList()}).
   */
  public final ImmutableList<E> toList() {
    return ImmutableList.copyOf(getDelegate());
  }

  /**
   * Returns an {@code ImmutableList} containing all of the elements from this {@code
   * FluentIterable} in the order specified by {@code comparator}. To produce an {@code
   * ImmutableList} sorted by its natural ordering, use {@code toSortedList(Ordering.natural())}.
   *
   *
{@code Stream} equivalent: pass {@link ImmutableList#toImmutableList} to {@code
   * stream.sorted(comparator).collect()}.
   *
   * @param comparator the function by which to sort list elements
   * @throws NullPointerException if any element of this iterable is {@code null}
   * @since 14.0 (since 13.0 as {@code toSortedImmutableList()}).
   */
  public final ImmutableList<E> toSortedList(Comparator<? super E> comparator) {
    return Ordering.from(comparator).immutableSortedCopy(getDelegate());
  }

  /**
   * Returns an {@code ImmutableSet} containing all of the elements from this fluent iterable with
   * duplicates removed.
   *
   *
{@code Stream} equivalent: pass {@link ImmutableSet#toImmutableSet} to {@code
   * stream.collect()}.
   *
   * @throws NullPointerException if any element is {@code null}
   * @since 14.0 (since 12.0 as {@code toImmutableSet()}).
   */
  public final ImmutableSet<E> toSet() {
    return ImmutableSet.copyOf(getDelegate());
  }

  /**
   * Returns an {@code ImmutableSortedSet} containing all of the elements from this {@code
   * FluentIterable} in the order specified by {@code comparator}, with duplicates (determined by
   * {@code comparator.compare(x, y) == 0}) removed. To produce an {@code ImmutableSortedSet} sorted
   * by its natural ordering, use {@code toSortedSet(Ordering.natural())}.
   *
   *
{@code Stream} equivalent: pass {@link ImmutableSortedSet#toImmutableSortedSet} to
   * {@code stream.collect()}.
   *
   * @param comparator the function by which to sort set elements
   * @throws NullPointerException if any element of this iterable is {@code null}
   * @since 14.0 (since 12.0 as {@code toImmutableSortedSet()}).
   */
  public final ImmutableSortedSet<E> toSortedSet(Comparator<? super E> comparator) {
    return ImmutableSortedSet.copyOf(comparator, getDelegate());
  }

  /**
   * Returns an {@code ImmutableMultiset} containing all of the elements from this fluent iterable.
   *
   *
{@code Stream} equivalent: pass {@link ImmutableMultiset#toImmutableMultiset} to
   * {@code stream.collect()}.
   *
   * @throws NullPointerException if any element is null
   * @since 19.0
   */
  public final ImmutableMultiset<E> toMultiset() {
    return ImmutableMultiset.copyOf(getDelegate());
  }

  /**
   * Returns an immutable map whose keys are the distinct elements of this {@code FluentIterable}
   * and whose value for each key was computed by {@code valueFunction}. The map's iteration order
   * is the order of the first appearance of each key in this iterable.
   *
   *
When there are multiple instances of a key in this iterable, it is unspecified whether
   * {@code valueFunction} will be applied to more than one instance of that key and, if it is,
   * which result will be mapped to that key in the returned map.
   *
   *
{@code Stream} equivalent: {@code stream.collect(ImmutableMap.toImmutableMap(k -> k,
   * valueFunction))}.
   *
   * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
   *     valueFunction} produces {@code null} for any key
   * @since 14.0
   */
  public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) {
    return Maps.toMap(getDelegate(), valueFunction);
  }

  /**
   * Creates an index {@code ImmutableListMultimap} that contains the results of applying a
   * specified function to each item in this {@code FluentIterable} of values. Each element of this
   * iterable will be stored as a value in the resulting multimap, yielding a multimap with the same
   * size as this iterable. The key used to store that value in the multimap will be the result of
   * calling the function on that value. The resulting multimap is created as an immutable snapshot.
   * In the returned multimap, keys appear in the order they are first encountered, and the values
   * corresponding to each key appear in the same order as they are encountered.
   *
   *
{@code Stream} equivalent: {@code stream.collect(Collectors.groupingBy(keyFunction))}
   * behaves similarly, but returns a mutable {@code Map<K, List<E>>} instead, and may not preserve
   * the order of entries).
   *
   * @param keyFunction the function used to produce the key for each value
   * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
   *     keyFunction} produces {@code null} for any key
   * @since 14.0
   */
  public final <K> ImmutableListMultimap<K, E> index(Function<? super E, K> keyFunction) {
    return Multimaps.index(getDelegate(), keyFunction);
  }

  /**
   * Returns a map with the contents of this {@code FluentIterable} as its {@code values}, indexed
   * by keys derived from those values. In other words, each input value produces an entry in the
   * map whose key is the result of applying {@code keyFunction} to that value. These entries appear
   * in the same order as they appeared in this fluent iterable. Example usage:
   *
   *
{@code
   * Color red = new Color("red", 255, 0, 0);
   * ...
   * FluentIterable<Color> allColors = FluentIterable.from(ImmutableSet.of(red, green, blue));
   *
   * Map<String, Color> colorForName = allColors.uniqueIndex(toStringFunction());
   * assertThat(colorForName).containsEntry("red", red);
   * }

   *
   *
If your index may associate multiple values with each key, use {@link #index(Function)
   * index}.
   *
   *
{@code Stream} equivalent: {@code
   * stream.collect(ImmutableMap.toImmutableMap(keyFunction, v -> v))}.
   *
   * @param keyFunction the function used to produce the key for each value
   * @return a map mapping the result of evaluating the function {@code keyFunction} on each value
   *     in this fluent iterable to that value
   * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
   *     value in this fluent iterable
   * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
   *     keyFunction} produces {@code null} for any key
   * @since 14.0
   */
  public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) {
    return Maps.uniqueIndex(getDelegate(), keyFunction);
  }

  /**
   * Returns an array containing all of the elements from this fluent iterable in iteration order.
   *
   *
{@code Stream} equivalent: if an object array is acceptable, use {@code
   * stream.toArray()}; if {@code type} is a class literal such as {@code MyType.class}, use {@code
   * stream.toArray(MyType[]::new)}. Otherwise use {@code stream.toArray( len -> (E[])
   * Array.newInstance(type, len))}.
   *
   * @param type the type of the elements
   * @return a newly-allocated array into which all the elements of this fluent iterable have been
   *     copied
   */
  @GwtIncompatible // Array.newArray(Class, int)
  public final E[] toArray(Class<E> type) {
    return Iterables.toArray(getDelegate(), type);
  }

  /**
   * Copies all the elements from this fluent iterable to {@code collection}. This is equivalent to
   * calling {@code Iterables.addAll(collection, this)}.
   *
   *
{@code Stream} equivalent: {@code stream.forEachOrdered(collection::add)} or {@code
   * stream.forEach(collection::add)}.
   *
   * @param collection the collection to copy elements to
   * @return {@code collection}, for convenience
   * @since 14.0
   */
  @CanIgnoreReturnValue
  public final <C extends Collection<? super E>> C copyInto(C collection) {
    checkNotNull(collection);
    Iterable<E> iterable = getDelegate();
    if (iterable instanceof Collection) {
      collection.addAll(Collections2.cast(iterable));
    } else {
      for (E item : iterable) {
        collection.add(item);
      }
    }
    return collection;
  }

  /**
   * Returns a {@link String} containing all of the elements of this fluent iterable joined with
   * {@code joiner}.
   *
   *
{@code Stream} equivalent: {@code joiner.join(stream.iterator())}, or, if you are not
   * using any optional {@code Joiner} features, {@code
   * stream.collect(Collectors.joining(delimiter)}.
   *
   * @since 18.0
   */
  @Beta
  public final String join(Joiner joiner) {
    return joiner.join(this);
  }

  /**
   * Returns the element at the specified position in this fluent iterable.
   *
   *
{@code Stream} equivalent: {@code stream.skip(position).findFirst().get()} (but note
   * that this throws different exception types, and throws an exception if {@code null} would be
   * returned).
   *
   * @param position position of the element to return
   * @return the element at the specified position in this fluent iterable
   * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to
   *     the size of this fluent iterable
   */
  // TODO(kevinb): add @Nullable?
  public final E get(int position) {
    return Iterables.get(getDelegate(), position);
  }

  /**
   * Returns a stream of this fluent iterable's contents (similar to calling {@link
   * Collection#stream} on a collection).
   *
   *
Note: the earlier in the chain you can switch to {@code Stream} usage (ideally not
   * going through {@code FluentIterable} at all), the more performant and idiomatic your code will
   * be. This method is a transitional aid, to be used only when really necessary.
   *
   * @since 21.0
   */
  public final Stream<E> stream() {
    return Streams.stream(getDelegate());
  }

  /** Function that transforms {@code Iterable<E>} into a fluent iterable. */
  private static class FromIterableFunction<E> implements Function<Iterable<E>, FluentIterable<E>> {
    @Override
    public FluentIterable<E> apply(Iterable<E> fromObject) {
      return FluentIterable.from(fromObject);
    }
  }
}


/*
 * Copyright (C) 2010 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.util.concurrent;

import com.google.common.annotations.GwtIncompatible;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * Static utility methods pertaining to classes in the {@code java.util.concurrent.atomic} package.
 *
 * @author Kurt Alfred Kluever
 * @since 10.0
 */
@GwtIncompatible
public final class Atomics {
  private Atomics() {}

  /**
   * Creates an {@code AtomicReference} instance with no initial value.
   *
   * @return a new {@code AtomicReference} with no initial value
   */
  public static <V> AtomicReference<V> newReference() {
    return new AtomicReference<V>();
  }

  /**
   * Creates an {@code AtomicReference} instance with the given initial value.
   *
   * @param initialValue the initial value
   * @return a new {@code AtomicReference} with the given initial value
   */
  public static <V> AtomicReference<V> newReference(@NullableDecl V initialValue) {
    return new AtomicReference<V>(initialValue);
  }

  /**
   * Creates an {@code AtomicReferenceArray} instance of given length.
   *
   * @param length the length of the array
   * @return a new {@code AtomicReferenceArray} with the given length
   */
  public static <E> AtomicReferenceArray<E> newReferenceArray(int length) {
    return new AtomicReferenceArray<E>(length);
  }

  /**
   * Creates an {@code AtomicReferenceArray} instance with the same length as, and all elements
   * copied from, the given array.
   *
   * @param array the array to copy elements from
   * @return a new {@code AtomicReferenceArray} copied from the given array
   */
  public static <E> AtomicReferenceArray<E> newReferenceArray(E[] array) {
    return new AtomicReferenceArray<E>(array);
  }
}


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

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.Weak;
import com.google.j2objc.annotations.WeakOuter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.checkerframework.checker.nullness.compatqual.MonotonicNonNullDecl;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * A {@link Multimap} whose contents will never change, with many other important properties
 * detailed at {@link ImmutableCollection}.
 *
 *
Warning: avoid direct usage of {@link ImmutableMultimap} as a type (as with
 * {@link Multimap} itself). Prefer subtypes such as {@link ImmutableSetMultimap} or {@link
 * ImmutableListMultimap}, which have well-defined {@link #equals} semantics, thus avoiding a common
 * source of bugs and confusion.
 *
 *
Note: every {@link ImmutableMultimap} offers an {@link #inverse} view, so there is no
 * need for a distinct {@code ImmutableBiMultimap} type.
 *
 *

 *
 *
Key-grouped iteration. All view collections follow the same iteration order. In all
 * current implementations, the iteration order always keeps multiple entries with the same key
 * together. Any creation method that would customarily respect insertion order (such as {@link
 * #copyOf(Multimap)}) instead preserves key-grouped order by inserting entries for an existing key
 * immediately after the last entry having that key.
 *
 *
See the Guava User Guide article on  immutable collections.
 *
 * @author Jared Levy
 * @since 2.0
 */
@GwtCompatible(emulated = true)
public abstract class ImmutableMultimap<K, V> extends BaseImmutableMultimap<K, V>
    implements Serializable {

  /** Returns an empty multimap. */
  public static <K, V> ImmutableMultimap<K, V> of() {
    return ImmutableListMultimap.of();
  }

  /** Returns an immutable multimap containing a single entry. */
  public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1) {
    return ImmutableListMultimap.of(k1, v1);
  }

  /** Returns an immutable multimap containing the given entries, in order. */
  public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2) {
    return ImmutableListMultimap.of(k1, v1, k2, v2);
  }

  /**
   * Returns an immutable multimap containing the given entries, in the "key-grouped" insertion
   * order described in the class documentation.
   */
  public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
    return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3);
  }

  /**
   * Returns an immutable multimap containing the given entries, in the "key-grouped" insertion
   * order described in the class documentation.
   */
  public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
    return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4);
  }

  /**
   * Returns an immutable multimap containing the given entries, in the "key-grouped" insertion
   * order described in the class documentation.
   */
  public static <K, V> ImmutableMultimap<K, V> of(
      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
    return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5);
  }

  // looking for of() with > 5 entries? Use the builder instead.

  /**
   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
   * Builder} constructor.
   */
  public static <K, V> Builder<K, V> builder() {
    return new Builder<>();
  }

  /**
   * A builder for creating immutable multimap instances, especially {@code public static final}
   * multimaps ("constant multimaps"). Example:
   *
   *
{@code
   * static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
   *     new ImmutableMultimap.Builder<String, Integer>()
   *         .put("one", 1)
   *         .putAll("several", 1, 2, 3)
   *         .putAll("many", 1, 2, 3, 4, 5)
   *         .build();
   * }

   *
   *
Builder instances can be reused; it is safe to call {@link #build} multiple times to build
   * multiple multimaps in series. Each multimap contains the key-value mappings in the previously
   * created multimaps.
   *
   * @since 2.0
   */
  public static class Builder<K, V> {
    Map<K, Collection<V>> builderMap;
    @MonotonicNonNullDecl Comparator<? super K> keyComparator;
    @MonotonicNonNullDecl Comparator<? super V> valueComparator;

    /**
     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
     * ImmutableMultimap#builder}.
     */
    public Builder() {
      this.builderMap = Platform.preservesInsertionOrderOnPutsMap();
    }

    Collection<V> newMutableValueCollection() {
      return new ArrayList<>();
    }

    /** Adds a key-value mapping to the built multimap. */
    @CanIgnoreReturnValue
    public Builder<K, V> put(K key, V value) {
      checkEntryNotNull(key, value);
      Collection<V> valueCollection = builderMap.get(key);
      if (valueCollection == null) {
        builderMap.put(key, valueCollection = newMutableValueCollection());
      }
      valueCollection.add(value);
      return this;
    }

    /**
     * Adds an entry to the built multimap.
     *
     * @since 11.0
     */
    @CanIgnoreReturnValue
    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
      return put(entry.getKey(), entry.getValue());
    }

    /**
     * Adds entries to the built multimap.
     *
     * @since 19.0
     */
    @CanIgnoreReturnValue
    @Beta
    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
      for (Entry<? extends K, ? extends V> entry : entries) {
        put(entry);
      }
      return this;
    }

    /**
     * Stores a collection of values with the same key in the built multimap.
     *
     * @throws NullPointerException if {@code key}, {@code values}, or any element in {@code values}
     *     is null. The builder is left in an invalid state.
     */
    @CanIgnoreReturnValue
    public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
      if (key == null) {
        throw new NullPointerException("null key in entry: null=" + Iterables.toString(values));
      }
      Collection<V> valueCollection = builderMap.get(key);
      if (valueCollection != null) {
        for (V value : values) {
          checkEntryNotNull(key, value);
          valueCollection.add(value);
        }
        return this;
      }
      Iterator<? extends V> valuesItr = values.iterator();
      if (!valuesItr.hasNext()) {
        return this;
      }
      valueCollection = newMutableValueCollection();
      while (valuesItr.hasNext()) {
        V value = valuesItr.next();
        checkEntryNotNull(key, value);
        valueCollection.add(value);
      }
      builderMap.put(key, valueCollection);
      return this;
    }

    /**
     * Stores an array of values with the same key in the built multimap.
     *
     * @throws NullPointerException if the key or any value is null. The builder is left in an
     *     invalid state.
     */
    @CanIgnoreReturnValue
    public Builder<K, V> putAll(K key, V... values) {
      return putAll(key, Arrays.asList(values));
    }

    /**
     * Stores another multimap's entries in the built multimap. The generated multimap's key and
     * value orderings correspond to the iteration ordering of the {@code multimap.asMap()} view,
     * with new keys and values following any existing keys and values.
     *
     * @throws NullPointerException if any key or value in {@code multimap} is null. The builder is
     *     left in an invalid state.
     */
    @CanIgnoreReturnValue
    public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
      for (Entry<? extends K, ? extends Collection<? extends V>> entry :
          multimap.asMap().entrySet()) {
        putAll(entry.getKey(), entry.getValue());
      }
      return this;
    }

    /**
     * Specifies the ordering of the generated multimap's keys.
     *
     * @since 8.0
     */
    @CanIgnoreReturnValue
    public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
      this.keyComparator = checkNotNull(keyComparator);
      return this;
    }

    /**
     * Specifies the ordering of the generated multimap's values for each key.
     *
     * @since 8.0
     */
    @CanIgnoreReturnValue
    public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
      this.valueComparator = checkNotNull(valueComparator);
      return this;
    }

    @CanIgnoreReturnValue
    Builder<K, V> combine(Builder<K, V> other) {
      for (Map.Entry<K, Collection<V>> entry : other.builderMap.entrySet()) {
        putAll(entry.getKey(), entry.getValue());
      }
      return this;
    }

    /** Returns a newly-created immutable multimap. */
    public ImmutableMultimap<K, V> build() {
      Collection<Map.Entry<K, Collection<V>>> mapEntries = builderMap.entrySet();
      if (keyComparator != null) {
        mapEntries = Ordering.from(keyComparator).<K>onKeys().immutableSortedCopy(mapEntries);
      }
      return ImmutableListMultimap.fromMapEntries(mapEntries, valueComparator);
    }
  }

  /**
   * Returns an immutable multimap containing the same mappings as {@code multimap}, in the
   * "key-grouped" iteration order described in the class documentation.
   *
   *
Despite the method name, this method attempts to avoid actually copying the data when it is
   * safe to do so. The exact circumstances under which a copy will or will not be performed are
   * undocumented and subject to change.
   *
   * @throws NullPointerException if any key or value in {@code multimap} is null
   */
  public static <K, V> ImmutableMultimap<K, V> copyOf(Multimap<? extends K, ? extends V> multimap) {
    if (multimap instanceof ImmutableMultimap) {
      @SuppressWarnings("unchecked") // safe since multimap is not writable
      ImmutableMultimap<K, V> kvMultimap = (ImmutableMultimap<K, V>) multimap;
      if (!kvMultimap.isPartialView()) {
        return kvMultimap;
      }
    }
    return ImmutableListMultimap.copyOf(multimap);
  }

  /**
   * Returns an immutable multimap containing the specified entries. The returned multimap iterates
   * over keys in the order they were first encountered in the input, and the values for each key
   * are iterated in the order they were encountered.
   *
   * @throws NullPointerException if any key, value, or entry is null
   * @since 19.0
   */
  @Beta
  public static <K, V> ImmutableMultimap<K, V> copyOf(
      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
    return ImmutableListMultimap.copyOf(entries);
  }

  final transient ImmutableMap<K, ? extends ImmutableCollection<V>> map;
  final transient int size;

  // These constants allow the deserialization code to set final fields. This
  // holder class makes sure they are not initialized unless an instance is
  // deserialized.
  @GwtIncompatible // java serialization is not supported
  static class FieldSettersHolder {
    static final Serialization.FieldSetter<ImmutableMultimap> MAP_FIELD_SETTER =
        Serialization.getFieldSetter(ImmutableMultimap.class, "map");
    static final Serialization.FieldSetter<ImmutableMultimap> SIZE_FIELD_SETTER =
        Serialization.getFieldSetter(ImmutableMultimap.class, "size");
  }

  ImmutableMultimap(ImmutableMap<K, ? extends ImmutableCollection<V>> map, int size) {
    this.map = map;
    this.size = size;
  }

  // mutators (not supported)

  /**
   * Guaranteed to throw an exception and leave the multimap unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @CanIgnoreReturnValue
  @Deprecated
  @Override
  public ImmutableCollection<V> removeAll(Object key) {
    throw new UnsupportedOperationException();
  }

  /**
   * Guaranteed to throw an exception and leave the multimap unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @CanIgnoreReturnValue
  @Deprecated
  @Override
  public ImmutableCollection<V> replaceValues(K key, Iterable<? extends V> values) {
    throw new UnsupportedOperationException();
  }

  /**
   * Guaranteed to throw an exception and leave the multimap unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @Deprecated
  @Override
  public void clear() {
    throw new UnsupportedOperationException();
  }

  /**
   * Returns an immutable collection of the values for the given key. If no mappings in the multimap
   * have the provided key, an empty immutable collection is returned. The values are in the same
   * order as the parameters used to build this multimap.
   */
  @Override
  public abstract ImmutableCollection<V> get(K key);

  /**
   * Returns an immutable multimap which is the inverse of this one. For every key-value mapping in
   * the original, the result will have a mapping with key and value reversed.
   *
   * @since 11.0
   */
  public abstract ImmutableMultimap<V, K> inverse();

  /**
   * Guaranteed to throw an exception and leave the multimap unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @CanIgnoreReturnValue
  @Deprecated
  @Override
  public boolean put(K key, V value) {
    throw new UnsupportedOperationException();
  }

  /**
   * Guaranteed to throw an exception and leave the multimap unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @CanIgnoreReturnValue
  @Deprecated
  @Override
  public boolean putAll(K key, Iterable<? extends V> values) {
    throw new UnsupportedOperationException();
  }

  /**
   * Guaranteed to throw an exception and leave the multimap unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @CanIgnoreReturnValue
  @Deprecated
  @Override
  public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
    throw new UnsupportedOperationException();
  }

  /**
   * Guaranteed to throw an exception and leave the multimap unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @CanIgnoreReturnValue
  @Deprecated
  @Override
  public boolean remove(Object key, Object value) {
    throw new UnsupportedOperationException();
  }

  /**
   * Returns {@code true} if this immutable multimap's implementation contains references to
   * user-created objects that aren't accessible via this multimap's methods. This is generally used
   * to determine whether {@code copyOf} implementations should make an explicit copy to avoid
   * memory leaks.
   */
  boolean isPartialView() {
    return map.isPartialView();
  }

  // accessors

  @Override
  public boolean containsKey(@NullableDecl Object key) {
    return map.containsKey(key);
  }

  @Override
  public boolean containsValue(@NullableDecl Object value) {
    return value != null && super.containsValue(value);
  }

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

  // views

  /**
   * Returns an immutable set of the distinct keys in this multimap, in the same order as they
   * appear in this multimap.
   */
  @Override
  public ImmutableSet<K> keySet() {
    return map.keySet();
  }

  @Override
  Set<K> createKeySet() {
    throw new AssertionError("unreachable");
  }

  /**
   * Returns an immutable map that associates each key with its corresponding values in the
   * multimap. Keys and values appear in the same order as in this multimap.
   */
  @Override
  @SuppressWarnings("unchecked") // a widening cast
  public ImmutableMap<K, Collection<V>> asMap() {
    return (ImmutableMap) map;
  }

  @Override
  Map<K, Collection<V>> createAsMap() {
    throw new AssertionError("should never be called");
  }

  /** Returns an immutable collection of all key-value pairs in the multimap. */
  @Override
  public ImmutableCollection<Entry<K, V>> entries() {
    return (ImmutableCollection<Entry<K, V>>) super.entries();
  }

  @Override
  ImmutableCollection<Entry<K, V>> createEntries() {
    return new EntryCollection<>(this);
  }

  private static class EntryCollection<K, V> extends ImmutableCollection<Entry<K, V>> {
    @Weak final ImmutableMultimap<K, V> multimap;

    EntryCollection(ImmutableMultimap<K, V> multimap) {
      this.multimap = multimap;
    }

    @Override
    public UnmodifiableIterator<Entry<K, V>> iterator() {
      return multimap.entryIterator();
    }

    @Override
    boolean isPartialView() {
      return multimap.isPartialView();
    }

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

    @Override
    public boolean contains(Object object) {
      if (object instanceof Entry) {
        Entry<?, ?> entry = (Entry<?, ?>) object;
        return multimap.containsEntry(entry.getKey(), entry.getValue());
      }
      return false;
    }

    private static final long serialVersionUID = 0;
  }

  @Override
  UnmodifiableIterator<Entry<K, V>> entryIterator() {
    return new UnmodifiableIterator<Entry<K, V>>() {
      final Iterator<? extends Entry<K, ? extends ImmutableCollection<V>>> asMapItr =
          map.entrySet().iterator();
      K currentKey = null;
      Iterator<V> valueItr = Iterators.emptyIterator();

      @Override
      public boolean hasNext() {
        return valueItr.hasNext() || asMapItr.hasNext();
      }

      @Override
      public Entry<K, V> next() {
        if (!valueItr.hasNext()) {
          Entry<K, ? extends ImmutableCollection<V>> entry = asMapItr.next();
          currentKey = entry.getKey();
          valueItr = entry.getValue().iterator();
        }
        return Maps.immutableEntry(currentKey, valueItr.next());
      }
    };
  }

  /**
   * Returns an immutable multiset containing all the keys in this multimap, in the same order and
   * with the same frequencies as they appear in this multimap; to get only a single occurrence of
   * each key, use {@link #keySet}.
   */
  @Override
  public ImmutableMultiset<K> keys() {
    return (ImmutableMultiset<K>) super.keys();
  }

  @Override
  ImmutableMultiset<K> createKeys() {
    return new Keys();
  }

  @SuppressWarnings("serial") // Uses writeReplace, not default serialization
  @WeakOuter
  class Keys extends ImmutableMultiset<K> {
    @Override
    public boolean contains(@NullableDecl Object object) {
      return containsKey(object);
    }

    @Override
    public int count(@NullableDecl Object element) {
      Collection<V> values = map.get(element);
      return (values == null) ? 0 : values.size();
    }

    @Override
    public ImmutableSet<K> elementSet() {
      return keySet();
    }

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

    @Override
    Multiset.Entry<K> getEntry(int index) {
      Map.Entry<K, ? extends Collection<V>> entry = map.entrySet().asList().get(index);
      return Multisets.immutableEntry(entry.getKey(), entry.getValue().size());
    }

    @Override
    boolean isPartialView() {
      return true;
    }

    @GwtIncompatible
    @Override
    Object writeReplace() {
      return new KeysSerializedForm(ImmutableMultimap.this);
    }
  }

  @GwtIncompatible
  private static final class KeysSerializedForm implements Serializable {
    final ImmutableMultimap<?, ?> multimap;

    KeysSerializedForm(ImmutableMultimap<?, ?> multimap) {
      this.multimap = multimap;
    }

    Object readResolve() {
      return multimap.keys();
    }
  }

  /**
   * Returns an immutable collection of the values in this multimap. Its iterator traverses the
   * values for the first key, the values for the second key, and so on.
   */
  @Override
  public ImmutableCollection<V> values() {
    return (ImmutableCollection<V>) super.values();
  }

  @Override
  ImmutableCollection<V> createValues() {
    return new Values<>(this);
  }

  @Override
  UnmodifiableIterator<V> valueIterator() {
    return new UnmodifiableIterator<V>() {
      Iterator<? extends ImmutableCollection<V>> valueCollectionItr = map.values().iterator();
      Iterator<V> valueItr = Iterators.emptyIterator();

      @Override
      public boolean hasNext() {
        return valueItr.hasNext() || valueCollectionItr.hasNext();
      }

      @Override
      public V next() {
        if (!valueItr.hasNext()) {
          valueItr = valueCollectionItr.next().iterator();
        }
        return valueItr.next();
      }
    };
  }

  private static final class Values<K, V> extends ImmutableCollection<V> {
    @Weak private final transient ImmutableMultimap<K, V> multimap;

    Values(ImmutableMultimap<K, V> multimap) {
      this.multimap = multimap;
    }

    @Override
    public boolean contains(@NullableDecl Object object) {
      return multimap.containsValue(object);
    }

    @Override
    public UnmodifiableIterator<V> iterator() {
      return multimap.valueIterator();
    }

    @GwtIncompatible // not present in emulated superclass
    @Override
    int copyIntoArray(Object[] dst, int offset) {
      for (ImmutableCollection<V> valueCollection : multimap.map.values()) {
        offset = valueCollection.copyIntoArray(dst, offset);
      }
      return offset;
    }

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

    @Override
    boolean isPartialView() {
      return true;
    }

    private static final long serialVersionUID = 0;
  }

  private static final long serialVersionUID = 0;
}


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

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.graph.GraphConstants.NODE_NOT_IN_GRAPH;

import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * Static utility methods for {@link Graph}, {@link ValueGraph}, and {@link Network} instances.
 *
 * @author James Sexton
 * @author Joshua O'Madadhain
 * @since 20.0
 */
@Beta
public final class Graphs {

  private Graphs() {}

  // Graph query methods

  /**
   * Returns true if {@code graph} has at least one cycle. A cycle is defined as a non-empty subset
   * of edges in a graph arranged to form a path (a sequence of adjacent outgoing edges) starting
   * and ending with the same node.
   *
   *
This method will detect any non-empty cycle, including self-loops (a cycle of length 1).
   */
  public static <N> boolean hasCycle(Graph<N> graph) {
    int numEdges = graph.edges().size();
    if (numEdges == 0) {
      return false; // An edge-free graph is acyclic by definition.
    }
    if (!graph.isDirected() && numEdges >= graph.nodes().size()) {
      return true; // Optimization for the undirected case: at least one cycle must exist.
    }

    Map<Object, NodeVisitState> visitedNodes =
        Maps.newHashMapWithExpectedSize(graph.nodes().size());
    for (N node : graph.nodes()) {
      if (subgraphHasCycle(graph, visitedNodes, node, null)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Returns true if {@code network} has at least one cycle. A cycle is defined as a non-empty
   * subset of edges in a graph arranged to form a path (a sequence of adjacent outgoing edges)
   * starting and ending with the same node.
   *
   *
This method will detect any non-empty cycle, including self-loops (a cycle of length 1).
   */
  public static boolean hasCycle(Network<?, ?> network) {
    // In a directed graph, parallel edges cannot introduce a cycle in an acyclic graph.
    // However, in an undirected graph, any parallel edge induces a cycle in the graph.
    if (!network.isDirected()
        && network.allowsParallelEdges()
        && network.edges().size() > network.asGraph().edges().size()) {
      return true;
    }
    return hasCycle(network.asGraph());
  }

  /**
   * Performs a traversal of the nodes reachable from {@code node}. If we ever reach a node we've
   * already visited (following only outgoing edges and without reusing edges), we know there's a
   * cycle in the graph.
   */
  private static <N> boolean subgraphHasCycle(
      Graph<N> graph,
      Map<Object, NodeVisitState> visitedNodes,
      N node,
      @NullableDecl N previousNode) {
    NodeVisitState state = visitedNodes.get(node);
    if (state == NodeVisitState.COMPLETE) {
      return false;
    }
    if (state == NodeVisitState.PENDING) {
      return true;
    }

    visitedNodes.put(node, NodeVisitState.PENDING);
    for (N nextNode : graph.successors(node)) {
      if (canTraverseWithoutReusingEdge(graph, nextNode, previousNode)
          && subgraphHasCycle(graph, visitedNodes, nextNode, node)) {
        return true;
      }
    }
    visitedNodes.put(node, NodeVisitState.COMPLETE);
    return false;
  }

  /**
   * Determines whether an edge has already been used during traversal. In the directed case a cycle
   * is always detected before reusing an edge, so no special logic is required. In the undirected
   * case, we must take care not to "backtrack" over an edge (i.e. going from A to B and then going
   * from B to A).
   */
  private static boolean canTraverseWithoutReusingEdge(
      Graph<?> graph, Object nextNode, @NullableDecl Object previousNode) {
    if (graph.isDirected() || !Objects.equal(previousNode, nextNode)) {
      return true;
    }
    // This falls into the undirected A->B->A case. The Graph interface does not support parallel
    // edges, so this traversal would require reusing the undirected AB edge.
    return false;
  }

  /**
   * Returns the transitive closure of {@code graph}. The transitive closure of a graph is another
   * graph with an edge connecting node A to node B if node B is {@link #reachableNodes(Graph,
   * Object) reachable} from node A.
   *
   *
This is a "snapshot" based on the current topology of {@code graph}, rather than a live view
   * of the transitive closure of {@code graph}. In other words, the returned {@link Graph} will not
   * be updated after modifications to {@code graph}.
   */
  // TODO(b/31438252): Consider potential optimizations for this algorithm.
  public static <N> Graph<N> transitiveClosure(Graph<N> graph) {
    MutableGraph<N> transitiveClosure = GraphBuilder.from(graph).allowsSelfLoops(true).build();
    // Every node is, at a minimum, reachable from itself. Since the resulting transitive closure
    // will have no isolated nodes, we can skip adding nodes explicitly and let putEdge() do it.

    if (graph.isDirected()) {
      // Note: works for both directed and undirected graphs, but we only use in the directed case.
      for (N node : graph.nodes()) {
        for (N reachableNode : reachableNodes(graph, node)) {
          transitiveClosure.putEdge(node, reachableNode);
        }
      }
    } else {
      // An optimization for the undirected case: for every node B reachable from node A,
      // node A and node B have the same reachability set.
      Set<N> visitedNodes = new HashSet<N>();
      for (N node : graph.nodes()) {
        if (!visitedNodes.contains(node)) {
          Set<N> reachableNodes = reachableNodes(graph, node);
          visitedNodes.addAll(reachableNodes);
          int pairwiseMatch = 1; // start at 1 to include self-loops
          for (N nodeU : reachableNodes) {
            for (N nodeV : Iterables.limit(reachableNodes, pairwiseMatch++)) {
              transitiveClosure.putEdge(nodeU, nodeV);
            }
          }
        }
      }
    }

    return transitiveClosure;
  }

  /**
   * Returns the set of nodes that are reachable from {@code node}. Node B is defined as reachable
   * from node A if there exists a path (a sequence of adjacent outgoing edges) starting at node A
   * and ending at node B. Note that a node is always reachable from itself via a zero-length path.
   *
   *
This is a "snapshot" based on the current topology of {@code graph}, rather than a live view
   * of the set of nodes reachable from {@code node}. In other words, the returned {@link Set} will
   * not be updated after modifications to {@code graph}.
   *
   * @throws IllegalArgumentException if {@code node} is not present in {@code graph}
   */
  public static <N> Set<N> reachableNodes(Graph<N> graph, N node) {
    checkArgument(graph.nodes().contains(node), NODE_NOT_IN_GRAPH, node);
    Set<N> visitedNodes = new LinkedHashSet<N>();
    Queue<N> queuedNodes = new ArrayDeque<N>();
    visitedNodes.add(node);
    queuedNodes.add(node);
    // Perform a breadth-first traversal rooted at the input node.
    while (!queuedNodes.isEmpty()) {
      N currentNode = queuedNodes.remove();
      for (N successor : graph.successors(currentNode)) {
        if (visitedNodes.add(successor)) {
          queuedNodes.add(successor);
        }
      }
    }
    return Collections.unmodifiableSet(visitedNodes);
  }

  // Graph mutation methods

  // Graph view methods

  /**
   * Returns a view of {@code graph} with the direction (if any) of every edge reversed. All other
   * properties remain intact, and further updates to {@code graph} will be reflected in the view.
   */
  public static <N> Graph<N> transpose(Graph<N> graph) {
    if (!graph.isDirected()) {
      return graph; // the transpose of an undirected graph is an identical graph
    }

    if (graph instanceof TransposedGraph) {
      return ((TransposedGraph<N>) graph).graph;
    }

    return new TransposedGraph<N>(graph);
  }

  /**
   * Returns a view of {@code graph} with the direction (if any) of every edge reversed. All other
   * properties remain intact, and further updates to {@code graph} will be reflected in the view.
   */
  public static <N, V> ValueGraph<N, V> transpose(ValueGraph<N, V> graph) {
    if (!graph.isDirected()) {
      return graph; // the transpose of an undirected graph is an identical graph
    }

    if (graph instanceof TransposedValueGraph) {
      return ((TransposedValueGraph<N, V>) graph).graph;
    }

    return new TransposedValueGraph<>(graph);
  }

  /**
   * Returns a view of {@code network} with the direction (if any) of every edge reversed. All other
   * properties remain intact, and further updates to {@code network} will be reflected in the view.
   */
  public static <N, E> Network<N, E> transpose(Network<N, E> network) {
    if (!network.isDirected()) {
      return network; // the transpose of an undirected network is an identical network
    }

    if (network instanceof TransposedNetwork) {
      return ((TransposedNetwork<N, E>) network).network;
    }

    return new TransposedNetwork<>(network);
  }

  static <N> EndpointPair<N> transpose(EndpointPair<N> endpoints) {
    if (endpoints.isOrdered()) {
      return EndpointPair.ordered(endpoints.target(), endpoints.source());
    }
    return endpoints;
  }

  // NOTE: this should work as long as the delegate graph's implementation of edges() (like that of
  // AbstractGraph) derives its behavior from calling successors().
  private static class TransposedGraph<N> extends ForwardingGraph<N> {
    private final Graph<N> graph;

    TransposedGraph(Graph<N> graph) {
      this.graph = graph;
    }

    @Override
    protected Graph<N> delegate() {
      return graph;
    }

    @Override
    public Set<N> predecessors(N node) {
      return delegate().successors(node); // transpose
    }

    @Override
    public Set<N> successors(N node) {
      return delegate().predecessors(node); // transpose
    }

    @Override
    public int inDegree(N node) {
      return delegate().outDegree(node); // transpose
    }

    @Override
    public int outDegree(N node) {
      return delegate().inDegree(node); // transpose
    }

    @Override
    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
    }

    @Override
    public boolean hasEdgeConnecting(EndpointPair<N> endpoints) {
      return delegate().hasEdgeConnecting(transpose(endpoints));
    }
  }

  // NOTE: this should work as long as the delegate graph's implementation of edges() (like that of
  // AbstractValueGraph) derives its behavior from calling successors().
  private static class TransposedValueGraph<N, V> extends ForwardingValueGraph<N, V> {
    private final ValueGraph<N, V> graph;

    TransposedValueGraph(ValueGraph<N, V> graph) {
      this.graph = graph;
    }

    @Override
    protected ValueGraph<N, V> delegate() {
      return graph;
    }

    @Override
    public Set<N> predecessors(N node) {
      return delegate().successors(node); // transpose
    }

    @Override
    public Set<N> successors(N node) {
      return delegate().predecessors(node); // transpose
    }

    @Override
    public int inDegree(N node) {
      return delegate().outDegree(node); // transpose
    }

    @Override
    public int outDegree(N node) {
      return delegate().inDegree(node); // transpose
    }

    @Override
    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
    }

    @Override
    public boolean hasEdgeConnecting(EndpointPair<N> endpoints) {
      return delegate().hasEdgeConnecting(transpose(endpoints));
    }

    @Override
    @NullableDecl
    public V edgeValueOrDefault(N nodeU, N nodeV, @NullableDecl V defaultValue) {
      return delegate().edgeValueOrDefault(nodeV, nodeU, defaultValue); // transpose
    }

    @Override
    @NullableDecl
    public V edgeValueOrDefault(EndpointPair<N> endpoints, @NullableDecl V defaultValue) {
      return delegate().edgeValueOrDefault(transpose(endpoints), defaultValue);
    }
  }

  private static class TransposedNetwork<N, E> extends ForwardingNetwork<N, E> {
    private final Network<N, E> network;

    TransposedNetwork(Network<N, E> network) {
      this.network = network;
    }

    @Override
    protected Network<N, E> delegate() {
      return network;
    }

    @Override
    public Set<N> predecessors(N node) {
      return delegate().successors(node); // transpose
    }

    @Override
    public Set<N> successors(N node) {
      return delegate().predecessors(node); // transpose
    }

    @Override
    public int inDegree(N node) {
      return delegate().outDegree(node); // transpose
    }

    @Override
    public int outDegree(N node) {
      return delegate().inDegree(node); // transpose
    }

    @Override
    public Set<E> inEdges(N node) {
      return delegate().outEdges(node); // transpose
    }

    @Override
    public Set<E> outEdges(N node) {
      return delegate().inEdges(node); // transpose
    }

    @Override
    public EndpointPair<N> incidentNodes(E edge) {
      EndpointPair<N> endpointPair = delegate().incidentNodes(edge);
      return EndpointPair.of(network, endpointPair.nodeV(), endpointPair.nodeU()); // transpose
    }

    @Override
    public Set<E> edgesConnecting(N nodeU, N nodeV) {
      return delegate().edgesConnecting(nodeV, nodeU); // transpose
    }

    @Override
    public Set<E> edgesConnecting(EndpointPair<N> endpoints) {
      return delegate().edgesConnecting(transpose(endpoints));
    }

    @Override
    public E edgeConnectingOrNull(N nodeU, N nodeV) {
      return delegate().edgeConnectingOrNull(nodeV, nodeU); // transpose
    }

    @Override
    public E edgeConnectingOrNull(EndpointPair<N> endpoints) {
      return delegate().edgeConnectingOrNull(transpose(endpoints));
    }

    @Override
    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
    }

    @Override
    public boolean hasEdgeConnecting(EndpointPair<N> endpoints) {
      return delegate().hasEdgeConnecting(transpose(endpoints));
    }
  }

  // Graph copy methods

  /**
   * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph
   * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges}
   * from {@code graph} for which both nodes are contained by {@code nodes}.
   *
   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
   */
  public static <N> MutableGraph<N> inducedSubgraph(Graph<N> graph, Iterable<? extends N> nodes) {
    MutableGraph<N> subgraph =
        (nodes instanceof Collection)
            ? GraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build()
            : GraphBuilder.from(graph).build();
    for (N node : nodes) {
      subgraph.addNode(node);
    }
    for (N node : subgraph.nodes()) {
      for (N successorNode : graph.successors(node)) {
        if (subgraph.nodes().contains(successorNode)) {
          subgraph.putEdge(node, successorNode);
        }
      }
    }
    return subgraph;
  }

  /**
   * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph
   * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges}
   * (and associated edge values) from {@code graph} for which both nodes are contained by {@code
   * nodes}.
   *
   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
   */
  public static <N, V> MutableValueGraph<N, V> inducedSubgraph(
      ValueGraph<N, V> graph, Iterable<? extends N> nodes) {
    MutableValueGraph<N, V> subgraph =
        (nodes instanceof Collection)
            ? ValueGraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build()
            : ValueGraphBuilder.from(graph).build();
    for (N node : nodes) {
      subgraph.addNode(node);
    }
    for (N node : subgraph.nodes()) {
      for (N successorNode : graph.successors(node)) {
        if (subgraph.nodes().contains(successorNode)) {
          subgraph.putEdgeValue(
              node, successorNode, graph.edgeValueOrDefault(node, successorNode, null));
        }
      }
    }
    return subgraph;
  }

  /**
   * Returns the subgraph of {@code network} induced by {@code nodes}. This subgraph is a new graph
   * that contains all of the nodes in {@code nodes}, and all of the {@link Network#edges() edges}
   * from {@code network} for which the {@link Network#incidentNodes(Object) incident nodes} are
   * both contained by {@code nodes}.
   *
   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
   */
  public static <N, E> MutableNetwork<N, E> inducedSubgraph(
      Network<N, E> network, Iterable<? extends N> nodes) {
    MutableNetwork<N, E> subgraph =
        (nodes instanceof Collection)
            ? NetworkBuilder.from(network).expectedNodeCount(((Collection) nodes).size()).build()
            : NetworkBuilder.from(network).build();
    for (N node : nodes) {
      subgraph.addNode(node);
    }
    for (N node : subgraph.nodes()) {
      for (E edge : network.outEdges(node)) {
        N successorNode = network.incidentNodes(edge).adjacentNode(node);
        if (subgraph.nodes().contains(successorNode)) {
          subgraph.addEdge(node, successorNode, edge);
        }
      }
    }
    return subgraph;
  }

  /** Creates a mutable copy of {@code graph} with the same nodes and edges. */
  public static <N> MutableGraph<N> copyOf(Graph<N> graph) {
    MutableGraph<N> copy = GraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
    for (N node : graph.nodes()) {
      copy.addNode(node);
    }
    for (EndpointPair<N> edge : graph.edges()) {
      copy.putEdge(edge.nodeU(), edge.nodeV());
    }
    return copy;
  }

  /** Creates a mutable copy of {@code graph} with the same nodes, edges, and edge values. */
  public static <N, V> MutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) {
    MutableValueGraph<N, V> copy =
        ValueGraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
    for (N node : graph.nodes()) {
      copy.addNode(node);
    }
    for (EndpointPair<N> edge : graph.edges()) {
      copy.putEdgeValue(
          edge.nodeU(), edge.nodeV(), graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null));
    }
    return copy;
  }

  /** Creates a mutable copy of {@code network} with the same nodes and edges. */
  public static <N, E> MutableNetwork<N, E> copyOf(Network<N, E> network) {
    MutableNetwork<N, E> copy =
        NetworkBuilder.from(network)
            .expectedNodeCount(network.nodes().size())
            .expectedEdgeCount(network.edges().size())
            .build();
    for (N node : network.nodes()) {
      copy.addNode(node);
    }
    for (E edge : network.edges()) {
      EndpointPair<N> endpointPair = network.incidentNodes(edge);
      copy.addEdge(endpointPair.nodeU(), endpointPair.nodeV(), edge);
    }
    return copy;
  }

  @CanIgnoreReturnValue
  static int checkNonNegative(int value) {
    checkArgument(value >= 0, "Not true that %s is non-negative.", value);
    return value;
  }

  @CanIgnoreReturnValue
  static long checkNonNegative(long value) {
    checkArgument(value >= 0, "Not true that %s is non-negative.", value);
    return value;
  }

  @CanIgnoreReturnValue
  static int checkPositive(int value) {
    checkArgument(value > 0, "Not true that %s is positive.", value);
    return value;
  }

  @CanIgnoreReturnValue
  static long checkPositive(long value) {
    checkArgument(value > 0, "Not true that %s is positive.", value);
    return value;
  }

  /**
   * An enum representing the state of a node during DFS. {@code PENDING} means that the node is on
   * the stack of the DFS, while {@code COMPLETE} means that the node and all its successors have
   * been already explored. Any node that has not been explored will not have a state at all.
   */
  private enum NodeVisitState {
    PENDING,
    COMPLETE
  }
}