/*
 * Copyright (C) 2009 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.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Supplier;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.WeakOuter;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Base class for services that do not need a thread while "running" but may need one during startup
 * and shutdown. Subclasses can implement {@link #startUp} and {@link #shutDown} methods, each which
 * run in a executor which by default uses a separate thread for each method.
 *
 * @author Chris Nokleberg
 * @since 1.0
 */
@Beta
@GwtIncompatible
public abstract class AbstractIdleService implements Service {

  /* Thread names will look like {@code "MyService STARTING"}. */
  private final Supplier<String> threadNameSupplier = new ThreadNameSupplier();

  @WeakOuter
  private final class ThreadNameSupplier implements Supplier<String> {
    @Override
    public String get() {
      return serviceName() + " " + state();
    }
  }

  /* use AbstractService for state management */
  private final Service delegate = new DelegateService();

  @WeakOuter
  private final class DelegateService extends AbstractService {
    @Override
    protected final void doStart() {
      MoreExecutors.renamingDecorator(executor(), threadNameSupplier)
          .execute(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    startUp();
                    notifyStarted();
                  } catch (Throwable t) {
                    notifyFailed(t);
                  }
                }
              });
    }

    @Override
    protected final void doStop() {
      MoreExecutors.renamingDecorator(executor(), threadNameSupplier)
          .execute(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    shutDown();
                    notifyStopped();
                  } catch (Throwable t) {
                    notifyFailed(t);
                  }
                }
              });
    }

    @Override
    public String toString() {
      return AbstractIdleService.this.toString();
    }
  }

  /** Constructor for use by subclasses. */
  protected AbstractIdleService() {}

  /** Start the service. */
  protected abstract void startUp() throws Exception;

  /** Stop the service. */
  protected abstract void shutDown() throws Exception;

  /**
   * Returns the {@link Executor} that will be used to run this service. Subclasses may override
   * this method to use a custom {@link Executor}, which may configure its worker thread with a
   * specific name, thread group or priority. The returned executor's {@link
   * Executor#execute(Runnable) execute()} method is called when this service is started and
   * stopped, and should return promptly.
   */
  protected Executor executor() {
    return new Executor() {
      @Override
      public void execute(Runnable command) {
        MoreExecutors.newThread(threadNameSupplier.get(), command).start();
      }
    };
  }

  @Override
  public String toString() {
    return serviceName() + " [" + state() + "]";
  }

  @Override
  public final boolean isRunning() {
    return delegate.isRunning();
  }

  @Override
  public final State state() {
    return delegate.state();
  }

  /** @since 13.0 */
  @Override
  public final void addListener(Listener listener, Executor executor) {
    delegate.addListener(listener, executor);
  }

  /** @since 14.0 */
  @Override
  public final Throwable failureCause() {
    return delegate.failureCause();
  }

  /** @since 15.0 */
  @CanIgnoreReturnValue
  @Override
  public final Service startAsync() {
    delegate.startAsync();
    return this;
  }

  /** @since 15.0 */
  @CanIgnoreReturnValue
  @Override
  public final Service stopAsync() {
    delegate.stopAsync();
    return this;
  }

  /** @since 15.0 */
  @Override
  public final void awaitRunning() {
    delegate.awaitRunning();
  }

  /** @since 15.0 */
  @Override
  public final void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException {
    delegate.awaitRunning(timeout, unit);
  }

  /** @since 15.0 */
  @Override
  public final void awaitTerminated() {
    delegate.awaitTerminated();
  }

  /** @since 15.0 */
  @Override
  public final void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException {
    delegate.awaitTerminated(timeout, unit);
  }

  /**
   * Returns the name of this service. {@link AbstractIdleService} may include the name in debugging
   * output.
   *
   * @since 14.0
   */
  protected String serviceName() {
    return getClass().getSimpleName();
  }
}


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

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.FileWriteMode.APPEND;

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.TreeTraverser;
import com.google.common.graph.SuccessorsFunction;
import com.google.common.graph.Traverser;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Provides utility methods for working with {@linkplain File files}.
 *
 *
{@link java.nio.file.Path} users will find similar utilities in {@link MoreFiles} and the
 * JDK's {@link java.nio.file.Files} class.
 *
 * @author Chris Nokleberg
 * @author Colin Decker
 * @since 1.0
 */
@GwtIncompatible
public final class Files {

  /** Maximum loop count when creating temp directories. */
  private static final int TEMP_DIR_ATTEMPTS = 10000;

  private Files() {}

  /**
   * Returns a buffered reader that reads from a file using the given character set.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#newBufferedReader(java.nio.file.Path, Charset)}.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return the buffered reader
   */
  @Beta
  public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException {
    checkNotNull(file);
    checkNotNull(charset);
    return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
  }

  /**
   * Returns a buffered writer that writes to a file using the given character set.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#newBufferedWriter(java.nio.file.Path, Charset,
   * java.nio.file.OpenOption...)}.
   *
   * @param file the file to write to
   * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return the buffered writer
   */
  @Beta
  public static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException {
    checkNotNull(file);
    checkNotNull(charset);
    return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
  }

  /**
   * Returns a new {@link ByteSource} for reading bytes from the given file.
   *
   * @since 14.0
   */
  public static ByteSource asByteSource(File file) {
    return new FileByteSource(file);
  }

  private static final class FileByteSource extends ByteSource {

    private final File file;

    private FileByteSource(File file) {
      this.file = checkNotNull(file);
    }

    @Override
    public FileInputStream openStream() throws IOException {
      return new FileInputStream(file);
    }

    @Override
    public Optional<Long> sizeIfKnown() {
      if (file.isFile()) {
        return Optional.of(file.length());
      } else {
        return Optional.absent();
      }
    }

    @Override
    public long size() throws IOException {
      if (!file.isFile()) {
        throw new FileNotFoundException(file.toString());
      }
      return file.length();
    }

    @Override
    public byte[] read() throws IOException {
      Closer closer = Closer.create();
      try {
        FileInputStream in = closer.register(openStream());
        return ByteStreams.toByteArray(in, in.getChannel().size());
      } catch (Throwable e) {
        throw closer.rethrow(e);
      } finally {
        closer.close();
      }
    }

    @Override
    public String toString() {
      return "Files.asByteSource(" + file + ")";
    }
  }

  /**
   * Returns a new {@link ByteSink} for writing bytes to the given file. The given {@code modes}
   * control how the file is opened for writing. When no mode is provided, the file will be
   * truncated before writing. When the {@link FileWriteMode#APPEND APPEND} mode is provided, writes
   * will append to the end of the file without truncating it.
   *
   * @since 14.0
   */
  public static ByteSink asByteSink(File file, FileWriteMode... modes) {
    return new FileByteSink(file, modes);
  }

  private static final class FileByteSink extends ByteSink {

    private final File file;
    private final ImmutableSet<FileWriteMode> modes;

    private FileByteSink(File file, FileWriteMode... modes) {
      this.file = checkNotNull(file);
      this.modes = ImmutableSet.copyOf(modes);
    }

    @Override
    public FileOutputStream openStream() throws IOException {
      return new FileOutputStream(file, modes.contains(APPEND));
    }

    @Override
    public String toString() {
      return "Files.asByteSink(" + file + ", " + modes + ")";
    }
  }

  /**
   * Returns a new {@link CharSource} for reading character data from the given file using the given
   * character set.
   *
   * @since 14.0
   */
  public static CharSource asCharSource(File file, Charset charset) {
    return asByteSource(file).asCharSource(charset);
  }

  /**
   * Returns a new {@link CharSink} for writing character data to the given file using the given
   * character set. The given {@code modes} control how the file is opened for writing. When no mode
   * is provided, the file will be truncated before writing. When the {@link FileWriteMode#APPEND
   * APPEND} mode is provided, writes will append to the end of the file without truncating it.
   *
   * @since 14.0
   */
  public static CharSink asCharSink(File file, Charset charset, FileWriteMode... modes) {
    return asByteSink(file, modes).asCharSink(charset);
  }

  /**
   * Reads all bytes from a file into a byte array.
   *
   *
{@link java.nio.file.Path} equivalent: {@link java.nio.file.Files#readAllBytes}.
   *
   * @param file the file to read from
   * @return a byte array containing all the bytes from file
   * @throws IllegalArgumentException if the file is bigger than the largest possible byte array
   *     (2^31 - 1)
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static byte[] toByteArray(File file) throws IOException {
    return asByteSource(file).read();
  }

  /**
   * Reads all characters from a file into a {@link String}, using the given character set.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return a string containing all the characters from the file
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSource(file, charset).read()}. This method is scheduled to be
   *     removed in January 2019.
   */
  @Beta
  @Deprecated
  public static String toString(File file, Charset charset) throws IOException {
    return asCharSource(file, charset).read();
  }

  /**
   * Overwrites a file with the contents of a byte array.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#write(java.nio.file.Path, byte[], java.nio.file.OpenOption...)}.
   *
   * @param from the bytes to write
   * @param to the destination file
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static void write(byte[] from, File to) throws IOException {
    asByteSink(to).write(from);
  }

  /**
   * Writes a character sequence (such as a string) to a file using the given character set.
   *
   * @param from the character sequence to write
   * @param to the destination file
   * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSink(to, charset).write(from)}. This method is scheduled to be
   *     removed in January 2019.
   */
  @Beta
  @Deprecated
  public static void write(CharSequence from, File to, Charset charset) throws IOException {
    asCharSink(to, charset).write(from);
  }

  /**
   * Copies all bytes from a file to an output stream.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#copy(java.nio.file.Path, OutputStream)}.
   *
   * @param from the source file
   * @param to the output stream
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static void copy(File from, OutputStream to) throws IOException {
    asByteSource(from).copyTo(to);
  }

  /**
   * Copies all the bytes from one file to another.
   *
   *
Copying is not an atomic operation - in the case of an I/O error, power loss, process
   * termination, or other problems, {@code to} may not be a complete copy of {@code from}. If you
   * need to guard against those conditions, you should employ other file-level synchronization.
   *
   *
Warning: If {@code to} represents an existing file, that file will be overwritten
   * with the contents of {@code from}. If {@code to} and {@code from} refer to the same
   * file, the contents of that file will be deleted.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}.
   *
   * @param from the source file
   * @param to the destination file
   * @throws IOException if an I/O error occurs
   * @throws IllegalArgumentException if {@code from.equals(to)}
   */
  @Beta
  public static void copy(File from, File to) throws IOException {
    checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
    asByteSource(from).copyTo(asByteSink(to));
  }

  /**
   * Copies all characters from a file to an appendable object, using the given character set.
   *
   * @param from the source file
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @param to the appendable object
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSource(from, charset).copyTo(to)}. This method is scheduled to
   *     be removed in January 2019.
   */
  @Beta
  @Deprecated
  public
  static void copy(File from, Charset charset, Appendable to) throws IOException {
    asCharSource(from, charset).copyTo(to);
  }

  /**
   * Appends a character sequence (such as a string) to a file using the given character set.
   *
   * @param from the character sequence to append
   * @param to the destination file
   * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSink(to, charset, FileWriteMode.APPEND).write(from)}. This
   *     method is scheduled to be removed in January 2019.
   */
  @Beta
  @Deprecated
  public
  static void append(CharSequence from, File to, Charset charset) throws IOException {
    asCharSink(to, charset, FileWriteMode.APPEND).write(from);
  }

  /**
   * Returns true if the given files exist, are not directories, and contain the same bytes.
   *
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static boolean equal(File file1, File file2) throws IOException {
    checkNotNull(file1);
    checkNotNull(file2);
    if (file1 == file2 || file1.equals(file2)) {
      return true;
    }

    /*
     * Some operating systems may return zero as the length for files denoting system-dependent
     * entities such as devices or pipes, in which case we must fall back on comparing the bytes
     * directly.
     */
    long len1 = file1.length();
    long len2 = file2.length();
    if (len1 != 0 && len2 != 0 && len1 != len2) {
      return false;
    }
    return asByteSource(file1).contentEquals(asByteSource(file2));
  }

  /**
   * Atomically creates a new directory somewhere beneath the system's temporary directory (as
   * defined by the {@code java.io.tmpdir} system property), and returns its name.
   *
   *
Use this method instead of {@link File#createTempFile(String, String)} when you wish to
   * create a directory, not a regular file. A common pitfall is to call {@code createTempFile},
   * delete the file and create a directory in its place, but this leads a race condition which can
   * be exploited to create security vulnerabilities, especially when executable files are to be
   * written into the directory.
   *
   *
This method assumes that the temporary volume is writable, has free inodes and free blocks,
   * and that it will not be called thousands of times per second.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#createTempDirectory}.
   *
   * @return the newly-created directory
   * @throws IllegalStateException if the directory could not be created
   */
  @Beta
  public static File createTempDir() {
    File baseDir = new File(System.getProperty("java.io.tmpdir"));
    @SuppressWarnings("GoodTime") // reading system time without TimeSource
    String baseName = System.currentTimeMillis() + "-";

    for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
      File tempDir = new File(baseDir, baseName + counter);
      if (tempDir.mkdir()) {
        return tempDir;
      }
    }
    throw new IllegalStateException(
        "Failed to create directory within "
            + TEMP_DIR_ATTEMPTS
            + " attempts (tried "
            + baseName
            + "0 to "
            + baseName
            + (TEMP_DIR_ATTEMPTS - 1)
            + ')');
  }

  /**
   * Creates an empty file or updates the last updated timestamp on the same as the unix command of
   * the same name.
   *
   * @param file the file to create or update
   * @throws IOException if an I/O error occurs
   */
  @Beta
  @SuppressWarnings("GoodTime") // reading system time without TimeSource
  public static void touch(File file) throws IOException {
    checkNotNull(file);
    if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) {
      throw new IOException("Unable to update modification time of " + file);
    }
  }

  /**
   * Creates any necessary but nonexistent parent directories of the specified file. Note that if
   * this operation fails it may have succeeded in creating some (but not all) of the necessary
   * parent directories.
   *
   * @throws IOException if an I/O error occurs, or if any necessary but nonexistent parent
   *     directories of the specified file could not be created.
   * @since 4.0
   */
  @Beta
  public static void createParentDirs(File file) throws IOException {
    checkNotNull(file);
    File parent = file.getCanonicalFile().getParentFile();
    if (parent == null) {
      /*
       * The given directory is a filesystem root. All zero of its ancestors exist. This doesn't
       * mean that the root itself exists -- consider x:\ on a Windows machine without such a drive
       * -- or even that the caller can create it, but this method makes no such guarantees even for
       * non-root files.
       */
      return;
    }
    parent.mkdirs();
    if (!parent.isDirectory()) {
      throw new IOException("Unable to create parent directories of " + file);
    }
  }

  /**
   * Moves a file from one path to another. This method can rename a file and/or move it to a
   * different directory. In either case {@code to} must be the target path for the file itself; not
   * just the new name for the file or the path to the new parent directory.
   *
   *
{@link java.nio.file.Path} equivalent: {@link java.nio.file.Files#move}.
   *
   * @param from the source file
   * @param to the destination file
   * @throws IOException if an I/O error occurs
   * @throws IllegalArgumentException if {@code from.equals(to)}
   */
  @Beta
  public static void move(File from, File to) throws IOException {
    checkNotNull(from);
    checkNotNull(to);
    checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);

    if (!from.renameTo(to)) {
      copy(from, to);
      if (!from.delete()) {
        if (!to.delete()) {
          throw new IOException("Unable to delete " + to);
        }
        throw new IOException("Unable to delete " + from);
      }
    }
  }

  /**
   * Reads the first line from a file. The line does not include line-termination characters, but
   * does include other leading and trailing whitespace.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return the first line, or null if the file is empty
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSource(file, charset).readFirstLine()}. This method is
   *     scheduled to be removed in January 2019.
   */
  @Beta
  @Deprecated
  public
  static String readFirstLine(File file, Charset charset) throws IOException {
    return asCharSource(file, charset).readFirstLine();
  }

  /**
   * Reads all of the lines from a file. The lines do not include line-termination characters, but
   * do include other leading and trailing whitespace.
   *
   *
This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code
   * Files.asCharSource(file, charset).readLines()}.
   *
   *
{@link java.nio.file.Path} equivalent: {@link
   * java.nio.file.Files#readAllLines(java.nio.file.Path, Charset)}.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @return a mutable {@link List} containing all the lines
   * @throws IOException if an I/O error occurs
   */
  @Beta
  public static List<String> readLines(File file, Charset charset) throws IOException {
    // don't use asCharSource(file, charset).readLines() because that returns
    // an immutable list, which would change the behavior of this method
    return asCharSource(file, charset)
        .readLines(
            new LineProcessor<List<String>>() {
              final List<String> result = Lists.newArrayList();

              @Override
              public boolean processLine(String line) {
                result.add(line);
                return true;
              }

              @Override
              public List<String> getResult() {
                return result;
              }
            });
  }

  /**
   * Streams lines from a {@link File}, stopping when our callback returns false, or we have read
   * all of the lines.
   *
   * @param file the file to read from
   * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
   *     helpful predefined constants
   * @param callback the {@link LineProcessor} to use to handle the lines
   * @return the output of processing the lines
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asCharSource(file, charset).readLines(callback)}. This method is
   *     scheduled to be removed in January 2019.
   */
  @Beta
  @Deprecated
  @CanIgnoreReturnValue // some processors won't return a useful result
  public
  static <T> T readLines(File file, Charset charset, LineProcessor<T> callback) throws IOException {
    return asCharSource(file, charset).readLines(callback);
  }

  /**
   * Process the bytes of a file.
   *
   *
(If this seems too complicated, maybe you're looking for {@link #toByteArray}.)
   *
   * @param file the file to read
   * @param processor the object to which the bytes of the file are passed.
   * @return the result of the byte processor
   * @throws IOException if an I/O error occurs
   * @deprecated Prefer {@code asByteSource(file).read(processor)}. This method is scheduled to be
   *     removed in January 2019.
   */
  @Beta
  @Deprecated
  @CanIgnoreReturnValue // some processors won't return a useful result
  public
  static <T> T readBytes(File file, ByteProcessor<T> processor) throws IOException {
    return asByteSource(file).read(processor);
  }

  /**
   * Computes the hash code of the {@code file} using {@code hashFunction}.
   *
   * @param file the file to read
   * @param hashFunction the hash function to use to hash the data
   * @return the {@link HashCode} of all of the bytes in the file
   * @throws IOException if an I/O error occurs
   * @since 12.0
   * @deprecated Prefer {@code asByteSource(file).hash(hashFunction)}. This method is scheduled to
   *     be removed in January 2019.
   */
  @Beta
  @Deprecated
  public
  static HashCode hash(File file, HashFunction hashFunction) throws IOException {
    return asByteSource(file).hash(hashFunction);
  }

  /**
   * Fully maps a file read-only in to memory as per {@link
   * FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}.
   *
   *
Files are mapped from offset 0 to its length.
   *
   *
This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
   *
   * @param file the file to map
   * @return a read-only buffer reflecting {@code file}
   * @throws FileNotFoundException if the {@code file} does not exist
   * @throws IOException if an I/O error occurs
   * @see FileChannel#map(MapMode, long, long)
   * @since 2.0
   */
  @Beta
  public static MappedByteBuffer map(File file) throws IOException {
    checkNotNull(file);
    return map(file, MapMode.READ_ONLY);
  }

  /**
   * Fully maps a file in to memory as per {@link
   * FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} using the requested {@link
   * MapMode}.
   *
   *
Files are mapped from offset 0 to its length.
   *
   *
This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
   *
   * @param file the file to map
   * @param mode the mode to use when mapping {@code file}
   * @return a buffer reflecting {@code file}
   * @throws FileNotFoundException if the {@code file} does not exist
   * @throws IOException if an I/O error occurs
   * @see FileChannel#map(MapMode, long, long)
   * @since 2.0
   */
  @Beta
  public static MappedByteBuffer map(File file, MapMode mode) throws IOException {
    return mapInternal(file, mode, -1);
  }

  /**
   * Maps a file in to memory as per {@link FileChannel#map(java.nio.channels.FileChannel.MapMode,
   * long, long)} using the requested {@link MapMode}.
   *
   *
Files are mapped from offset 0 to {@code size}.
   *
   *
If the mode is {@link MapMode#READ_WRITE} and the file does not exist, it will be created
   * with the requested {@code size}. Thus this method is useful for creating memory mapped files
   * which do not yet exist.
   *
   *
This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
   *
   * @param file the file to map
   * @param mode the mode to use when mapping {@code file}
   * @return a buffer reflecting {@code file}
   * @throws IOException if an I/O error occurs
   * @see FileChannel#map(MapMode, long, long)
   * @since 2.0
   */
  @Beta
  public static MappedByteBuffer map(File file, MapMode mode, long size) throws IOException {
    checkArgument(size >= 0, "size (%s) may not be negative", size);
    return mapInternal(file, mode, size);
  }

  private static MappedByteBuffer mapInternal(File file, MapMode mode, long size)
      throws IOException {
    checkNotNull(file);
    checkNotNull(mode);

    Closer closer = Closer.create();
    try {
      RandomAccessFile raf =
          closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw"));
      FileChannel channel = closer.register(raf.getChannel());
      return channel.map(mode, 0, size == -1 ? channel.size() : size);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

  /**
   * Returns the lexically cleaned form of the path name, usually (but not always) equivalent
   * to the original. The following heuristics are used:
   *
   *

   *
empty string becomes .
   *
. stays as .
   *
fold out ./
   *
fold out ../ when possible
   *
collapse multiple slashes
   *
delete trailing slashes (unless the path is just "/")
   *

   *
   *
These heuristics do not always match the behavior of the filesystem. In particular, consider
   * the path {@code a/../b}, which {@code simplifyPath} will change to {@code b}. If {@code a} is a
   * symlink to {@code x}, {@code a/../b} may refer to a sibling of {@code x}, rather than the
   * sibling of {@code a} referred to by {@code b}.
   *
   * @since 11.0
   */
  @Beta
  public static String simplifyPath(String pathname) {
    checkNotNull(pathname);
    if (pathname.length() == 0) {
      return ".";
    }

    // split the path apart
    Iterable<String> components = Splitter.on('/').omitEmptyStrings().split(pathname);
    List<String> path = new ArrayList<>();

    // resolve ., .., and //
    for (String component : components) {
      switch (component) {
        case ".":
          continue;
        case "..":
          if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) {
            path.remove(path.size() - 1);
          } else {
            path.add("..");
          }
          break;
        default:
          path.add(component);
          break;
      }
    }

    // put it back together
    String result = Joiner.on('/').join(path);
    if (pathname.charAt(0) == '/') {
      result = "/" + result;
    }

    while (result.startsWith("/../")) {
      result = result.substring(3);
    }
    if (result.equals("/..")) {
      result = "/";
    } else if ("".equals(result)) {
      result = ".";
    }

    return result;
  }

  /**
   * Returns the file extension for
   * the given file name, or the empty string if the file has no extension. The result does not
   * include the '{@code .}'.
   *
   *
Note: This method simply returns everything after the last '{@code .}' in the file's
   * name as determined by {@link File#getName}. It does not account for any filesystem-specific
   * behavior that the {@link File} API does not already account for. For example, on NTFS it will
   * report {@code "txt"} as the extension for the filename {@code "foo.exe:.txt"} even though NTFS
   * will drop the {@code ":.txt"} part of the name when the file is actually created on the
   * filesystem due to NTFS's Alternate Data Streams.
   *
   * @since 11.0
   */
  @Beta
  public static String getFileExtension(String fullName) {
    checkNotNull(fullName);
    String fileName = new File(fullName).getName();
    int dotIndex = fileName.lastIndexOf('.');
    return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
  }

  /**
   * Returns the file name without its file extension or path. This is
   * similar to the {@code basename} unix command. The result does not include the '{@code .}'.
   *
   * @param file The name of the file to trim the extension from. This can be either a fully
   *     qualified file name (including a path) or just a file name.
   * @return The file name without its path or extension.
   * @since 14.0
   */
  @Beta
  public static String getNameWithoutExtension(String file) {
    checkNotNull(file);
    String fileName = new File(file).getName();
    int dotIndex = fileName.lastIndexOf('.');
    return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
  }

  /**
   * Returns a {@link TreeTraverser} instance for {@link File} trees.
   *
   *
Warning: {@code File} provides no support for symbolic links, and as such there is no
   * way to ensure that a symbolic link to a directory is not followed when traversing the tree. In
   * this case, iterables created by this traverser could contain files that are outside of the
   * given directory or even be infinite if there is a symbolic link loop.
   *
   * @since 15.0
   * @deprecated The returned {@link TreeTraverser} type is deprecated. Use the replacement method
   *     {@link #fileTraverser()} instead with the same semantics as this method.
   */
  @Deprecated
  static TreeTraverser<File> fileTreeTraverser() {
    return FILE_TREE_TRAVERSER;
  }

  private static final TreeTraverser<File> FILE_TREE_TRAVERSER =
      new TreeTraverser<File>() {
        @Override
        public Iterable<File> children(File file) {
          return fileTreeChildren(file);
        }

        @Override
        public String toString() {
          return "Files.fileTreeTraverser()";
        }
      };

  /**
   * Returns a {@link Traverser} instance for the file and directory tree. The returned traverser
   * starts from a {@link File} and will return all files and directories it encounters.
   *
   *
Warning: {@code File} provides no support for symbolic links, and as such there is no
   * way to ensure that a symbolic link to a directory is not followed when traversing the tree. In
   * this case, iterables created by this traverser could contain files that are outside of the
   * given directory or even be infinite if there is a symbolic link loop.
   *
   *
If available, consider using {@link MoreFiles#fileTraverser()} instead. It behaves the same
   * except that it doesn't follow symbolic links and returns {@code Path} instances.
   *
   *
If the {@link File} passed to one of the {@link Traverser} methods does not exist or is not
   * a directory, no exception will be thrown and the returned {@link Iterable} will contain a
   * single element: that file.
   *
   *
Example: {@code Files.fileTraverser().depthFirstPreOrder(new File("/"))} may return files
   * with the following paths: {@code ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home",
   * "/home/alice", ...]}
   *
   * @since 23.5
   */
  @Beta
  public static Traverser<File> fileTraverser() {
    return Traverser.forTree(FILE_TREE);
  }

  private static final SuccessorsFunction<File> FILE_TREE =
      new SuccessorsFunction<File>() {
        @Override
        public Iterable<File> successors(File file) {
          return fileTreeChildren(file);
        }
      };

  private static Iterable<File> fileTreeChildren(File file) {
    // check isDirectory() just because it may be faster than listFiles() on a non-directory
    if (file.isDirectory()) {
      File[] files = file.listFiles();
      if (files != null) {
        return Collections.unmodifiableList(Arrays.asList(files));
      }
    }

    return Collections.emptyList();
  }

  /**
   * Returns a predicate that returns the result of {@link File#isDirectory} on input files.
   *
   * @since 15.0
   */
  @Beta
  public static Predicate<File> isDirectory() {
    return FilePredicate.IS_DIRECTORY;
  }

  /**
   * Returns a predicate that returns the result of {@link File#isFile} on input files.
   *
   * @since 15.0
   */
  @Beta
  public static Predicate<File> isFile() {
    return FilePredicate.IS_FILE;
  }

  private enum FilePredicate implements Predicate<File> {
    IS_DIRECTORY {
      @Override
      public boolean apply(File file) {
        return file.isDirectory();
      }

      @Override
      public String toString() {
        return "Files.isDirectory()";
      }
    },

    IS_FILE {
      @Override
      public boolean apply(File file) {
        return file.isFile();
      }

      @Override
      public String toString() {
        return "Files.isFile()";
      }
    }
  }
}


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

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * A {@link BiMap} whose contents will never change, with many other important properties detailed
 * at {@link ImmutableCollection}.
 *
 * @author Jared Levy
 * @since 2.0
 */
@GwtCompatible(serializable = true, emulated = true)
public abstract class ImmutableBiMap<K, V> extends ImmutableBiMapFauxverideShim<K, V>
    implements BiMap<K, V> {

  /**
   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableBiMap} whose keys
   * and values are the result of applying the provided mapping functions to the input elements.
   * Entries appear in the result {@code ImmutableBiMap} in encounter order.
   *
   *
If the mapped keys or values contain duplicates (according to {@link Object#equals(Object)},
   * an {@code IllegalArgumentException} is thrown when the collection operation is performed. (This
   * differs from the {@code Collector} returned by {@link Collectors#toMap(Function, Function)},
   * which throws an {@code IllegalStateException}.)
   *
   * @since 21.0
   */
  public static <T, K, V> Collector<T, ?, ImmutableBiMap<K, V>> toImmutableBiMap(
      Function<? super T, ? extends K> keyFunction,
      Function<? super T, ? extends V> valueFunction) {
    return CollectCollectors.toImmutableBiMap(keyFunction, valueFunction);
  }

  /** Returns the empty bimap. */
  // Casting to any type is safe because the set will never hold any elements.
  @SuppressWarnings("unchecked")
  public static <K, V> ImmutableBiMap<K, V> of() {
    return (ImmutableBiMap<K, V>) RegularImmutableBiMap.EMPTY;
  }

  /** Returns an immutable bimap containing a single entry. */
  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) {
    return new SingletonImmutableBiMap<>(k1, v1);
  }

  /**
   * Returns an immutable map containing the given entries, in order.
   *
   * @throws IllegalArgumentException if duplicate keys or values are added
   */
  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) {
    return RegularImmutableBiMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2));
  }

  /**
   * Returns an immutable map containing the given entries, in order.
   *
   * @throws IllegalArgumentException if duplicate keys or values are added
   */
  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
    return RegularImmutableBiMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3));
  }

  /**
   * Returns an immutable map containing the given entries, in order.
   *
   * @throws IllegalArgumentException if duplicate keys or values are added
   */
  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
    return RegularImmutableBiMap.fromEntries(
        entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4));
  }

  /**
   * Returns an immutable map containing the given entries, in order.
   *
   * @throws IllegalArgumentException if duplicate keys or values are added
   */
  public static <K, V> ImmutableBiMap<K, V> of(
      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
    return RegularImmutableBiMap.fromEntries(
        entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(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<>();
  }

  /**
   * Returns a new builder, expecting the specified number of entries to be added.
   *
   *
If {@code expectedSize} is exactly the number of entries added to the builder before {@link
   * Builder#build} is called, the builder is likely to perform better than an unsized {@link
   * #builder()} would have.
   *
   *
It is not specified if any performance benefits apply if {@code expectedSize} is close to,
   * but not exactly, the number of entries added to the builder.
   *
   * @since 23.1
   */
  @Beta
  public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
    checkNonnegative(expectedSize, "expectedSize");
    return new Builder<>(expectedSize);
  }

  /**
   * A builder for creating immutable bimap instances, especially {@code public static final} bimaps
   * ("constant bimaps"). Example:
   *
   *
{@code
   * static final ImmutableBiMap<String, Integer> WORD_TO_INT =
   *     new ImmutableBiMap.Builder<String, Integer>()
   *         .put("one", 1)
   *         .put("two", 2)
   *         .put("three", 3)
   *         .build();
   * }

   *
   *
For small immutable bimaps, the {@code ImmutableBiMap.of()} methods are even more
   * convenient.
   *
   *
By default, a {@code Builder} will generate bimaps that iterate over entries in the order
   * they were inserted into the builder. For example, in the above example, {@code
   * WORD_TO_INT.entrySet()} is guaranteed to iterate over the entries in the order {@code "one"=1,
   * "two"=2, "three"=3}, and {@code keySet()} and {@code values()} respect the same order. If you
   * want a different order, consider using {@link #orderEntriesByValue(Comparator)}, which changes
   * this builder to sort entries by value.
   *
   *
Builder instances can be reused - it is safe to call {@link #build} multiple times to build
   * multiple bimaps in series. Each bimap is a superset of the bimaps created before it.
   *
   * @since 2.0
   */
  public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> {

    /**
     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
     * ImmutableBiMap#builder}.
     */
    public Builder() {}

    Builder(int size) {
      super(size);
    }

    /**
     * Associates {@code key} with {@code value} in the built bimap. Duplicate keys or values are
     * not allowed, and will cause {@link #build} to fail.
     */
    @CanIgnoreReturnValue
    @Override
    public Builder<K, V> put(K key, V value) {
      super.put(key, value);
      return this;
    }

    /**
     * Adds the given {@code entry} to the bimap. Duplicate keys or values are not allowed, and will
     * cause {@link #build} to fail.
     *
     * @since 19.0
     */
    @CanIgnoreReturnValue
    @Override
    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
      super.put(entry);
      return this;
    }

    /**
     * Associates all of the given map's keys and values in the built bimap. Duplicate keys or
     * values are not allowed, and will cause {@link #build} to fail.
     *
     * @throws NullPointerException if any key or value in {@code map} is null
     */
    @CanIgnoreReturnValue
    @Override
    public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
      super.putAll(map);
      return this;
    }

    /**
     * Adds all of the given entries to the built bimap. Duplicate keys or values are not allowed,
     * and will cause {@link #build} to fail.
     *
     * @throws NullPointerException if any key, value, or entry is null
     * @since 19.0
     */
    @CanIgnoreReturnValue
    @Beta
    @Override
    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
      super.putAll(entries);
      return this;
    }

    /**
     * Configures this {@code Builder} to order entries by value according to the specified
     * comparator.
     *
     *
The sort order is stable, that is, if two entries have values that compare as equivalent,
     * the entry that was inserted first will be first in the built map's iteration order.
     *
     * @throws IllegalStateException if this method was already called
     * @since 19.0
     */
    @CanIgnoreReturnValue
    @Beta
    @Override
    public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
      super.orderEntriesByValue(valueComparator);
      return this;
    }

    @Override
    @CanIgnoreReturnValue
    Builder<K, V> combine(ImmutableMap.Builder<K, V> builder) {
      super.combine(builder);
      return this;
    }

    /**
     * Returns a newly-created immutable bimap. The iteration order of the returned bimap is the
     * order in which entries were inserted into the builder, unless {@link #orderEntriesByValue}
     * was called, in which case entries are sorted by value.
     *
     * @throws IllegalArgumentException if duplicate keys or values were added
     */
    @Override
    public ImmutableBiMap<K, V> build() {
      switch (size) {
        case 0:
          return of();
        case 1:
          return of(entries[0].getKey(), entries[0].getValue());
        default:
          /*
           * If entries is full, or if hash flooding is detected, then this implementation may end
           * up using the entries array directly and writing over the entry objects with
           * non-terminal entries, but this is safe; if this Builder is used further, it will grow
           * the entries array (so it can't affect the original array), and future build() calls
           * will always copy any entry objects that cannot be safely reused.
           */
          if (valueComparator != null) {
            if (entriesUsed) {
              entries = Arrays.copyOf(entries, size);
            }
            Arrays.sort(
                entries,
                0,
                size,
                Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction()));
          }
          entriesUsed = true;
          return RegularImmutableBiMap.fromEntryArray(size, entries);
      }
    }

    @Override
    @VisibleForTesting
    ImmutableBiMap<K, V> buildJdkBacked() {
      checkState(
          valueComparator == null,
          "buildJdkBacked is for tests only, doesn't support orderEntriesByValue");
      switch (size) {
        case 0:
          return of();
        case 1:
          return of(entries[0].getKey(), entries[0].getValue());
        default:
          entriesUsed = true;
          return RegularImmutableBiMap.fromEntryArray(size, entries);
      }
    }
  }

  /**
   * Returns an immutable bimap containing the same entries as {@code map}. If {@code map} somehow
   * contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose
   * comparator is not consistent with equals), the results of this method are undefined.
   *
   *
The returned {@code BiMap} iterates over entries in the same order as the {@code entrySet}
   * of the original map.
   *
   *
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 IllegalArgumentException if two keys have the same value or two values have the same
   *     key
   * @throws NullPointerException if any key or value in {@code map} is null
   */
  public static <K, V> ImmutableBiMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
    if (map instanceof ImmutableBiMap) {
      @SuppressWarnings("unchecked") // safe since map is not writable
      ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map;
      // TODO(lowasser): if we need to make a copy of a BiMap because the
      // forward map is a view, don't make a copy of the non-view delegate map
      if (!bimap.isPartialView()) {
        return bimap;
      }
    }
    return copyOf(map.entrySet());
  }

  /**
   * Returns an immutable bimap containing the given entries. The returned bimap iterates over
   * entries in the same order as the original iterable.
   *
   * @throws IllegalArgumentException if two keys have the same value or two values have the same
   *     key
   * @throws NullPointerException if any key, value, or entry is null
   * @since 19.0
   */
  @Beta
  public static <K, V> ImmutableBiMap<K, V> copyOf(
      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
    @SuppressWarnings("unchecked") // we'll only be using getKey and getValue, which are covariant
    Entry<K, V>[] entryArray = (Entry<K, V>[]) Iterables.toArray(entries, EMPTY_ENTRY_ARRAY);
    switch (entryArray.length) {
      case 0:
        return of();
      case 1:
        Entry<K, V> entry = entryArray[0];
        return of(entry.getKey(), entry.getValue());
      default:
        /*
         * The current implementation will end up using entryArray directly, though it will write
         * over the (arbitrary, potentially mutable) Entry objects actually stored in entryArray.
         */
        return RegularImmutableBiMap.fromEntries(entryArray);
    }
  }

  ImmutableBiMap() {}

  /**
   * {@inheritDoc}
   *
   *
The inverse of an {@code ImmutableBiMap} is another {@code ImmutableBiMap}.
   */
  @Override
  public abstract ImmutableBiMap<V, K> inverse();

  /**
   * Returns an immutable set of the values in this map, in the same order they appear in {@link
   * #entrySet}.
   */
  @Override
  public ImmutableSet<V> values() {
    return inverse().keySet();
  }

  @Override
  final ImmutableSet<V> createValues() {
    throw new AssertionError("should never be called");
  }

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

  /**
   * Serialized type for all ImmutableBiMap instances. It captures the logical contents and they are
   * reconstructed using public factory methods. This ensures that the implementation types remain
   * as implementation details.
   *
   *
Since the bimap is immutable, ImmutableBiMap doesn't require special logic for keeping the
   * bimap and its inverse in sync during serialization, the way AbstractBiMap does.
   */
  private static class SerializedForm extends ImmutableMap.SerializedForm {
    SerializedForm(ImmutableBiMap<?, ?> bimap) {
      super(bimap);
    }

    @Override
    Object readResolve() {
      Builder<Object, Object> builder = new Builder<>();
      return createMap(builder);
    }

    private static final long serialVersionUID = 0;
  }

  @Override
  Object writeReplace() {
    return new SerializedForm(this);
  }
}


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

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkState;
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.VisibleForTesting;
import com.google.common.math.IntMath;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.Weak;
import com.google.j2objc.annotations.WeakOuter;
import java.util.AbstractQueue;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A double-ended priority queue, which provides constant-time access to both its least element and
 * its greatest element, as determined by the queue's specified comparator. If no comparator is
 * given at creation time, the natural order of elements is used. If no maximum size is given at
 * creation time, the queue is unbounded.
 *
 *
Usage example:
 *
 *
{@code
 * MinMaxPriorityQueue<User> users = MinMaxPriorityQueue.orderedBy(userComparator)
 *     .maximumSize(1000)
 *     .create();
 * }

 *
 *
As a {@link Queue} it functions exactly as a {@link PriorityQueue}: its head element -- the
 * implicit target of the methods {@link #peek()}, {@link #poll()} and {@link #remove()} -- is
 * defined as the least element in the queue according to the queue's comparator. But unlike
 * a regular priority queue, the methods {@link #peekLast}, {@link #pollLast} and {@link
 * #removeLast} are also provided, to act on the greatest element in the queue instead.
 *
 *
A min-max priority queue can be configured with a maximum size. If so, each time the size of
 * the queue exceeds that value, the queue automatically removes its greatest element according to
 * its comparator (which might be the element that was just added). This is different from
 * conventional bounded queues, which either block or reject new elements when full.
 *
 *
This implementation is based on the min-max heap developed by Atkinson, et al.
 * Unlike many other double-ended priority queues, it stores elements in a single array, as compact
 * as the traditional heap data structure used in {@link PriorityQueue}.
 *
 *
This class is not thread-safe, and does not accept null elements.
 *
 *
Performance notes:
 *
 *

 *
If you only access one end of the queue, and do use a maximum size, this class will perform
 *       significantly worse than a {@code PriorityQueue} with manual eviction above the maximum
 *       size. In many cases {@link Ordering#leastOf} may work for your use case with significantly
 *       improved (and asymptotically superior) performance.
 *
The retrieval operations {@link #peek}, {@link #peekFirst}, {@link #peekLast}, {@link
 *       #element}, and {@link #size} are constant-time.
 *
The enqueuing and dequeuing operations ({@link #offer}, {@link #add}, and all the forms of
 *       {@link #poll} and {@link #remove()}) run in {@code O(log n) time}.
 *
The {@link #remove(Object)} and {@link #contains} operations require linear ({@code O(n)})
 *       time.
 *
If you only access one end of the queue, and don't use a maximum size, this class is
 *       functionally equivalent to {@link PriorityQueue}, but significantly slower.
 *

 *
 * @author Sverre Sundsdal
 * @author Torbjorn Gannholm
 * @since 8.0
 */
@Beta
@GwtCompatible
public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {

  /**
   * Creates a new min-max priority queue with default settings: natural order, no maximum size, no
   * initial contents, and an initial expected size of 11.
   */
  public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create() {
    return new Builder<Comparable>(Ordering.natural()).create();
  }

  /**
   * Creates a new min-max priority queue using natural order, no maximum size, and initially
   * containing the given elements.
   */
  public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create(
      Iterable<? extends E> initialContents) {
    return new Builder<E>(Ordering.<E>natural()).create(initialContents);
  }

  /**
   * Creates and returns a new builder, configured to build {@code MinMaxPriorityQueue} instances
   * that use {@code comparator} to determine the least and greatest elements.
   */
  public static  Builder orderedBy(Comparator comparator) {
    return new Builder(comparator);
  }

  /**
   * Creates and returns a new builder, configured to build {@code MinMaxPriorityQueue} instances
   * sized appropriately to hold {@code expectedSize} elements.
   */
  public static Builder<Comparable> expectedSize(int expectedSize) {
    return new Builder<Comparable>(Ordering.natural()).expectedSize(expectedSize);
  }

  /**
   * Creates and returns a new builder, configured to build {@code MinMaxPriorityQueue} instances
   * that are limited to {@code maximumSize} elements. Each time a queue grows beyond this bound, it
   * immediately removes its greatest element (according to its comparator), which might be the
   * element that was just added.
   */
  public static Builder<Comparable> maximumSize(int maximumSize) {
    return new Builder<Comparable>(Ordering.natural()).maximumSize(maximumSize);
  }

  /**
   * The builder class used in creation of min-max priority queues. Instead of constructing one
   * directly, use {@link MinMaxPriorityQueue#orderedBy(Comparator)}, {@link
   * MinMaxPriorityQueue#expectedSize(int)} or {@link MinMaxPriorityQueue#maximumSize(int)}.
   *
   * @param  the upper bound on the eventual type that can be produced by this builder (for
   *     example, a {@code Builder<Number>} can produce a {@code Queue<Number>} or {@code
   *     Queue<Integer>} but not a {@code Queue<Object>}).
   * @since 8.0
   */
  @Beta
  public static final class Builder {
    /*
     * TODO(kevinb): when the dust settles, see if we still need this or can
     * just default to DEFAULT_CAPACITY.
     */
    private static final int UNSET_EXPECTED_SIZE = -1;

    private final Comparator comparator;
    private int expectedSize = UNSET_EXPECTED_SIZE;
    private int maximumSize = Integer.MAX_VALUE;

    private Builder(Comparator comparator) {
      this.comparator = checkNotNull(comparator);
    }

    /**
     * Configures this builder to build min-max priority queues with an initial expected size of
     * {@code expectedSize}.
     */
    @CanIgnoreReturnValue
    public Builder expectedSize(int expectedSize) {
      checkArgument(expectedSize >= 0);
      this.expectedSize = expectedSize;
      return this;
    }

    /**
     * Configures this builder to build {@code MinMaxPriorityQueue} instances that are limited to
     * {@code maximumSize} elements. Each time a queue grows beyond this bound, it immediately
     * removes its greatest element (according to its comparator), which might be the element that
     * was just added.
     */
    @CanIgnoreReturnValue
    public Builder maximumSize(int maximumSize) {
      checkArgument(maximumSize > 0);
      this.maximumSize = maximumSize;
      return this;
    }

    /**
     * Builds a new min-max priority queue using the previously specified options, and having no
     * initial contents.
     */
    public <T extends B> MinMaxPriorityQueue<T> create() {
      return create(Collections.<T>emptySet());
    }

    /**
     * Builds a new min-max priority queue using the previously specified options, and having the
     * given initial elements.
     */
    public <T extends B> MinMaxPriorityQueue<T> create(Iterable<? extends T> initialContents) {
      MinMaxPriorityQueue<T> queue =
          new MinMaxPriorityQueue<T>(
              this, initialQueueSize(expectedSize, maximumSize, initialContents));
      for (T element : initialContents) {
        queue.offer(element);
      }
      return queue;
    }

    @SuppressWarnings("unchecked") // safe "contravariant cast"
    private <T extends B> Ordering<T> ordering() {
      return Ordering.from((Comparator<T>) comparator);
    }
  }

  private final Heap minHeap;
  private final Heap maxHeap;
  @VisibleForTesting final int maximumSize;
  private Object[] queue;
  private int size;
  private int modCount;

  private MinMaxPriorityQueue(Builder<? super E> builder, int queueSize) {
    Ordering<E> ordering = builder.ordering();
    this.minHeap = new Heap(ordering);
    this.maxHeap = new Heap(ordering.reverse());
    minHeap.otherHeap = maxHeap;
    maxHeap.otherHeap = minHeap;

    this.maximumSize = builder.maximumSize;
    // TODO(kevinb): pad?
    this.queue = new Object[queueSize];
  }

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

  /**
   * Adds the given element to this queue. If this queue has a maximum size, after adding {@code
   * element} the queue will automatically evict its greatest element (according to its comparator),
   * which may be {@code element} itself.
   *
   * @return {@code true} always
   */
  @CanIgnoreReturnValue
  @Override
  public boolean add(E element) {
    offer(element);
    return true;
  }

  @CanIgnoreReturnValue
  @Override
  public boolean addAll(Collection<? extends E> newElements) {
    boolean modified = false;
    for (E element : newElements) {
      offer(element);
      modified = true;
    }
    return modified;
  }

  /**
   * Adds the given element to this queue. If this queue has a maximum size, after adding {@code
   * element} the queue will automatically evict its greatest element (according to its comparator),
   * which may be {@code element} itself.
   */
  @CanIgnoreReturnValue
  @Override
  public boolean offer(E element) {
    checkNotNull(element);
    modCount++;
    int insertIndex = size++;

    growIfNeeded();

    // Adds the element to the end of the heap and bubbles it up to the correct
    // position.
    heapForIndex(insertIndex).bubbleUp(insertIndex, element);
    return size <= maximumSize || pollLast() != element;
  }

  @CanIgnoreReturnValue
  @Override
  public E poll() {
    return isEmpty() ? null : removeAndGet(0);
  }

  @SuppressWarnings("unchecked") // we must carefully only allow Es to get in
  E elementData(int index) {
    return (E) queue[index];
  }

  @Override
  public E peek() {
    return isEmpty() ? null : elementData(0);
  }

  /** Returns the index of the max element. */
  private int getMaxElementIndex() {
    switch (size) {
      case 1:
        return 0; // The lone element in the queue is the maximum.
      case 2:
        return 1; // The lone element in the maxHeap is the maximum.
      default:
        // The max element must sit on the first level of the maxHeap. It is
        // actually the *lesser* of the two from the maxHeap's perspective.
        return (maxHeap.compareElements(1, 2) <= 0) ? 1 : 2;
    }
  }

  /**
   * Removes and returns the least element of this queue, or returns {@code null} if the queue is
   * empty.
   */
  @CanIgnoreReturnValue
  public E pollFirst() {
    return poll();
  }

  /**
   * Removes and returns the least element of this queue.
   *
   * @throws NoSuchElementException if the queue is empty
   */
  @CanIgnoreReturnValue
  public E removeFirst() {
    return remove();
  }

  /**
   * Retrieves, but does not remove, the least element of this queue, or returns {@code null} if the
   * queue is empty.
   */
  public E peekFirst() {
    return peek();
  }

  /**
   * Removes and returns the greatest element of this queue, or returns {@code null} if the queue is
   * empty.
   */
  @CanIgnoreReturnValue
  public E pollLast() {
    return isEmpty() ? null : removeAndGet(getMaxElementIndex());
  }

  /**
   * Removes and returns the greatest element of this queue.
   *
   * @throws NoSuchElementException if the queue is empty
   */
  @CanIgnoreReturnValue
  public E removeLast() {
    if (isEmpty()) {
      throw new NoSuchElementException();
    }
    return removeAndGet(getMaxElementIndex());
  }

  /**
   * Retrieves, but does not remove, the greatest element of this queue, or returns {@code null} if
   * the queue is empty.
   */
  public E peekLast() {
    return isEmpty() ? null : elementData(getMaxElementIndex());
  }

  /**
   * Removes the element at position {@code index}.
   *
   *
Normally this method leaves the elements at up to {@code index - 1}, inclusive, untouched.
   * Under these circumstances, it returns {@code null}.
   *
   *
Occasionally, in order to maintain the heap invariant, it must swap a later element of the
   * list with one before {@code index}. Under these circumstances it returns a pair of elements as
   * a {@link MoveDesc}. The first one is the element that was previously at the end of the heap and
   * is now at some position before {@code index}. The second element is the one that was swapped
   * down to replace the element at {@code index}. This fact is used by iterator.remove so as to
   * visit elements during a traversal once and only once.
   */
  @VisibleForTesting
  @CanIgnoreReturnValue
  MoveDesc<E> removeAt(int index) {
    checkPositionIndex(index, size);
    modCount++;
    size--;
    if (size == index) {
      queue[size] = null;
      return null;
    }
    E actualLastElement = elementData(size);
    int lastElementAt = heapForIndex(size).swapWithConceptuallyLastElement(actualLastElement);
    if (lastElementAt == index) {
      // 'actualLastElement' is now at 'lastElementAt', and the element that was at 'lastElementAt'
      // is now at the end of queue. If that's the element we wanted to remove in the first place,
      // don't try to (incorrectly) trickle it. Instead, just delete it and we're done.
      queue[size] = null;
      return null;
    }
    E toTrickle = elementData(size);
    queue[size] = null;
    MoveDesc<E> changes = fillHole(index, toTrickle);
    if (lastElementAt < index) {
      // Last element is moved to before index, swapped with trickled element.
      if (changes == null) {
        // The trickled element is still after index.
        return new MoveDesc<E>(actualLastElement, toTrickle);
      } else {
        // The trickled element is back before index, but the replaced element
        // has now been moved after index.
        return new MoveDesc<E>(actualLastElement, changes.replaced);
      }
    }
    // Trickled element was after index to begin with, no adjustment needed.
    return changes;
  }

  private MoveDesc<E> fillHole(int index, E toTrickle) {
    Heap heap = heapForIndex(index);
    // We consider elementData(index) a "hole", and we want to fill it
    // with the last element of the heap, toTrickle.
    // Since the last element of the heap is from the bottom level, we
    // optimistically fill index position with elements from lower levels,
    // moving the hole down. In most cases this reduces the number of
    // comparisons with toTrickle, but in some cases we will need to bubble it
    // all the way up again.
    int vacated = heap.fillHoleAt(index);
    // Try to see if toTrickle can be bubbled up min levels.
    int bubbledTo = heap.bubbleUpAlternatingLevels(vacated, toTrickle);
    if (bubbledTo == vacated) {
      // Could not bubble toTrickle up min levels, try moving
      // it from min level to max level (or max to min level) and bubble up
      // there.
      return heap.tryCrossOverAndBubbleUp(index, vacated, toTrickle);
    } else {
      return (bubbledTo < index) ? new MoveDesc<E>(toTrickle, elementData(index)) : null;
    }
  }

  // Returned from removeAt() to iterator.remove()
  static class MoveDesc<E> {
    final E toTrickle;
    final E replaced;

    MoveDesc(E toTrickle, E replaced) {
      this.toTrickle = toTrickle;
      this.replaced = replaced;
    }
  }

  /** Removes and returns the value at {@code index}. */
  private E removeAndGet(int index) {
    E value = elementData(index);
    removeAt(index);
    return value;
  }

  private Heap heapForIndex(int i) {
    return isEvenLevel(i) ? minHeap : maxHeap;
  }

  private static final int EVEN_POWERS_OF_TWO = 0x55555555;
  private static final int ODD_POWERS_OF_TWO = 0xaaaaaaaa;

  @VisibleForTesting
  static boolean isEvenLevel(int index) {
    int oneBased = ~~(index + 1); // for GWT
    checkState(oneBased > 0, "negative index");
    return (oneBased & EVEN_POWERS_OF_TWO) > (oneBased & ODD_POWERS_OF_TWO);
  }

  /**
   * Returns {@code true} if the MinMax heap structure holds. This is only used in testing.
   *
   *
TODO(kevinb): move to the test class?
   */
  @VisibleForTesting
  boolean isIntact() {
    for (int i = 1; i < size; i++) {
      if (!heapForIndex(i).verifyIndex(i)) {
        return false;
      }
    }
    return true;
  }

  /**
   * Each instance of MinMaxPriortyQueue encapsulates two instances of Heap: a min-heap and a
   * max-heap. Conceptually, these might each have their own array for storage, but for efficiency's
   * sake they are stored interleaved on alternate heap levels in the same array (MMPQ.queue).
   */
  @WeakOuter
  private class Heap {
    final Ordering<E> ordering;
    @MonotonicNonNull @Weak Heap otherHeap;

    Heap(Ordering<E> ordering) {
      this.ordering = ordering;
    }

    int compareElements(int a, int b) {
      return ordering.compare(elementData(a), elementData(b));
    }

    /**
     * Tries to move {@code toTrickle} from a min to a max level and bubble up there. If it moved
     * before {@code removeIndex} this method returns a pair as described in {@link #removeAt}.
     */
    MoveDesc<E> tryCrossOverAndBubbleUp(int removeIndex, int vacated, E toTrickle) {
      int crossOver = crossOver(vacated, toTrickle);
      if (crossOver == vacated) {
        return null;
      }
      // Successfully crossed over from min to max.
      // Bubble up max levels.
      E parent;
      // If toTrickle is moved up to a parent of removeIndex, the parent is
      // placed in removeIndex position. We must return that to the iterator so
      // that it knows to skip it.
      if (crossOver < removeIndex) {
        // We crossed over to the parent level in crossOver, so the parent
        // has already been moved.
        parent = elementData(removeIndex);
      } else {
        parent = elementData(getParentIndex(removeIndex));
      }
      // bubble it up the opposite heap
      if (otherHeap.bubbleUpAlternatingLevels(crossOver, toTrickle) < removeIndex) {
        return new MoveDesc<E>(toTrickle, parent);
      } else {
        return null;
      }
    }

    /** Bubbles a value from {@code index} up the appropriate heap if required. */
    void bubbleUp(int index, E x) {
      int crossOver = crossOverUp(index, x);

      Heap heap;
      if (crossOver == index) {
        heap = this;
      } else {
        index = crossOver;
        heap = otherHeap;
      }
      heap.bubbleUpAlternatingLevels(index, x);
    }

    /**
     * Bubbles a value from {@code index} up the levels of this heap, and returns the index the
     * element ended up at.
     */
    @CanIgnoreReturnValue
    int bubbleUpAlternatingLevels(int index, E x) {
      while (index > 2) {
        int grandParentIndex = getGrandparentIndex(index);
        E e = elementData(grandParentIndex);
        if (ordering.compare(e, x) <= 0) {
          break;
        }
        queue[index] = e;
        index = grandParentIndex;
      }
      queue[index] = x;
      return index;
    }

    /**
     * Returns the index of minimum value between {@code index} and {@code index + len}, or {@code
     * -1} if {@code index} is greater than {@code size}.
     */
    int findMin(int index, int len) {
      if (index >= size) {
        return -1;
      }
      checkState(index > 0);
      int limit = Math.min(index, size - len) + len;
      int minIndex = index;
      for (int i = index + 1; i < limit; i++) {
        if (compareElements(i, minIndex) < 0) {
          minIndex = i;
        }
      }
      return minIndex;
    }

    /** Returns the minimum child or {@code -1} if no child exists. */
    int findMinChild(int index) {
      return findMin(getLeftChildIndex(index), 2);
    }

    /** Returns the minimum grand child or -1 if no grand child exists. */
    int findMinGrandChild(int index) {
      int leftChildIndex = getLeftChildIndex(index);
      if (leftChildIndex < 0) {
        return -1;
      }
      return findMin(getLeftChildIndex(leftChildIndex), 4);
    }

    /**
     * Moves an element one level up from a min level to a max level (or vice versa). Returns the
     * new position of the element.
     */
    int crossOverUp(int index, E x) {
      if (index == 0) {
        queue[0] = x;
        return 0;
      }
      int parentIndex = getParentIndex(index);
      E parentElement = elementData(parentIndex);
      if (parentIndex != 0) {
        // This is a guard for the case of the childless uncle.
        // Since the end of the array is actually the middle of the heap,
        // a smaller childless uncle can become a child of x when we
        // bubble up alternate levels, violating the invariant.
        int grandparentIndex = getParentIndex(parentIndex);
        int uncleIndex = getRightChildIndex(grandparentIndex);
        if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) {
          E uncleElement = elementData(uncleIndex);
          if (ordering.compare(uncleElement, parentElement) < 0) {
            parentIndex = uncleIndex;
            parentElement = uncleElement;
          }
        }
      }
      if (ordering.compare(parentElement, x) < 0) {
        queue[index] = parentElement;
        queue[parentIndex] = x;
        return parentIndex;
      }
      queue[index] = x;
      return index;
    }

    /**
     * Swap {@code actualLastElement} with the conceptually correct last element of the heap.
     * Returns the index that {@code actualLastElement} now resides in.
     *
     *
Since the last element of the array is actually in the middle of the sorted structure, a
     * childless uncle node could be smaller, which would corrupt the invariant if this element
     * becomes the new parent of the uncle. In that case, we first switch the last element with its
     * uncle, before returning.
     */
    int swapWithConceptuallyLastElement(E actualLastElement) {
      int parentIndex = getParentIndex(size);
      if (parentIndex != 0) {
        int grandparentIndex = getParentIndex(parentIndex);
        int uncleIndex = getRightChildIndex(grandparentIndex);
        if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) {
          E uncleElement = elementData(uncleIndex);
          if (ordering.compare(uncleElement, actualLastElement) < 0) {
            queue[uncleIndex] = actualLastElement;
            queue[size] = uncleElement;
            return uncleIndex;
          }
        }
      }
      return size;
    }

    /**
     * Crosses an element over to the opposite heap by moving it one level down (or up if there are
     * no elements below it).
     *
     *
Returns the new position of the element.
     */
    int crossOver(int index, E x) {
      int minChildIndex = findMinChild(index);
      // TODO(kevinb): split the && into two if's and move crossOverUp so it's
      // only called when there's no child.
      if ((minChildIndex > 0) && (ordering.compare(elementData(minChildIndex), x) < 0)) {
        queue[index] = elementData(minChildIndex);
        queue[minChildIndex] = x;
        return minChildIndex;
      }
      return crossOverUp(index, x);
    }

    /**
     * Fills the hole at {@code index} by moving in the least of its grandchildren to this position,
     * then recursively filling the new hole created.
     *
     * @return the position of the new hole (where the lowest grandchild moved from, that had no
     *     grandchild to replace it)
     */
    int fillHoleAt(int index) {
      int minGrandchildIndex;
      while ((minGrandchildIndex = findMinGrandChild(index)) > 0) {
        queue[index] = elementData(minGrandchildIndex);
        index = minGrandchildIndex;
      }
      return index;
    }

    private boolean verifyIndex(int i) {
      if ((getLeftChildIndex(i) < size) && (compareElements(i, getLeftChildIndex(i)) > 0)) {
        return false;
      }
      if ((getRightChildIndex(i) < size) && (compareElements(i, getRightChildIndex(i)) > 0)) {
        return false;
      }
      if ((i > 0) && (compareElements(i, getParentIndex(i)) > 0)) {
        return false;
      }
      if ((i > 2) && (compareElements(getGrandparentIndex(i), i) > 0)) {
        return false;
      }
      return true;
    }

    // These would be static if inner classes could have static members.

    private int getLeftChildIndex(int i) {
      return i * 2 + 1;
    }

    private int getRightChildIndex(int i) {
      return i * 2 + 2;
    }

    private int getParentIndex(int i) {
      return (i - 1) / 2;
    }

    private int getGrandparentIndex(int i) {
      return getParentIndex(getParentIndex(i)); // (i - 3) / 4
    }
  }

  /**
   * Iterates the elements of the queue in no particular order.
   *
   *
If the underlying queue is modified during iteration an exception will be thrown.
   */
  private class QueueIterator implements Iterator<E> {
    private int cursor = -1;
    private int nextCursor = -1;
    private int expectedModCount = modCount;
    // The same element is not allowed in both forgetMeNot and skipMe, but duplicates are allowed in
    // either of them, up to the same multiplicity as the queue.
    @MonotonicNonNull private Queue<E> forgetMeNot;
    @MonotonicNonNull private List<E> skipMe;
    private @Nullable E lastFromForgetMeNot;
    private boolean canRemove;

    @Override
    public boolean hasNext() {
      checkModCount();
      nextNotInSkipMe(cursor + 1);
      return (nextCursor < size()) || ((forgetMeNot != null) && !forgetMeNot.isEmpty());
    }

    @Override
    public E next() {
      checkModCount();
      nextNotInSkipMe(cursor + 1);
      if (nextCursor < size()) {
        cursor = nextCursor;
        canRemove = true;
        return elementData(cursor);
      } else if (forgetMeNot != null) {
        cursor = size();
        lastFromForgetMeNot = forgetMeNot.poll();
        if (lastFromForgetMeNot != null) {
          canRemove = true;
          return lastFromForgetMeNot;
        }
      }
      throw new NoSuchElementException("iterator moved past last element in queue.");
    }

    @Override
    public void remove() {
      checkRemove(canRemove);
      checkModCount();
      canRemove = false;
      expectedModCount++;
      if (cursor < size()) {
        MoveDesc<E> moved = removeAt(cursor);
        if (moved != null) {
          if (forgetMeNot == null) {
            forgetMeNot = new ArrayDeque<E>();
            skipMe = new ArrayList<E>(3);
          }
          if (!foundAndRemovedExactReference(skipMe, moved.toTrickle)) {
            forgetMeNot.add(moved.toTrickle);
          }
          if (!foundAndRemovedExactReference(forgetMeNot, moved.replaced)) {
            skipMe.add(moved.replaced);
          }
        }
        cursor--;
        nextCursor--;
      } else { // we must have set lastFromForgetMeNot in next()
        checkState(removeExact(lastFromForgetMeNot));
        lastFromForgetMeNot = null;
      }
    }

    /** Returns true if an exact reference (==) was found and removed from the supplied iterable. */
    private boolean foundAndRemovedExactReference(Iterable<E> elements, E target) {
      for (Iterator<E> it = elements.iterator(); it.hasNext(); ) {
        E element = it.next();
        if (element == target) {
          it.remove();
          return true;
        }
      }
      return false;
    }

    /** Removes only this exact instance, not others that are equals() */
    private boolean removeExact(Object target) {
      for (int i = 0; i < size; i++) {
        if (queue[i] == target) {
          removeAt(i);
          return true;
        }
      }
      return false;
    }

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

    /**
     * Advances nextCursor to the index of the first element after {@code c} that is not in {@code
     * skipMe} and returns {@code size()} if there is no such element.
     */
    private void nextNotInSkipMe(int c) {
      if (nextCursor < c) {
        if (skipMe != null) {
          while (c < size() && foundAndRemovedExactReference(skipMe, elementData(c))) {
            c++;
          }
        }
        nextCursor = c;
      }
    }
  }

  /**
   * Returns an iterator over the elements contained in this collection, in no particular
   * order.
   *
   *
The iterator is fail-fast: If the MinMaxPriorityQueue is modified at any time after
   * the iterator is created, in any way except through the iterator's own remove method, the
   * iterator will generally throw a {@link ConcurrentModificationException}. Thus, in the face of
   * concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary,
   * non-deterministic behavior at an undetermined time in the future.
   *
   *
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally
   * speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent
   * modification. Fail-fast iterators throw {@code ConcurrentModificationException} on a
   * best-effort basis. Therefore, it would be wrong to write a program that depended on this
   * exception for its correctness: the fail-fast behavior of iterators should be used only to
   * detect bugs.
   *
   * @return an iterator over the elements contained in this collection
   */
  @Override
  public Iterator<E> iterator() {
    return new QueueIterator();
  }

  @Override
  public void clear() {
    for (int i = 0; i < size; i++) {
      queue[i] = null;
    }
    size = 0;
  }

  @Override
  public Object[] toArray() {
    Object[] copyTo = new Object[size];
    System.arraycopy(queue, 0, copyTo, 0, size);
    return copyTo;
  }

  /**
   * Returns the comparator used to order the elements in this queue. Obeys the general contract of
   * {@link PriorityQueue#comparator}, but returns {@link Ordering#natural} instead of {@code null}
   * to indicate natural ordering.
   */
  public Comparator<? super E> comparator() {
    return minHeap.ordering;
  }

  @VisibleForTesting
  int capacity() {
    return queue.length;
  }

  // Size/capacity-related methods

  private static final int DEFAULT_CAPACITY = 11;

  @VisibleForTesting
  static int initialQueueSize(
      int configuredExpectedSize, int maximumSize, Iterable<?> initialContents) {
    // Start with what they said, if they said it, otherwise DEFAULT_CAPACITY
    int result =
        (configuredExpectedSize == Builder.UNSET_EXPECTED_SIZE)
            ? DEFAULT_CAPACITY
            : configuredExpectedSize;

    // Enlarge to contain initial contents
    if (initialContents instanceof Collection) {
      int initialSize = ((Collection<?>) initialContents).size();
      result = Math.max(result, initialSize);
    }

    // Now cap it at maxSize + 1
    return capAtMaximumSize(result, maximumSize);
  }

  private void growIfNeeded() {
    if (size > queue.length) {
      int newCapacity = calculateNewCapacity();
      Object[] newQueue = new Object[newCapacity];
      System.arraycopy(queue, 0, newQueue, 0, queue.length);
      queue = newQueue;
    }
  }

  /** Returns ~2x the old capacity if small; ~1.5x otherwise. */
  private int calculateNewCapacity() {
    int oldCapacity = queue.length;
    int newCapacity =
        (oldCapacity < 64) ? (oldCapacity + 1) * 2 : IntMath.checkedMultiply(oldCapacity / 2, 3);
    return capAtMaximumSize(newCapacity, maximumSize);
  }

  /** There's no reason for the queueSize to ever be more than maxSize + 1 */
  private static int capAtMaximumSize(int queueSize, int maximumSize) {
    return Math.min(queueSize - 1, maximumSize) + 1; // don't overflow
  }
}