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

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

import com.google.common.annotations.GwtCompatible;

/**
 * Static methods pertaining to ASCII characters (those in the range of values {@code 0x00} through
 * {@code 0x7F}), and to strings containing such characters.
 *
 *
ASCII utilities also exist in other classes of this package:
 *
 *

 *
 *
{@link Charsets#US_ASCII} specifies the {@code Charset} of ASCII characters.
 *
{@link CharMatcher#ascii} matches ASCII characters and provides text processing methods
 *       which operate only on the ASCII characters of a string.
 *

 *
 * @author Catherine Berry
 * @author Gregory Kick
 * @since 7.0
 */
@GwtCompatible
public final class Ascii {

  private Ascii() {}

  /* The ASCII control characters, per RFC 20. */
  /**
   * Null ('\0'): The all-zeros character which may serve to accomplish time fill and media fill.
   * Normally used as a C string terminator.
   *
   *
Although RFC 20 names this as "Null", note that it is distinct from the C/C++ "NULL"
   * pointer.
   *
   * @since 8.0
   */
  public static final byte NUL = 0;

  /**
   * Start of Heading: A communication control character used at the beginning of a sequence of
   * characters which constitute a machine-sensible address or routing information. Such a sequence
   * is referred to as the "heading." An STX character has the effect of terminating a heading.
   *
   * @since 8.0
   */
  public static final byte SOH = 1;

  /**
   * Start of Text: A communication control character which precedes a sequence of characters that
   * is to be treated as an entity and entirely transmitted through to the ultimate destination.
   * Such a sequence is referred to as "text." STX may be used to terminate a sequence of characters
   * started by SOH.
   *
   * @since 8.0
   */
  public static final byte STX = 2;

  /**
   * End of Text: A communication control character used to terminate a sequence of characters
   * started with STX and transmitted as an entity.
   *
   * @since 8.0
   */
  public static final byte ETX = 3;

  /**
   * End of Transmission: A communication control character used to indicate the conclusion of a
   * transmission, which may have contained one or more texts and any associated headings.
   *
   * @since 8.0
   */
  public static final byte EOT = 4;

  /**
   * Enquiry: A communication control character used in data communication systems as a request for
   * a response from a remote station. It may be used as a "Who Are You" (WRU) to obtain
   * identification, or may be used to obtain station status, or both.
   *
   * @since 8.0
   */
  public static final byte ENQ = 5;

  /**
   * Acknowledge: A communication control character transmitted by a receiver as an affirmative
   * response to a sender.
   *
   * @since 8.0
   */
  public static final byte ACK = 6;

  /**
   * Bell ('\a'): A character for use when there is a need to call for human attention. It may
   * control alarm or attention devices.
   *
   * @since 8.0
   */
  public static final byte BEL = 7;

  /**
   * Backspace ('\b'): A format effector which controls the movement of the printing position one
   * printing space backward on the same printing line. (Applicable also to display devices.)
   *
   * @since 8.0
   */
  public static final byte BS = 8;

  /**
   * Horizontal Tabulation ('\t'): A format effector which controls the movement of the printing
   * position to the next in a series of predetermined positions along the printing line.
   * (Applicable also to display devices and the skip function on punched cards.)
   *
   * @since 8.0
   */
  public static final byte HT = 9;

  /**
   * Line Feed ('\n'): A format effector which controls the movement of the printing position to the
   * next printing line. (Applicable also to display devices.) Where appropriate, this character may
   * have the meaning "New Line" (NL), a format effector which controls the movement of the printing
   * point to the first printing position on the next printing line. Use of this convention requires
   * agreement between sender and recipient of data.
   *
   * @since 8.0
   */
  public static final byte LF = 10;

  /**
   * Alternate name for {@link #LF}. ({@code LF} is preferred.)
   *
   * @since 8.0
   */
  public static final byte NL = 10;

  /**
   * Vertical Tabulation ('\v'): A format effector which controls the movement of the printing
   * position to the next in a series of predetermined printing lines. (Applicable also to display
   * devices.)
   *
   * @since 8.0
   */
  public static final byte VT = 11;

  /**
   * Form Feed ('\f'): A format effector which controls the movement of the printing position to the
   * first pre-determined printing line on the next form or page. (Applicable also to display
   * devices.)
   *
   * @since 8.0
   */
  public static final byte FF = 12;

  /**
   * Carriage Return ('\r'): A format effector which controls the movement of the printing position
   * to the first printing position on the same printing line. (Applicable also to display devices.)
   *
   * @since 8.0
   */
  public static final byte CR = 13;

  /**
   * Shift Out: A control character indicating that the code combinations which follow shall be
   * interpreted as outside of the character set of the standard code table until a Shift In
   * character is reached.
   *
   * @since 8.0
   */
  public static final byte SO = 14;

  /**
   * Shift In: A control character indicating that the code combinations which follow shall be
   * interpreted according to the standard code table.
   *
   * @since 8.0
   */
  public static final byte SI = 15;

  /**
   * Data Link Escape: A communication control character which will change the meaning of a limited
   * number of contiguously following characters. It is used exclusively to provide supplementary
   * controls in data communication networks.
   *
   * @since 8.0
   */
  public static final byte DLE = 16;

  /**
   * Device Control 1. Characters for the control of ancillary devices associated with data
   * processing or telecommunication systems, more especially switching devices "on" or "off." (If a
   * single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the
   * preferred assignment.)
   *
   * @since 8.0
   */
  public static final byte DC1 = 17; // aka XON

  /**
   * Transmission On: Although originally defined as DC1, this ASCII control character is now better
   * known as the XON code used for software flow control in serial communications. The main use is
   * restarting the transmission after the communication has been stopped by the XOFF control code.
   *
   * @since 8.0
   */
  public static final byte XON = 17; // aka DC1

  /**
   * Device Control 2. Characters for the control of ancillary devices associated with data
   * processing or telecommunication systems, more especially switching devices "on" or "off." (If a
   * single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the
   * preferred assignment.)
   *
   * @since 8.0
   */
  public static final byte DC2 = 18;

  /**
   * Device Control 3. Characters for the control of ancillary devices associated with data
   * processing or telecommunication systems, more especially switching devices "on" or "off." (If a
   * single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the
   * preferred assignment.)
   *
   * @since 8.0
   */
  public static final byte DC3 = 19; // aka XOFF

  /**
   * Transmission off. See {@link #XON} for explanation.
   *
   * @since 8.0
   */
  public static final byte XOFF = 19; // aka DC3

  /**
   * Device Control 4. Characters for the control of ancillary devices associated with data
   * processing or telecommunication systems, more especially switching devices "on" or "off." (If a
   * single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the
   * preferred assignment.)
   *
   * @since 8.0
   */
  public static final byte DC4 = 20;

  /**
   * Negative Acknowledge: A communication control character transmitted by a receiver as a negative
   * response to the sender.
   *
   * @since 8.0
   */
  public static final byte NAK = 21;

  /**
   * Synchronous Idle: A communication control character used by a synchronous transmission system
   * in the absence of any other character to provide a signal from which synchronism may be
   * achieved or retained.
   *
   * @since 8.0
   */
  public static final byte SYN = 22;

  /**
   * End of Transmission Block: A communication control character used to indicate the end of a
   * block of data for communication purposes. ETB is used for blocking data where the block
   * structure is not necessarily related to the processing format.
   *
   * @since 8.0
   */
  public static final byte ETB = 23;

  /**
   * Cancel: A control character used to indicate that the data with which it is sent is in error or
   * is to be disregarded.
   *
   * @since 8.0
   */
  public static final byte CAN = 24;

  /**
   * End of Medium: A control character associated with the sent data which may be used to identify
   * the physical end of the medium, or the end of the used, or wanted, portion of information
   * recorded on a medium. (The position of this character does not necessarily correspond to the
   * physical end of the medium.)
   *
   * @since 8.0
   */
  public static final byte EM = 25;

  /**
   * Substitute: A character that may be substituted for a character which is determined to be
   * invalid or in error.
   *
   * @since 8.0
   */
  public static final byte SUB = 26;

  /**
   * Escape: A control character intended to provide code extension (supplementary characters) in
   * general information interchange. The Escape character itself is a prefix affecting the
   * interpretation of a limited number of contiguously following characters.
   *
   * @since 8.0
   */
  public static final byte ESC = 27;

  /**
   * File Separator: These four information separators may be used within data in optional fashion,
   * except that their hierarchical relationship shall be: FS is the most inclusive, then GS, then
   * RS, and US is least inclusive. (The content and length of a File, Group, Record, or Unit are
   * not specified.)
   *
   * @since 8.0
   */
  public static final byte FS = 28;

  /**
   * Group Separator: These four information separators may be used within data in optional fashion,
   * except that their hierarchical relationship shall be: FS is the most inclusive, then GS, then
   * RS, and US is least inclusive. (The content and length of a File, Group, Record, or Unit are
   * not specified.)
   *
   * @since 8.0
   */
  public static final byte GS = 29;

  /**
   * Record Separator: These four information separators may be used within data in optional
   * fashion, except that their hierarchical relationship shall be: FS is the most inclusive, then
   * GS, then RS, and US is least inclusive. (The content and length of a File, Group, Record, or
   * Unit are not specified.)
   *
   * @since 8.0
   */
  public static final byte RS = 30;

  /**
   * Unit Separator: These four information separators may be used within data in optional fashion,
   * except that their hierarchical relationship shall be: FS is the most inclusive, then GS, then
   * RS, and US is least inclusive. (The content and length of a File, Group, Record, or Unit are
   * not specified.)
   *
   * @since 8.0
   */
  public static final byte US = 31;

  /**
   * Space: A normally non-printing graphic character used to separate words. It is also a format
   * effector which controls the movement of the printing position, one printing position forward.
   * (Applicable also to display devices.)
   *
   * @since 8.0
   */
  public static final byte SP = 32;

  /**
   * Alternate name for {@link #SP}.
   *
   * @since 8.0
   */
  public static final byte SPACE = 32;

  /**
   * Delete: This character is used primarily to "erase" or "obliterate" erroneous or unwanted
   * characters in perforated tape.
   *
   * @since 8.0
   */
  public static final byte DEL = 127;

  /**
   * The minimum value of an ASCII character.
   *
   * @since 9.0 (was type {@code int} before 12.0)
   */
  public static final char MIN = 0;

  /**
   * The maximum value of an ASCII character.
   *
   * @since 9.0 (was type {@code int} before 12.0)
   */
  public static final char MAX = 127;

  /** A bit mask which selects the bit encoding ASCII character case. */
  private static final char CASE_MASK = 0x20;

  /**
   * Returns a copy of the input string in which all {@linkplain #isUpperCase(char) uppercase ASCII
   * characters} have been converted to lowercase. All other characters are copied without
   * modification.
   */
  public static String toLowerCase(String string) {
    int length = string.length();
    for (int i = 0; i < length; i++) {
      if (isUpperCase(string.charAt(i))) {
        char[] chars = string.toCharArray();
        for (; i < length; i++) {
          char c = chars[i];
          if (isUpperCase(c)) {
            chars[i] = (char) (c ^ CASE_MASK);
          }
        }
        return String.valueOf(chars);
      }
    }
    return string;
  }

  /**
   * Returns a copy of the input character sequence in which all {@linkplain #isUpperCase(char)
   * uppercase ASCII characters} have been converted to lowercase. All other characters are copied
   * without modification.
   *
   * @since 14.0
   */
  public static String toLowerCase(CharSequence chars) {
    if (chars instanceof String) {
      return toLowerCase((String) chars);
    }
    char[] newChars = new char[chars.length()];
    for (int i = 0; i < newChars.length; i++) {
      newChars[i] = toLowerCase(chars.charAt(i));
    }
    return String.valueOf(newChars);
  }

  /**
   * If the argument is an {@linkplain #isUpperCase(char) uppercase ASCII character} returns the
   * lowercase equivalent. Otherwise returns the argument.
   */
  public static char toLowerCase(char c) {
    return isUpperCase(c) ? (char) (c ^ CASE_MASK) : c;
  }

  /**
   * Returns a copy of the input string in which all {@linkplain #isLowerCase(char) lowercase ASCII
   * characters} have been converted to uppercase. All other characters are copied without
   * modification.
   */
  public static String toUpperCase(String string) {
    int length = string.length();
    for (int i = 0; i < length; i++) {
      if (isLowerCase(string.charAt(i))) {
        char[] chars = string.toCharArray();
        for (; i < length; i++) {
          char c = chars[i];
          if (isLowerCase(c)) {
            chars[i] = (char) (c ^ CASE_MASK);
          }
        }
        return String.valueOf(chars);
      }
    }
    return string;
  }

  /**
   * Returns a copy of the input character sequence in which all {@linkplain #isLowerCase(char)
   * lowercase ASCII characters} have been converted to uppercase. All other characters are copied
   * without modification.
   *
   * @since 14.0
   */
  public static String toUpperCase(CharSequence chars) {
    if (chars instanceof String) {
      return toUpperCase((String) chars);
    }
    char[] newChars = new char[chars.length()];
    for (int i = 0; i < newChars.length; i++) {
      newChars[i] = toUpperCase(chars.charAt(i));
    }
    return String.valueOf(newChars);
  }

  /**
   * If the argument is a {@linkplain #isLowerCase(char) lowercase ASCII character} returns the
   * uppercase equivalent. Otherwise returns the argument.
   */
  public static char toUpperCase(char c) {
    return isLowerCase(c) ? (char) (c ^ CASE_MASK) : c;
  }

  /**
   * Indicates whether {@code c} is one of the twenty-six lowercase ASCII alphabetic characters
   * between {@code 'a'} and {@code 'z'} inclusive. All others (including non-ASCII characters)
   * return {@code false}.
   */
  public static boolean isLowerCase(char c) {
    // Note: This was benchmarked against the alternate expression "(char)(c - 'a') < 26" (Nov '13)
    // and found to perform at least as well, or better.
    return (c >= 'a') && (c <= 'z');
  }

  /**
   * Indicates whether {@code c} is one of the twenty-six uppercase ASCII alphabetic characters
   * between {@code 'A'} and {@code 'Z'} inclusive. All others (including non-ASCII characters)
   * return {@code false}.
   */
  public static boolean isUpperCase(char c) {
    return (c >= 'A') && (c <= 'Z');
  }

  /**
   * Truncates the given character sequence to the given maximum length. If the length of the
   * sequence is greater than {@code maxLength}, the returned string will be exactly {@code
   * maxLength} chars in length and will end with the given {@code truncationIndicator}. Otherwise,
   * the sequence will be returned as a string with no changes to the content.
   *
   *
Examples:
   *
   *
{@code
   * Ascii.truncate("foobar", 7, "..."); // returns "foobar"
   * Ascii.truncate("foobar", 5, "..."); // returns "fo..."
   * }

   *
   *
Note: This method may work with certain non-ASCII text but is not safe for use
   * with arbitrary Unicode text. It is mostly intended for use with text that is known to be safe
   * for use with it (such as all-ASCII text) and for simple debugging text. When using this method,
   * consider the following:
   *
   *

   *
it may split surrogate pairs
   *
it may split characters and combining characters
   *
it does not consider word boundaries
   *
if truncating for display to users, there are other considerations that must be taken
   *       into account
   *
the appropriate truncation indicator may be locale-dependent
   *
it is safe to use non-ASCII characters in the truncation indicator
   *

   *
   *
   * @throws IllegalArgumentException if {@code maxLength} is less than the length of {@code
   *     truncationIndicator}
   * @since 16.0
   */
  public static String truncate(CharSequence seq, int maxLength, String truncationIndicator) {
    checkNotNull(seq);

    // length to truncate the sequence to, not including the truncation indicator
    int truncationLength = maxLength - truncationIndicator.length();

    // in this worst case, this allows a maxLength equal to the length of the truncationIndicator,
    // meaning that a string will be truncated to just the truncation indicator itself
    checkArgument(
        truncationLength >= 0,
        "maxLength (%s) must be >= length of the truncation indicator (%s)",
        maxLength,
        truncationIndicator.length());

    if (seq.length() <= maxLength) {
      String string = seq.toString();
      if (string.length() <= maxLength) {
        return string;
      }
      // if the length of the toString() result was > maxLength for some reason, truncate that
      seq = string;
    }

    return new StringBuilder(maxLength)
        .append(seq, 0, truncationLength)
        .append(truncationIndicator)
        .toString();
  }

  /**
   * Indicates whether the contents of the given character sequences {@code s1} and {@code s2} are
   * equal, ignoring the case of any ASCII alphabetic characters between {@code 'a'} and {@code 'z'}
   * or {@code 'A'} and {@code 'Z'} inclusive.
   *
   *
This method is significantly faster than {@link String#equalsIgnoreCase} and should be used
   * in preference if at least one of the parameters is known to contain only ASCII characters.
   *
   *
Note however that this method does not always behave identically to expressions such as:
   *
   *

   *
{@code string.toUpperCase().equals("UPPER CASE ASCII")}
   *
{@code string.toLowerCase().equals("lower case ascii")}
   *

   *
   *
due to case-folding of some non-ASCII characters (which does not occur in {@link
   * String#equalsIgnoreCase}). However in almost all cases that ASCII strings are used, the author
   * probably wanted the behavior provided by this method rather than the subtle and sometimes
   * surprising behavior of {@code toUpperCase()} and {@code toLowerCase()}.
   *
   * @since 16.0
   */
  public static boolean equalsIgnoreCase(CharSequence s1, CharSequence s2) {
    // Calling length() is the null pointer check (so do it before we can exit early).
    int length = s1.length();
    if (s1 == s2) {
      return true;
    }
    if (length != s2.length()) {
      return false;
    }
    for (int i = 0; i < length; i++) {
      char c1 = s1.charAt(i);
      char c2 = s2.charAt(i);
      if (c1 == c2) {
        continue;
      }
      int alphaIndex = getAlphaIndex(c1);
      // This was also benchmarked using '&' to avoid branching (but always evaluate the rhs),
      // however this showed no obvious improvement.
      if (alphaIndex < 26 && alphaIndex == getAlphaIndex(c2)) {
        continue;
      }
      return false;
    }
    return true;
  }

  /**
   * Returns the non-negative index value of the alpha character {@code c}, regardless of case. Ie,
   * 'a'/'A' returns 0 and 'z'/'Z' returns 25. Non-alpha characters return a value of 26 or greater.
   */
  private static int getAlphaIndex(char c) {
    // Fold upper-case ASCII to lower-case and make zero-indexed and unsigned (by casting to char).
    return (char) ((c | CASE_MASK) - 'a');
  }
}


/*
 * Copyright (C) 2015 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 com.google.common.annotations.GwtIncompatible;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collector;

/**
 * "Overrides" the {@link ImmutableMap} static methods that lack {@link ImmutableBiMap} equivalents
 * with deprecated, exception-throwing versions. See {@link ImmutableSortedSetFauxverideShim} for
 * details.
 *
 * @author Louis Wasserman
 */
@GwtIncompatible
abstract class ImmutableBiMapFauxverideShim<K, V> extends ImmutableMap<K, V> {
  /**
   * Not supported. Use {@link ImmutableBiMap#toImmutableBiMap} instead. This method exists only to
   * hide {@link ImmutableMap#toImmutableMap(Function, Function)} from consumers of {@code
   * ImmutableBiMap}.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Use {@link ImmutableBiMap#toImmutableBiMap}.
   */
  @Deprecated
  public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
      Function<? super T, ? extends K> keyFunction,
      Function<? super T, ? extends V> valueFunction) {
    throw new UnsupportedOperationException();
  }

  /**
   * Not supported. This method does not make sense for {@code BiMap}. This method exists only to
   * hide {@link ImmutableMap#toImmutableMap(Function, Function, BinaryOperator)} from consumers of
   * {@code ImmutableBiMap}.
   *
   * @throws UnsupportedOperationException always
   * @deprecated
   */
  @Deprecated
  public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
      Function<? super T, ? extends K> keyFunction,
      Function<? super T, ? extends V> valueFunction,
      BinaryOperator<V> mergeFunction) {
    throw new UnsupportedOperationException();
  }
}


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

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

import com.google.common.annotations.GwtCompatible;
import com.google.common.primitives.Booleans;
import java.io.Serializable;
import java.util.NoSuchElementException;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * Implementation detail for the internal structure of {@link Range} instances. Represents a unique
 * way of "cutting" a "number line" (actually of instances of type {@code C}, not necessarily
 * "numbers") into two sections; this can be done below a certain value, above a certain value,
 * below all values or above all values. With this object defined in this way, an interval can
 * always be represented by a pair of {@code Cut} instances.
 *
 * @author Kevin Bourrillion
 */
@GwtCompatible
abstract class Cut<C extends Comparable> implements Comparable<Cut<C>>, Serializable {
  final @Nullable C endpoint;

  Cut(@Nullable C endpoint) {
    this.endpoint = endpoint;
  }

  abstract boolean isLessThan(C value);

  abstract BoundType typeAsLowerBound();

  abstract BoundType typeAsUpperBound();

  abstract Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain);

  abstract Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain);

  abstract void describeAsLowerBound(StringBuilder sb);

  abstract void describeAsUpperBound(StringBuilder sb);

  abstract C leastValueAbove(DiscreteDomain<C> domain);

  abstract C greatestValueBelow(DiscreteDomain<C> domain);

  /*
   * The canonical form is a BelowValue cut whenever possible, otherwise ABOVE_ALL, or
   * (only in the case of types that are unbounded below) BELOW_ALL.
   */
  Cut<C> canonical(DiscreteDomain<C> domain) {
    return this;
  }

  // note: overridden by {BELOW,ABOVE}_ALL
  @Override
  public int compareTo(Cut<C> that) {
    if (that == belowAll()) {
      return 1;
    }
    if (that == aboveAll()) {
      return -1;
    }
    int result = Range.compareOrThrow(endpoint, that.endpoint);
    if (result != 0) {
      return result;
    }
    // same value. below comes before above
    return Booleans.compare(this instanceof AboveValue, that instanceof AboveValue);
  }

  C endpoint() {
    return endpoint;
  }

  @SuppressWarnings("unchecked") // catching CCE
  @Override
  public boolean equals(Object obj) {
    if (obj instanceof Cut) {
      // It might not really be a Cut<C>, but we'll catch a CCE if it's not
      Cut<C> that = (Cut<C>) obj;
      try {
        int compareResult = compareTo(that);
        return compareResult == 0;
      } catch (ClassCastException ignored) {
      }
    }
    return false;
  }

  // Prevent "missing hashCode" warning by explicitly forcing subclasses implement it
  @Override
  public abstract int hashCode();

  /*
   * The implementation neither produces nor consumes any non-null instance of type C, so
   * casting the type parameter is safe.
   */
  @SuppressWarnings("unchecked")
  static <C extends Comparable> Cut<C> belowAll() {
    return (Cut<C>) BelowAll.INSTANCE;
  }

  private static final long serialVersionUID = 0;

  private static final class BelowAll extends Cut<Comparable<?>> {
    private static final BelowAll INSTANCE = new BelowAll();

    private BelowAll() {
      super(null);
    }

    @Override
    Comparable<?> endpoint() {
      throw new IllegalStateException("range unbounded on this side");
    }

    @Override
    boolean isLessThan(Comparable<?> value) {
      return true;
    }

    @Override
    BoundType typeAsLowerBound() {
      throw new IllegalStateException();
    }

    @Override
    BoundType typeAsUpperBound() {
      throw new AssertionError("this statement should be unreachable");
    }

    @Override
    Cut<Comparable<?>> withLowerBoundType(
        BoundType boundType, DiscreteDomain<Comparable<?>> domain) {
      throw new IllegalStateException();
    }

    @Override
    Cut<Comparable<?>> withUpperBoundType(
        BoundType boundType, DiscreteDomain<Comparable<?>> domain) {
      throw new AssertionError("this statement should be unreachable");
    }

    @Override
    void describeAsLowerBound(StringBuilder sb) {
      sb.append("(-\u221e");
    }

    @Override
    void describeAsUpperBound(StringBuilder sb) {
      throw new AssertionError();
    }

    @Override
    Comparable<?> leastValueAbove(DiscreteDomain<Comparable<?>> domain) {
      return domain.minValue();
    }

    @Override
    Comparable<?> greatestValueBelow(DiscreteDomain<Comparable<?>> domain) {
      throw new AssertionError();
    }

    @Override
    Cut<Comparable<?>> canonical(DiscreteDomain<Comparable<?>> domain) {
      try {
        return Cut.<Comparable<?>>belowValue(domain.minValue());
      } catch (NoSuchElementException e) {
        return this;
      }
    }

    @Override
    public int compareTo(Cut<Comparable<?>> o) {
      return (o == this) ? 0 : -1;
    }

    @Override
    public int hashCode() {
      return System.identityHashCode(this);
    }

    @Override
    public String toString() {
      return "-\u221e";
    }

    private Object readResolve() {
      return INSTANCE;
    }

    private static final long serialVersionUID = 0;
  }

  /*
   * The implementation neither produces nor consumes any non-null instance of
   * type C, so casting the type parameter is safe.
   */
  @SuppressWarnings("unchecked")
  static <C extends Comparable> Cut<C> aboveAll() {
    return (Cut<C>) AboveAll.INSTANCE;
  }

  private static final class AboveAll extends Cut<Comparable<?>> {
    private static final AboveAll INSTANCE = new AboveAll();

    private AboveAll() {
      super(null);
    }

    @Override
    Comparable<?> endpoint() {
      throw new IllegalStateException("range unbounded on this side");
    }

    @Override
    boolean isLessThan(Comparable<?> value) {
      return false;
    }

    @Override
    BoundType typeAsLowerBound() {
      throw new AssertionError("this statement should be unreachable");
    }

    @Override
    BoundType typeAsUpperBound() {
      throw new IllegalStateException();
    }

    @Override
    Cut<Comparable<?>> withLowerBoundType(
        BoundType boundType, DiscreteDomain<Comparable<?>> domain) {
      throw new AssertionError("this statement should be unreachable");
    }

    @Override
    Cut<Comparable<?>> withUpperBoundType(
        BoundType boundType, DiscreteDomain<Comparable<?>> domain) {
      throw new IllegalStateException();
    }

    @Override
    void describeAsLowerBound(StringBuilder sb) {
      throw new AssertionError();
    }

    @Override
    void describeAsUpperBound(StringBuilder sb) {
      sb.append("+\u221e)");
    }

    @Override
    Comparable<?> leastValueAbove(DiscreteDomain<Comparable<?>> domain) {
      throw new AssertionError();
    }

    @Override
    Comparable<?> greatestValueBelow(DiscreteDomain<Comparable<?>> domain) {
      return domain.maxValue();
    }

    @Override
    public int compareTo(Cut<Comparable<?>> o) {
      return (o == this) ? 0 : 1;
    }

    @Override
    public int hashCode() {
      return System.identityHashCode(this);
    }

    @Override
    public String toString() {
      return "+\u221e";
    }

    private Object readResolve() {
      return INSTANCE;
    }

    private static final long serialVersionUID = 0;
  }

  static <C extends Comparable> Cut<C> belowValue(C endpoint) {
    return new BelowValue<C>(endpoint);
  }

  private static final class BelowValue<C extends Comparable> extends Cut<C> {
    BelowValue(C endpoint) {
      super(checkNotNull(endpoint));
    }

    @Override
    boolean isLessThan(C value) {
      return Range.compareOrThrow(endpoint, value) <= 0;
    }

    @Override
    BoundType typeAsLowerBound() {
      return BoundType.CLOSED;
    }

    @Override
    BoundType typeAsUpperBound() {
      return BoundType.OPEN;
    }

    @Override
    Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain) {
      switch (boundType) {
        case CLOSED:
          return this;
        case OPEN:
          @Nullable C previous = domain.previous(endpoint);
          return (previous == null) ? Cut.<C>belowAll() : new AboveValue<C>(previous);
        default:
          throw new AssertionError();
      }
    }

    @Override
    Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain) {
      switch (boundType) {
        case CLOSED:
          @Nullable C previous = domain.previous(endpoint);
          return (previous == null) ? Cut.<C>aboveAll() : new AboveValue<C>(previous);
        case OPEN:
          return this;
        default:
          throw new AssertionError();
      }
    }

    @Override
    void describeAsLowerBound(StringBuilder sb) {
      sb.append('[').append(endpoint);
    }

    @Override
    void describeAsUpperBound(StringBuilder sb) {
      sb.append(endpoint).append(')');
    }

    @Override
    C leastValueAbove(DiscreteDomain<C> domain) {
      return endpoint;
    }

    @Override
    C greatestValueBelow(DiscreteDomain<C> domain) {
      return domain.previous(endpoint);
    }

    @Override
    public int hashCode() {
      return endpoint.hashCode();
    }

    @Override
    public String toString() {
      return "\\" + endpoint + "/";
    }

    private static final long serialVersionUID = 0;
  }

  static <C extends Comparable> Cut<C> aboveValue(C endpoint) {
    return new AboveValue<C>(endpoint);
  }

  private static final class AboveValue<C extends Comparable> extends Cut<C> {
    AboveValue(C endpoint) {
      super(checkNotNull(endpoint));
    }

    @Override
    boolean isLessThan(C value) {
      return Range.compareOrThrow(endpoint, value) < 0;
    }

    @Override
    BoundType typeAsLowerBound() {
      return BoundType.OPEN;
    }

    @Override
    BoundType typeAsUpperBound() {
      return BoundType.CLOSED;
    }

    @Override
    Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain) {
      switch (boundType) {
        case OPEN:
          return this;
        case CLOSED:
          @Nullable C next = domain.next(endpoint);
          return (next == null) ? Cut.<C>belowAll() : belowValue(next);
        default:
          throw new AssertionError();
      }
    }

    @Override
    Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain) {
      switch (boundType) {
        case OPEN:
          @Nullable C next = domain.next(endpoint);
          return (next == null) ? Cut.<C>aboveAll() : belowValue(next);
        case CLOSED:
          return this;
        default:
          throw new AssertionError();
      }
    }

    @Override
    void describeAsLowerBound(StringBuilder sb) {
      sb.append('(').append(endpoint);
    }

    @Override
    void describeAsUpperBound(StringBuilder sb) {
      sb.append(endpoint).append(']');
    }

    @Override
    C leastValueAbove(DiscreteDomain<C> domain) {
      return domain.next(endpoint);
    }

    @Override
    C greatestValueBelow(DiscreteDomain<C> domain) {
      return endpoint;
    }

    @Override
    Cut<C> canonical(DiscreteDomain<C> domain) {
      C next = leastValueAbove(domain);
      return (next != null) ? belowValue(next) : Cut.<C>aboveAll();
    }

    @Override
    public int hashCode() {
      return ~endpoint.hashCode();
    }

    @Override
    public String toString() {
      return "/" + endpoint + "\\";
    }

    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.base;

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

import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Arrays;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * Helper functions that operate on any {@code Object}, and are not already provided in {@link
 * java.util.Objects}.
 *
 *
See the Guava User Guide on writing {@code Object}
 * methods with {@code MoreObjects}.
 *
 * @author Laurence Gonsalves
 * @since 18.0 (since 2.0 as {@code Objects})
 */
@GwtCompatible
public final class MoreObjects {
  /**
   * Returns the first of two given parameters that is not {@code null}, if either is, or otherwise
   * throws a {@link NullPointerException}.
   *
   *
To find the first non-null element in an iterable, use {@code Iterables.find(iterable,
   * Predicates.notNull())}. For varargs, use {@code Iterables.find(Arrays.asList(a, b, c, ...),
   * Predicates.notNull())}, static importing as necessary.
   *
   *
Note: if {@code first} is represented as an {@link Optional}, this can be
   * accomplished with {@link Optional#or(Object) first.or(second)}. That approach also allows for
   * lazy evaluation of the fallback instance, using {@link Optional#or(Supplier)
   * first.or(supplier)}.
   *
   * @return {@code first} if it is non-null; otherwise {@code second} if it is non-null
   * @throws NullPointerException if both {@code first} and {@code second} are null
   * @since 18.0 (since 3.0 as {@code Objects.firstNonNull()}).
   */
  public static <T> T firstNonNull(@NullableDecl T first, @NullableDecl T second) {
    if (first != null) {
      return first;
    }
    if (second != null) {
      return second;
    }
    throw new NullPointerException("Both parameters are null");
  }

  /**
   * Creates an instance of {@link ToStringHelper}.
   *
   *
This is helpful for implementing {@link Object#toString()}. Specification by example:
   *
   *
{@code
   * // Returns "ClassName{}"
   * MoreObjects.toStringHelper(this)
   *     .toString();
   *
   * // Returns "ClassName{x=1}"
   * MoreObjects.toStringHelper(this)
   *     .add("x", 1)
   *     .toString();
   *
   * // Returns "MyObject{x=1}"
   * MoreObjects.toStringHelper("MyObject")
   *     .add("x", 1)
   *     .toString();
   *
   * // Returns "ClassName{x=1, y=foo}"
   * MoreObjects.toStringHelper(this)
   *     .add("x", 1)
   *     .add("y", "foo")
   *     .toString();
   *
   * // Returns "ClassName{x=1}"
   * MoreObjects.toStringHelper(this)
   *     .omitNullValues()
   *     .add("x", 1)
   *     .add("y", null)
   *     .toString();
   * }

   *
   *
Note that in GWT, class names are often obfuscated.
   *
   * @param self the object to generate the string for (typically {@code this}), used only for its
   *     class name
   * @since 18.0 (since 2.0 as {@code Objects.toStringHelper()}).
   */
  public static ToStringHelper toStringHelper(Object self) {
    return new ToStringHelper(self.getClass().getSimpleName());
  }

  /**
   * Creates an instance of {@link ToStringHelper} in the same manner as {@link
   * #toStringHelper(Object)}, but using the simple name of {@code clazz} instead of using an
   * instance's {@link Object#getClass()}.
   *
   *
Note that in GWT, class names are often obfuscated.
   *
   * @param clazz the {@link Class} of the instance
   * @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}).
   */
  public static ToStringHelper toStringHelper(Class<?> clazz) {
    return new ToStringHelper(clazz.getSimpleName());
  }

  /**
   * Creates an instance of {@link ToStringHelper} in the same manner as {@link
   * #toStringHelper(Object)}, but using {@code className} instead of using an instance's {@link
   * Object#getClass()}.
   *
   * @param className the name of the instance type
   * @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}).
   */
  public static ToStringHelper toStringHelper(String className) {
    return new ToStringHelper(className);
  }

  /**
   * Support class for {@link MoreObjects#toStringHelper}.
   *
   * @author Jason Lee
   * @since 18.0 (since 2.0 as {@code Objects.ToStringHelper}).
   */
  public static final class ToStringHelper {
    private final String className;
    private final ValueHolder holderHead = new ValueHolder();
    private ValueHolder holderTail = holderHead;
    private boolean omitNullValues = false;

    /** Use {@link MoreObjects#toStringHelper(Object)} to create an instance. */
    private ToStringHelper(String className) {
      this.className = checkNotNull(className);
    }

    /**
     * Configures the {@link ToStringHelper} so {@link #toString()} will ignore properties with null
     * value. The order of calling this method, relative to the {@code add()}/{@code addValue()}
     * methods, is not significant.
     *
     * @since 18.0 (since 12.0 as {@code Objects.ToStringHelper.omitNullValues()}).
     */
    @CanIgnoreReturnValue
    public ToStringHelper omitNullValues() {
      omitNullValues = true;
      return this;
    }

    /**
     * Adds a name/value pair to the formatted output in {@code name=value} format. If {@code value}
     * is {@code null}, the string {@code "null"} is used, unless {@link #omitNullValues()} is
     * called, in which case this name/value pair will not be added.
     */
    @CanIgnoreReturnValue
    public ToStringHelper add(String name, @NullableDecl Object value) {
      return addHolder(name, value);
    }

    /**
     * Adds a name/value pair to the formatted output in {@code name=value} format.
     *
     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
     */
    @CanIgnoreReturnValue
    public ToStringHelper add(String name, boolean value) {
      return addHolder(name, String.valueOf(value));
    }

    /**
     * Adds a name/value pair to the formatted output in {@code name=value} format.
     *
     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
     */
    @CanIgnoreReturnValue
    public ToStringHelper add(String name, char value) {
      return addHolder(name, String.valueOf(value));
    }

    /**
     * Adds a name/value pair to the formatted output in {@code name=value} format.
     *
     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
     */
    @CanIgnoreReturnValue
    public ToStringHelper add(String name, double value) {
      return addHolder(name, String.valueOf(value));
    }

    /**
     * Adds a name/value pair to the formatted output in {@code name=value} format.
     *
     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
     */
    @CanIgnoreReturnValue
    public ToStringHelper add(String name, float value) {
      return addHolder(name, String.valueOf(value));
    }

    /**
     * Adds a name/value pair to the formatted output in {@code name=value} format.
     *
     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
     */
    @CanIgnoreReturnValue
    public ToStringHelper add(String name, int value) {
      return addHolder(name, String.valueOf(value));
    }

    /**
     * Adds a name/value pair to the formatted output in {@code name=value} format.
     *
     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
     */
    @CanIgnoreReturnValue
    public ToStringHelper add(String name, long value) {
      return addHolder(name, String.valueOf(value));
    }

    /**
     * Adds an unnamed value to the formatted output.
     *
     *
It is strongly encouraged to use {@link #add(String, Object)} instead and give value a
     * readable name.
     */
    @CanIgnoreReturnValue
    public ToStringHelper addValue(@NullableDecl Object value) {
      return addHolder(value);
    }

    /**
     * Adds an unnamed value to the formatted output.
     *
     *
It is strongly encouraged to use {@link #add(String, boolean)} instead and give value a
     * readable name.
     *
     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
     */
    @CanIgnoreReturnValue
    public ToStringHelper addValue(boolean value) {
      return addHolder(String.valueOf(value));
    }

    /**
     * Adds an unnamed value to the formatted output.
     *
     *
It is strongly encouraged to use {@link #add(String, char)} instead and give value a
     * readable name.
     *
     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
     */
    @CanIgnoreReturnValue
    public ToStringHelper addValue(char value) {
      return addHolder(String.valueOf(value));
    }

    /**
     * Adds an unnamed value to the formatted output.
     *
     *
It is strongly encouraged to use {@link #add(String, double)} instead and give value a
     * readable name.
     *
     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
     */
    @CanIgnoreReturnValue
    public ToStringHelper addValue(double value) {
      return addHolder(String.valueOf(value));
    }

    /**
     * Adds an unnamed value to the formatted output.
     *
     *
It is strongly encouraged to use {@link #add(String, float)} instead and give value a
     * readable name.
     *
     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
     */
    @CanIgnoreReturnValue
    public ToStringHelper addValue(float value) {
      return addHolder(String.valueOf(value));
    }

    /**
     * Adds an unnamed value to the formatted output.
     *
     *
It is strongly encouraged to use {@link #add(String, int)} instead and give value a
     * readable name.
     *
     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
     */
    @CanIgnoreReturnValue
    public ToStringHelper addValue(int value) {
      return addHolder(String.valueOf(value));
    }

    /**
     * Adds an unnamed value to the formatted output.
     *
     *
It is strongly encouraged to use {@link #add(String, long)} instead and give value a
     * readable name.
     *
     * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
     */
    @CanIgnoreReturnValue
    public ToStringHelper addValue(long value) {
      return addHolder(String.valueOf(value));
    }

    /**
     * Returns a string in the format specified by {@link MoreObjects#toStringHelper(Object)}.
     *
     *
After calling this method, you can keep adding more properties to later call toString()
     * again and get a more complete representation of the same object; but properties cannot be
     * removed, so this only allows limited reuse of the helper instance. The helper allows
     * duplication of properties (multiple name/value pairs with the same name can be added).
     */
    @Override
    public String toString() {
      // create a copy to keep it consistent in case value changes
      boolean omitNullValuesSnapshot = omitNullValues;
      String nextSeparator = "";
      StringBuilder builder = new StringBuilder(32).append(className).append('{');
      for (ValueHolder valueHolder = holderHead.next;
          valueHolder != null;
          valueHolder = valueHolder.next) {
        Object value = valueHolder.value;
        if (!omitNullValuesSnapshot || value != null) {
          builder.append(nextSeparator);
          nextSeparator = ", ";

          if (valueHolder.name != null) {
            builder.append(valueHolder.name).append('=');
          }
          if (value != null && value.getClass().isArray()) {
            Object[] objectArray = {value};
            String arrayString = Arrays.deepToString(objectArray);
            builder.append(arrayString, 1, arrayString.length() - 1);
          } else {
            builder.append(value);
          }
        }
      }
      return builder.append('}').toString();
    }

    private ValueHolder addHolder() {
      ValueHolder valueHolder = new ValueHolder();
      holderTail = holderTail.next = valueHolder;
      return valueHolder;
    }

    private ToStringHelper addHolder(@NullableDecl Object value) {
      ValueHolder valueHolder = addHolder();
      valueHolder.value = value;
      return this;
    }

    private ToStringHelper addHolder(String name, @NullableDecl Object value) {
      ValueHolder valueHolder = addHolder();
      valueHolder.value = value;
      valueHolder.name = checkNotNull(name);
      return this;
    }

    private static final class ValueHolder {
      @NullableDecl String name;
      @NullableDecl Object value;
      @NullableDecl ValueHolder next;
    }
  }

  private MoreObjects() {}
}


/*
 * 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.checkNotNull;
import static com.google.common.io.CharStreams.createBuffer;

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.LinkedList;
import java.util.Queue;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * A class for reading lines of text. Provides the same functionality as {@link
 * java.io.BufferedReader#readLine()} but for all {@link Readable} objects, not just instances of
 * {@link Reader}.
 *
 * @author Chris Nokleberg
 * @since 1.0
 */
@Beta
@GwtIncompatible
public final class LineReader {
  private final Readable readable;
  @NullableDecl private final Reader reader;
  private final CharBuffer cbuf = createBuffer();
  private final char[] buf = cbuf.array();

  private final Queue<String> lines = new LinkedList<>();
  private final LineBuffer lineBuf =
      new LineBuffer() {
        @Override
        protected void handleLine(String line, String end) {
          lines.add(line);
        }
      };

  /** Creates a new instance that will read lines from the given {@code Readable} object. */
  public LineReader(Readable readable) {
    this.readable = checkNotNull(readable);
    this.reader = (readable instanceof Reader) ? (Reader) readable : null;
  }

  /**
   * Reads a line of text. A line is considered to be terminated by any one of a line feed ({@code
   * '\n'}), a carriage return ({@code '\r'}), or a carriage return followed immediately by a
   * linefeed ({@code "\r\n"}).
   *
   * @return a {@code String} containing the contents of the line, not including any
   *     line-termination characters, or {@code null} if the end of the stream has been reached.
   * @throws IOException if an I/O error occurs
   */
  @CanIgnoreReturnValue // to skip a line
  public String readLine() throws IOException {
    while (lines.peek() == null) {
      cbuf.clear();
      // The default implementation of Reader#read(CharBuffer) allocates a
      // temporary char[], so we call Reader#read(char[], int, int) instead.
      int read = (reader != null) ? reader.read(buf, 0, buf.length) : readable.read(cbuf);
      if (read == -1) {
        lineBuf.finish();
        break;
      }
      lineBuf.add(buf, 0, read);
    }
    return lines.poll();
  }
}


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

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

import com.google.common.annotations.GwtCompatible;
import com.google.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.NoSuchElementException;

/**
 * A descriptor for a discrete {@code Comparable} domain such as all {@link Integer}
 * instances. A discrete domain is one that supports the three basic operations: {@link #next},
 * {@link #previous} and {@link #distance}, according to their specifications. The methods {@link
 * #minValue} and {@link #maxValue} should also be overridden for bounded types.
 *
 *
A discrete domain always represents the entire set of values of its type; it cannot
 * represent partial domains such as "prime integers" or "strings of length 5."
 *
 *
See the Guava User Guide section on  {@code
 * DiscreteDomain}.
 *
 * @author Kevin Bourrillion
 * @since 10.0
 */
@GwtCompatible
public abstract class DiscreteDomain<C extends Comparable> {

  /**
   * Returns the discrete domain for values of type {@code Integer}.
   *
   * @since 14.0 (since 10.0 as {@code DiscreteDomains.integers()})
   */
  public static DiscreteDomain<Integer> integers() {
    return IntegerDomain.INSTANCE;
  }

  private static final class IntegerDomain extends DiscreteDomain<Integer> implements Serializable {
    private static final IntegerDomain INSTANCE = new IntegerDomain();

    IntegerDomain() {
      super(true);
    }

    @Override
    public Integer next(Integer value) {
      int i = value;
      return (i == Integer.MAX_VALUE) ? null : i + 1;
    }

    @Override
    public Integer previous(Integer value) {
      int i = value;
      return (i == Integer.MIN_VALUE) ? null : i - 1;
    }

    @Override
    Integer offset(Integer origin, long distance) {
      checkNonnegative(distance, "distance");
      return Ints.checkedCast(origin.longValue() + distance);
    }

    @Override
    public long distance(Integer start, Integer end) {
      return (long) end - start;
    }

    @Override
    public Integer minValue() {
      return Integer.MIN_VALUE;
    }

    @Override
    public Integer maxValue() {
      return Integer.MAX_VALUE;
    }

    private Object readResolve() {
      return INSTANCE;
    }

    @Override
    public String toString() {
      return "DiscreteDomain.integers()";
    }

    private static final long serialVersionUID = 0;
  }

  /**
   * Returns the discrete domain for values of type {@code Long}.
   *
   * @since 14.0 (since 10.0 as {@code DiscreteDomains.longs()})
   */
  public static DiscreteDomain<Long> longs() {
    return LongDomain.INSTANCE;
  }

  private static final class LongDomain extends DiscreteDomain<Long> implements Serializable {
    private static final LongDomain INSTANCE = new LongDomain();

    LongDomain() {
      super(true);
    }

    @Override
    public Long next(Long value) {
      long l = value;
      return (l == Long.MAX_VALUE) ? null : l + 1;
    }

    @Override
    public Long previous(Long value) {
      long l = value;
      return (l == Long.MIN_VALUE) ? null : l - 1;
    }

    @Override
    Long offset(Long origin, long distance) {
      checkNonnegative(distance, "distance");
      long result = origin + distance;
      if (result < 0) {
        checkArgument(origin < 0, "overflow");
      }
      return result;
    }

    @Override
    public long distance(Long start, Long end) {
      long result = end - start;
      if (end > start && result < 0) { // overflow
        return Long.MAX_VALUE;
      }
      if (end < start && result > 0) { // underflow
        return Long.MIN_VALUE;
      }
      return result;
    }

    @Override
    public Long minValue() {
      return Long.MIN_VALUE;
    }

    @Override
    public Long maxValue() {
      return Long.MAX_VALUE;
    }

    private Object readResolve() {
      return INSTANCE;
    }

    @Override
    public String toString() {
      return "DiscreteDomain.longs()";
    }

    private static final long serialVersionUID = 0;
  }

  /**
   * Returns the discrete domain for values of type {@code BigInteger}.
   *
   * @since 15.0
   */
  public static DiscreteDomain<BigInteger> bigIntegers() {
    return BigIntegerDomain.INSTANCE;
  }

  private static final class BigIntegerDomain extends DiscreteDomain<BigInteger>
      implements Serializable {
    private static final BigIntegerDomain INSTANCE = new BigIntegerDomain();

    BigIntegerDomain() {
      super(true);
    }

    private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE);
    private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);

    @Override
    public BigInteger next(BigInteger value) {
      return value.add(BigInteger.ONE);
    }

    @Override
    public BigInteger previous(BigInteger value) {
      return value.subtract(BigInteger.ONE);
    }

    @Override
    BigInteger offset(BigInteger origin, long distance) {
      checkNonnegative(distance, "distance");
      return origin.add(BigInteger.valueOf(distance));
    }

    @Override
    public long distance(BigInteger start, BigInteger end) {
      return end.subtract(start).max(MIN_LONG).min(MAX_LONG).longValue();
    }

    private Object readResolve() {
      return INSTANCE;
    }

    @Override
    public String toString() {
      return "DiscreteDomain.bigIntegers()";
    }

    private static final long serialVersionUID = 0;
  }

  final boolean supportsFastOffset;

  /** Constructor for use by subclasses. */
  protected DiscreteDomain() {
    this(false);
  }

  /** Private constructor for built-in DiscreteDomains supporting fast offset. */
  private DiscreteDomain(boolean supportsFastOffset) {
    this.supportsFastOffset = supportsFastOffset;
  }

  /**
   * Returns, conceptually, "origin + distance", or equivalently, the result of calling {@link
   * #next} on {@code origin} {@code distance} times.
   */
  C offset(C origin, long distance) {
    checkNonnegative(distance, "distance");
    for (long i = 0; i < distance; i++) {
      origin = next(origin);
    }
    return origin;
  }

  /**
   * Returns the unique least value of type {@code C} that is greater than {@code value}, or {@code
   * null} if none exists. Inverse operation to {@link #previous}.
   *
   * @param value any value of type {@code C}
   * @return the least value greater than {@code value}, or {@code null} if {@code value} is {@code
   *     maxValue()}
   */
  public abstract C next(C value);

  /**
   * Returns the unique greatest value of type {@code C} that is less than {@code value}, or {@code
   * null} if none exists. Inverse operation to {@link #next}.
   *
   * @param value any value of type {@code C}
   * @return the greatest value less than {@code value}, or {@code null} if {@code value} is {@code
   *     minValue()}
   */
  public abstract C previous(C value);

  /**
   * Returns a signed value indicating how many nested invocations of {@link #next} (if positive) or
   * {@link #previous} (if negative) are needed to reach {@code end} starting from {@code start}.
   * For example, if {@code end = next(next(next(start)))}, then {@code distance(start, end) == 3}
   * and {@code distance(end, start) == -3}. As well, {@code distance(a, a)} is always zero.
   *
   *
Note that this function is necessarily well-defined for any discrete type.
   *
   * @return the distance as described above, or {@link Long#MIN_VALUE} or {@link Long#MAX_VALUE} if
   *     the distance is too small or too large, respectively.
   */
  public abstract long distance(C start, C end);

  /**
   * Returns the minimum value of type {@code C}, if it has one. The minimum value is the unique
   * value for which {@link Comparable#compareTo(Object)} never returns a positive value for any
   * input of type {@code C}.
   *
   *
The default implementation throws {@code NoSuchElementException}.
   *
   * @return the minimum value of type {@code C}; never null
   * @throws NoSuchElementException if the type has no (practical) minimum value; for example,
   *     {@link java.math.BigInteger}
   */
  @CanIgnoreReturnValue
  public C minValue() {
    throw new NoSuchElementException();
  }

  /**
   * Returns the maximum value of type {@code C}, if it has one. The maximum value is the unique
   * value for which {@link Comparable#compareTo(Object)} never returns a negative value for any
   * input of type {@code C}.
   *
   *
The default implementation throws {@code NoSuchElementException}.
   *
   * @return the maximum value of type {@code C}; never null
   * @throws NoSuchElementException if the type has no (practical) maximum value; for example,
   *     {@link java.math.BigInteger}
   */
  @CanIgnoreReturnValue
  public C maxValue() {
    throw new NoSuchElementException();
  }
}


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

package com.google.common.collect;

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

import 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.common.primitives.Ints;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.google.j2objc.annotations.RetainedWith;
import java.io.Serializable;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.Collector;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A {@link Set} whose contents will never change, with many other important properties detailed at
 * {@link ImmutableCollection}.
 *
 * @since 2.0
 */
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
public abstract class ImmutableSet<E> extends ImmutableCollection<E> implements Set<E> {
  static final int SPLITERATOR_CHARACTERISTICS =
      ImmutableCollection.SPLITERATOR_CHARACTERISTICS | Spliterator.DISTINCT;

  /**
   * Returns a {@code Collector} that accumulates the input elements into a new {@code
   * ImmutableSet}. Elements appear in the resulting set in the encounter order of the stream; if
   * the stream contains duplicates (according to {@link Object#equals(Object)}), only the first
   * duplicate in encounter order will appear in the result.
   *
   * @since 21.0
   */
  public static <E> Collector<E, ?, ImmutableSet<E>> toImmutableSet() {
    return CollectCollectors.toImmutableSet();
  }

  /**
   * Returns the empty immutable set. Preferred over {@link Collections#emptySet} for code
   * consistency, and because the return type conveys the immutability guarantee.
   */
  @SuppressWarnings({"unchecked"}) // fully variant implementation (never actually produces any Es)
  public static <E> ImmutableSet<E> of() {
    return (ImmutableSet<E>) RegularImmutableSet.EMPTY;
  }

  /**
   * Returns an immutable set containing {@code element}. Preferred over {@link
   * Collections#singleton} for code consistency, {@code null} rejection, and because the return
   * type conveys the immutability guarantee.
   */
  public static <E> ImmutableSet<E> of(E element) {
    return new SingletonImmutableSet<E>(element);
  }

  /**
   * Returns an immutable set containing the given elements, minus duplicates, in the order each was
   * first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
   * the first are ignored.
   */
  public static <E> ImmutableSet<E> of(E e1, E e2) {
    return construct(2, 2, e1, e2);
  }

  /**
   * Returns an immutable set containing the given elements, minus duplicates, in the order each was
   * first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
   * the first are ignored.
   */
  public static <E> ImmutableSet<E> of(E e1, E e2, E e3) {
    return construct(3, 3, e1, e2, e3);
  }

  /**
   * Returns an immutable set containing the given elements, minus duplicates, in the order each was
   * first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
   * the first are ignored.
   */
  public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4) {
    return construct(4, 4, e1, e2, e3, e4);
  }

  /**
   * Returns an immutable set containing the given elements, minus duplicates, in the order each was
   * first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
   * the first are ignored.
   */
  public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5) {
    return construct(5, 5, e1, e2, e3, e4, e5);
  }

  /**
   * Returns an immutable set containing the given elements, minus duplicates, in the order each was
   * first specified. That is, if multiple elements are {@linkplain Object#equals equal}, all except
   * the first are ignored.
   *
   *
The array {@code others} must not be longer than {@code Integer.MAX_VALUE - 6}.
   *
   * @since 3.0 (source-compatible since 2.0)
   */
  @SafeVarargs // For Eclipse. For internal javac we have disabled this pointless type of warning.
  public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) {
    checkArgument(
        others.length <= Integer.MAX_VALUE - 6, "the total number of elements must fit in an int");
    final int paramCount = 6;
    Object[] elements = new Object[paramCount + others.length];
    elements[0] = e1;
    elements[1] = e2;
    elements[2] = e3;
    elements[3] = e4;
    elements[4] = e5;
    elements[5] = e6;
    System.arraycopy(others, 0, elements, paramCount, others.length);
    return construct(elements.length, elements.length, elements);
  }

  /**
   * Constructs an {@code ImmutableSet} from the first {@code n} elements of the specified array,
   * which we have no particular reason to believe does or does not contain duplicates. If {@code k}
   * is the size of the returned {@code ImmutableSet}, then the unique elements of {@code elements}
   * will be in the first {@code k} positions, and {@code elements[i] == null} for {@code k <= i <
   * n}.
   *
   *
This may modify {@code elements}. Additionally, if {@code n == elements.length} and {@code
   * elements} contains no duplicates, {@code elements} may be used without copying in the returned
   * {@code ImmutableSet}, in which case the caller must not modify it.
   *
   *
{@code elements} may contain only values of type {@code E}.
   *
   * @throws NullPointerException if any of the first {@code n} elements of {@code elements} is null
   */
  private static <E> ImmutableSet<E> constructUnknownDuplication(int n, Object... elements) {
    // Guess the size is "halfway between" all duplicates and no duplicates, on a log scale.
    return construct(
        n,
        Math.max(
            ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY,
            IntMath.sqrt(n, RoundingMode.CEILING)),
        elements);
  }

  /**
   * Constructs an {@code ImmutableSet} from the first {@code n} elements of the specified array. If
   * {@code k} is the size of the returned {@code ImmutableSet}, then the unique elements of {@code
   * elements} will be in the first {@code k} positions, and {@code elements[i] == null} for {@code
   * k <= i < n}.
   *
   *
This may modify {@code elements}. Additionally, if {@code n == elements.length} and {@code
   * elements} contains no duplicates, {@code elements} may be used without copying in the returned
   * {@code ImmutableSet}, in which case it may no longer be modified.
   *
   *
{@code elements} may contain only values of type {@code E}.
   *
   * @throws NullPointerException if any of the first {@code n} elements of {@code elements} is null
   */
  private static <E> ImmutableSet<E> construct(int n, int expectedSize, Object... elements) {
    switch (n) {
      case 0:
        return of();
      case 1:
        @SuppressWarnings("unchecked") // safe; elements contains only E's
        E elem = (E) elements[0];
        return of(elem);
      default:
        SetBuilderImpl<E> builder = new RegularSetBuilderImpl<E>(expectedSize);
        for (int i = 0; i < n; i++) {
          @SuppressWarnings("unchecked")
          E e = (E) checkNotNull(elements[i]);
          builder = builder.add(e);
        }
        return builder.review().build();
    }
  }

  /**
   * Returns an immutable set containing each of {@code elements}, minus duplicates, in the order
   * each appears first in the source collection.
   *
   *
Performance note: This method will sometimes recognize that the actual copy operation
   * is unnecessary; for example, {@code copyOf(copyOf(anArrayList))} will copy the data only once.
   * This reduces the expense of habitually making defensive copies at API boundaries. However, the
   * precise conditions for skipping the copy operation are undefined.
   *
   * @throws NullPointerException if any of {@code elements} is null
   * @since 7.0 (source-compatible since 2.0)
   */
  public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) {
    /*
     * TODO(lowasser): consider checking for ImmutableAsList here
     * TODO(lowasser): consider checking for Multiset here
     */
    // Don't refer to ImmutableSortedSet by name so it won't pull in all that code
    if (elements instanceof ImmutableSet && !(elements instanceof SortedSet)) {
      @SuppressWarnings("unchecked") // all supported methods are covariant
      ImmutableSet<E> set = (ImmutableSet<E>) elements;
      if (!set.isPartialView()) {
        return set;
      }
    } else if (elements instanceof EnumSet) {
      return copyOfEnumSet((EnumSet) elements);
    }
    Object[] array = elements.toArray();
    if (elements instanceof Set) {
      // assume probably no duplicates (though it might be using different equality semantics)
      return construct(array.length, array.length, array);
    } else {
      return constructUnknownDuplication(array.length, array);
    }
  }

  /**
   * Returns an immutable set containing each of {@code elements}, minus duplicates, in the order
   * each appears first in the source iterable. This method iterates over {@code elements} only
   * once.
   *
   *
Performance note: This method will sometimes recognize that the actual copy operation
   * is unnecessary; for example, {@code copyOf(copyOf(anArrayList))} should copy the data only
   * once. This reduces the expense of habitually making defensive copies at API boundaries.
   * However, the precise conditions for skipping the copy operation are undefined.
   *
   * @throws NullPointerException if any of {@code elements} is null
   */
  public static <E> ImmutableSet<E> copyOf(Iterable<? extends E> elements) {
    return (elements instanceof Collection)
        ? copyOf((Collection<? extends E>) elements)
        : copyOf(elements.iterator());
  }

  /**
   * Returns an immutable set containing each of {@code elements}, minus duplicates, in the order
   * each appears first in the source iterator.
   *
   * @throws NullPointerException if any of {@code elements} is null
   */
  public static <E> ImmutableSet<E> copyOf(Iterator<? extends E> elements) {
    // We special-case for 0 or 1 elements, but anything further is madness.
    if (!elements.hasNext()) {
      return of();
    }
    E first = elements.next();
    if (!elements.hasNext()) {
      return of(first);
    } else {
      return new ImmutableSet.Builder<E>().add(first).addAll(elements).build();
    }
  }

  /**
   * Returns an immutable set containing each of {@code elements}, minus duplicates, in the order
   * each appears first in the source array.
   *
   * @throws NullPointerException if any of {@code elements} is null
   * @since 3.0
   */
  public static <E> ImmutableSet<E> copyOf(E[] elements) {
    switch (elements.length) {
      case 0:
        return of();
      case 1:
        return of(elements[0]);
      default:
        return constructUnknownDuplication(elements.length, elements.clone());
    }
  }

  @SuppressWarnings("rawtypes") // necessary to compile against Java 8
  private static ImmutableSet copyOfEnumSet(EnumSet enumSet) {
    return ImmutableEnumSet.asImmutable(EnumSet.copyOf(enumSet));
  }

  ImmutableSet() {}

  /** Returns {@code true} if the {@code hashCode()} method runs quickly. */
  boolean isHashCodeFast() {
    return false;
  }

  @Override
  public boolean equals(@Nullable Object object) {
    if (object == this) {
      return true;
    } else if (object instanceof ImmutableSet
        && isHashCodeFast()
        && ((ImmutableSet<?>) object).isHashCodeFast()
        && hashCode() != object.hashCode()) {
      return false;
    }
    return Sets.equalsImpl(this, object);
  }

  @Override
  public int hashCode() {
    return Sets.hashCodeImpl(this);
  }

  // This declaration is needed to make Set.iterator() and
  // ImmutableCollection.iterator() consistent.
  @Override
  public abstract UnmodifiableIterator<E> iterator();

  @LazyInit @RetainedWith private transient @Nullable ImmutableList<E> asList;

  @Override
  public ImmutableList<E> asList() {
    ImmutableList<E> result = asList;
    return (result == null) ? asList = createAsList() : result;
  }

  ImmutableList<E> createAsList() {
    return new RegularImmutableAsList<E>(this, toArray());
  }

  abstract static class Indexed<E> extends ImmutableSet<E> {
    abstract E get(int index);

    @Override
    public UnmodifiableIterator<E> iterator() {
      return asList().iterator();
    }

    @Override
    public Spliterator<E> spliterator() {
      return CollectSpliterators.indexed(size(), SPLITERATOR_CHARACTERISTICS, this::get);
    }

    @Override
    public void forEach(Consumer<? super E> consumer) {
      checkNotNull(consumer);
      int n = size();
      for (int i = 0; i < n; i++) {
        consumer.accept(get(i));
      }
    }

    @Override
    int copyIntoArray(Object[] dst, int offset) {
      return asList().copyIntoArray(dst, offset);
    }

    @Override
    ImmutableList<E> createAsList() {
      return new ImmutableAsList<E>() {
        @Override
        public E get(int index) {
          return Indexed.this.get(index);
        }

        @Override
        Indexed<E> delegateCollection() {
          return Indexed.this;
        }
      };
    }
  }

  /*
   * This class is used to serialize all ImmutableSet instances, except for
   * ImmutableEnumSet/ImmutableSortedSet, regardless of implementation type. It
   * captures their "logical contents" and they are reconstructed using public
   * static factories. This is necessary to ensure that the existence of a
   * particular implementation type is an implementation detail.
   */
  private static class SerializedForm implements Serializable {
    final Object[] elements;

    SerializedForm(Object[] elements) {
      this.elements = elements;
    }

    Object readResolve() {
      return copyOf(elements);
    }

    private static final long serialVersionUID = 0;
  }

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

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

  /**
   * Returns a new builder, expecting the specified number of distinct elements to be added.
   *
   *
If {@code expectedSize} is exactly the number of distinct elements 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 distinct elements added to the builder.
   *
   * @since 23.1
   */
  @Beta
  public static <E> Builder<E> builderWithExpectedSize(int expectedSize) {
    checkNonnegative(expectedSize, "expectedSize");
    return new Builder<E>(expectedSize);
  }

  /** Builds a new open-addressed hash table from the first n objects in elements. */
  static Object[] rebuildHashTable(int newTableSize, Object[] elements, int n) {
    Object[] hashTable = new Object[newTableSize];
    int mask = hashTable.length - 1;
    for (int i = 0; i < n; i++) {
      Object e = elements[i];
      int j0 = Hashing.smear(e.hashCode());
      for (int j = j0; ; j++) {
        int index = j & mask;
        if (hashTable[index] == null) {
          hashTable[index] = e;
          break;
        }
      }
    }
    return hashTable;
  }

  /**
   * A builder for creating {@code ImmutableSet} instances. Example:
   *
   *
{@code
   * static final ImmutableSet<Color> GOOGLE_COLORS =
   *     ImmutableSet.<Color>builder()
   *         .addAll(WEBSAFE_COLORS)
   *         .add(new Color(0, 191, 255))
   *         .build();
   * }

   *
   *
Elements appear in the resulting set in the same order they were first added to the builder.
   *
   *
Building does not change the state of the builder, so it is still possible to add more
   * elements and to build again.
   *
   * @since 2.0
   */
  public static class Builder<E> extends ImmutableCollection.Builder<E> {
    private SetBuilderImpl<E> impl;
    boolean forceCopy;

    public Builder() {
      this(DEFAULT_INITIAL_CAPACITY);
    }

    Builder(int capacity) {
      impl = new RegularSetBuilderImpl<E>(capacity);
    }

    Builder(@SuppressWarnings("unused") boolean subclass) {
      this.impl = null; // unused
    }

    @VisibleForTesting
    void forceJdk() {
      this.impl = new JdkBackedSetBuilderImpl<E>(impl);
    }

    final void copyIfNecessary() {
      if (forceCopy) {
        copy();
        forceCopy = false;
      }
    }

    void copy() {
      impl = impl.copy();
    }

    @Override
    @CanIgnoreReturnValue
    public Builder<E> add(E element) {
      checkNotNull(element);
      copyIfNecessary();
      impl = impl.add(element);
      return this;
    }

    @Override
    @CanIgnoreReturnValue
    public Builder<E> add(E... elements) {
      super.add(elements);
      return this;
    }

    @Override
    /**
     * Adds each element of {@code elements} to the {@code ImmutableSet}, ignoring duplicate
     * elements (only the first duplicate element is added).
     *
     * @param elements the elements to add
     * @return this {@code Builder} object
     * @throws NullPointerException if {@code elements} is null or contains a null element
     */
    @CanIgnoreReturnValue
    public Builder<E> addAll(Iterable<? extends E> elements) {
      super.addAll(elements);
      return this;
    }

    @Override
    @CanIgnoreReturnValue
    public Builder<E> addAll(Iterator<? extends E> elements) {
      super.addAll(elements);
      return this;
    }

    Builder<E> combine(Builder<E> other) {
      copyIfNecessary();
      this.impl = this.impl.combine(other.impl);
      return this;
    }

    @Override
    public ImmutableSet<E> build() {
      forceCopy = true;
      impl = impl.review();
      return impl.build();
    }
  }

  /** Swappable internal implementation of an ImmutableSet.Builder. */
  private abstract static class SetBuilderImpl<E> {
    E[] dedupedElements;
    int distinct;

    @SuppressWarnings("unchecked")
    SetBuilderImpl(int expectedCapacity) {
      this.dedupedElements = (E[]) new Object[expectedCapacity];
      this.distinct = 0;
    }

    /** Initializes this SetBuilderImpl with a copy of the deduped elements array from toCopy. */
    SetBuilderImpl(SetBuilderImpl<E> toCopy) {
      this.dedupedElements = Arrays.copyOf(toCopy.dedupedElements, toCopy.dedupedElements.length);
      this.distinct = toCopy.distinct;
    }

    /**
     * Resizes internal data structures if necessary to store the specified number of distinct
     * elements.
     */
    private void ensureCapacity(int minCapacity) {
      if (minCapacity > dedupedElements.length) {
        int newCapacity =
            ImmutableCollection.Builder.expandedCapacity(dedupedElements.length, minCapacity);
        dedupedElements = Arrays.copyOf(dedupedElements, newCapacity);
      }
    }

    /** Adds e to the insertion-order array of deduplicated elements. Calls ensureCapacity. */
    final void addDedupedElement(E e) {
      ensureCapacity(distinct + 1);
      dedupedElements[distinct++] = e;
    }

    /**
     * Adds e to this SetBuilderImpl, returning the updated result. Only use the returned
     * SetBuilderImpl, since we may switch implementations if e.g. hash flooding is detected.
     */
    abstract SetBuilderImpl<E> add(E e);

    /** Adds all the elements from the specified SetBuilderImpl to this SetBuilderImpl. */
    final SetBuilderImpl<E> combine(SetBuilderImpl<E> other) {
      SetBuilderImpl<E> result = this;
      for (int i = 0; i < other.distinct; i++) {
        result = result.add(other.dedupedElements[i]);
      }
      return result;
    }

    /**
     * Creates a new copy of this SetBuilderImpl. Modifications to that SetBuilderImpl will not
     * affect this SetBuilderImpl or sets constructed from this SetBuilderImpl via build().
     */
    abstract SetBuilderImpl<E> copy();

    /**
     * Call this before build(). Does a final check on the internal data structures, e.g. shrinking
     * unnecessarily large structures or detecting previously unnoticed hash flooding.
     */
    SetBuilderImpl<E> review() {
      return this;
    }

    abstract ImmutableSet<E> build();
  }

  // We use power-of-2 tables, and this is the highest int that's a power of 2
  static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO;

  // Represents how tightly we can pack things, as a maximum.
  private static final double DESIRED_LOAD_FACTOR = 0.7;

  // If the set has this many elements, it will "max out" the table size
  private static final int CUTOFF = (int) (MAX_TABLE_SIZE * DESIRED_LOAD_FACTOR);

  /**
   * Returns an array size suitable for the backing array of a hash table that uses open addressing
   * with linear probing in its implementation. The returned size is the smallest power of two that
   * can hold setSize elements with the desired load factor. Always returns at least setSize + 2.
   */
  @VisibleForTesting
  static int chooseTableSize(int setSize) {
    setSize = Math.max(setSize, 2);
    // Correct the size for open addressing to match desired load factor.
    if (setSize < CUTOFF) {
      // Round up to the next highest power of 2.
      int tableSize = Integer.highestOneBit(setSize - 1) << 1;
      while (tableSize * DESIRED_LOAD_FACTOR < setSize) {
        tableSize <<= 1;
      }
      return tableSize;
    }

    // The table can't be completely full or we'll get infinite reprobes
    checkArgument(setSize < MAX_TABLE_SIZE, "collection too large");
    return MAX_TABLE_SIZE;
  }

  /**
   * We attempt to detect deliberate hash flooding attempts, and if one is detected, fall back to a
   * wrapper around j.u.HashSet, which has built in flooding protection. HASH_FLOODING_FPP is the
   * maximum allowed probability of falsely detecting a hash flooding attack if the input is
   * randomly generated.
   *
   *
MAX_RUN_MULTIPLIER was determined experimentally to match this FPP.
   */
  static final double HASH_FLOODING_FPP = 0.001;

  // NB: yes, this is surprisingly high, but that's what the experiments said was necessary
  // The higher it is, the worse constant factors we are willing to accept.
  static final int MAX_RUN_MULTIPLIER = 13;

  /**
   * Checks the whole hash table for poor hash distribution. Takes O(n) in the worst case, O(n / log
   * n) on average.
   *
   *
The online hash flooding detecting in RegularSetBuilderImpl.add can detect e.g. many exactly
   * matching hash codes, which would cause construction to take O(n^2), but can't detect e.g. hash
   * codes adversarially designed to go into ascending table locations, which keeps construction
   * O(n) (as desired) but then can have O(n) queries later.
   *
   *
If this returns false, then no query can take more than O(log n).
   *
   *
Note that for a RegularImmutableSet with elements with truly random hash codes, contains
   * operations take expected O(1) time but with high probability take O(log n) for at least some
   * element. (https://en.wikipedia.org/wiki/Linear_probing#Analysis)
   *
   *
This method may return {@code true} up to {@link #HASH_FLOODING_FPP} of the time even on
   * truly random input.
   *
   *
If this method returns false, there are definitely no runs of length at least {@code
   * maxRunBeforeFallback(hashTable.length)} nonnull elements. If there are no runs of length at
   * least {@code maxRunBeforeFallback(hashTable.length) / 2} nonnull elements, this method
   * definitely returns false. In between those constraints, the result of this method is undefined,
   * subject to the above {@link #HASH_FLOODING_FPP} constraint.
   */
  static boolean hashFloodingDetected(Object[] hashTable) {
    int maxRunBeforeFallback = maxRunBeforeFallback(hashTable.length);

    // Test for a run wrapping around the end of the table of length at least maxRunBeforeFallback.
    int endOfStartRun;
    for (endOfStartRun = 0; endOfStartRun < hashTable.length; ) {
      if (hashTable[endOfStartRun] == null) {
        break;
      }
      endOfStartRun++;
      if (endOfStartRun > maxRunBeforeFallback) {
        return true;
      }
    }
    int startOfEndRun;
    for (startOfEndRun = hashTable.length - 1; startOfEndRun > endOfStartRun; startOfEndRun--) {
      if (hashTable[startOfEndRun] == null) {
        break;
      }
      if (endOfStartRun + (hashTable.length - 1 - startOfEndRun) > maxRunBeforeFallback) {
        return true;
      }
    }

    // Now, break the remainder of the table into blocks of maxRunBeforeFallback/2 elements and
    // check that each has at least one null.
    int testBlockSize = maxRunBeforeFallback / 2;
    blockLoop:
    for (int i = endOfStartRun + 1; i + testBlockSize <= startOfEndRun; i += testBlockSize) {
      for (int j = 0; j < testBlockSize; j++) {
        if (hashTable[i + j] == null) {
          continue blockLoop;
        }
      }
      return true;
    }
    return false;
  }

  /**
   * If more than this many consecutive positions are filled in a table of the specified size,
   * report probable hash flooding. ({@link #hashFloodingDetected} may also report hash flooding if
   * fewer consecutive positions are filled; see that method for details.)
   */
  private static int maxRunBeforeFallback(int tableSize) {
    return MAX_RUN_MULTIPLIER * IntMath.log2(tableSize, RoundingMode.UNNECESSARY);
  }

  /**
   * Default implementation of the guts of ImmutableSet.Builder, creating an open-addressed hash
   * table and deduplicating elements as they come, so it only allocates O(max(distinct,
   * expectedCapacity)) rather than O(calls to add).
   *
   *
This implementation attempts to detect hash flooding, and if it's identified, falls back to
   * JdkBackedSetBuilderImpl.
   */
  private static final class RegularSetBuilderImpl<E> extends SetBuilderImpl<E> {
    private Object[] hashTable;
    private int maxRunBeforeFallback;
    private int expandTableThreshold;
    private int hashCode;

    RegularSetBuilderImpl(int expectedCapacity) {
      super(expectedCapacity);
      int tableSize = chooseTableSize(expectedCapacity);
      this.hashTable = new Object[tableSize];
      this.maxRunBeforeFallback = maxRunBeforeFallback(tableSize);
      this.expandTableThreshold = (int) (DESIRED_LOAD_FACTOR * tableSize);
    }

    RegularSetBuilderImpl(RegularSetBuilderImpl<E> toCopy) {
      super(toCopy);
      this.hashTable = Arrays.copyOf(toCopy.hashTable, toCopy.hashTable.length);
      this.maxRunBeforeFallback = toCopy.maxRunBeforeFallback;
      this.expandTableThreshold = toCopy.expandTableThreshold;
      this.hashCode = toCopy.hashCode;
    }

    void ensureTableCapacity(int minCapacity) {
      if (minCapacity > expandTableThreshold && hashTable.length < MAX_TABLE_SIZE) {
        int newTableSize = hashTable.length * 2;
        hashTable = rebuildHashTable(newTableSize, dedupedElements, distinct);
        maxRunBeforeFallback = maxRunBeforeFallback(newTableSize);
        expandTableThreshold = (int) (DESIRED_LOAD_FACTOR * newTableSize);
      }
    }

    @Override
    SetBuilderImpl<E> add(E e) {
      checkNotNull(e);
      int eHash = e.hashCode();
      int i0 = Hashing.smear(eHash);
      int mask = hashTable.length - 1;
      for (int i = i0; i - i0 < maxRunBeforeFallback; i++) {
        int index = i & mask;
        Object tableEntry = hashTable[index];
        if (tableEntry == null) {
          addDedupedElement(e);
          hashTable[index] = e;
          hashCode += eHash;
          ensureTableCapacity(distinct); // rebuilds table if necessary
          return this;
        } else if (tableEntry.equals(e)) { // not a new element, ignore
          return this;
        }
      }
      // we fell out of the loop due to a long run; fall back to JDK impl
      return new JdkBackedSetBuilderImpl<E>(this).add(e);
    }

    @Override
    SetBuilderImpl<E> copy() {
      return new RegularSetBuilderImpl<E>(this);
    }

    @Override
    SetBuilderImpl<E> review() {
      int targetTableSize = chooseTableSize(distinct);
      if (targetTableSize * 2 < hashTable.length) {
        hashTable = rebuildHashTable(targetTableSize, dedupedElements, distinct);
      }
      return hashFloodingDetected(hashTable) ? new JdkBackedSetBuilderImpl<E>(this) : this;
    }

    @Override
    ImmutableSet<E> build() {
      switch (distinct) {
        case 0:
          return of();
        case 1:
          return of(dedupedElements[0]);
        default:
          Object[] elements =
              (distinct == dedupedElements.length)
                  ? dedupedElements
                  : Arrays.copyOf(dedupedElements, distinct);
          return new RegularImmutableSet<E>(elements, hashCode, hashTable, hashTable.length - 1);
      }
    }
  }

  /**
   * SetBuilderImpl version that uses a JDK HashSet, which has built in hash flooding protection.
   */
  private static final class JdkBackedSetBuilderImpl<E> extends SetBuilderImpl<E> {
    private final Set<Object> delegate;

    JdkBackedSetBuilderImpl(SetBuilderImpl<E> toCopy) {
      super(toCopy); // initializes dedupedElements and distinct
      delegate = Sets.newHashSetWithExpectedSize(distinct);
      for (int i = 0; i < distinct; i++) {
        delegate.add(dedupedElements[i]);
      }
    }

    @Override
    SetBuilderImpl<E> add(E e) {
      checkNotNull(e);
      if (delegate.add(e)) {
        addDedupedElement(e);
      }
      return this;
    }

    @Override
    SetBuilderImpl<E> copy() {
      return new JdkBackedSetBuilderImpl<>(this);
    }

    @Override
    ImmutableSet<E> build() {
      switch (distinct) {
        case 0:
          return of();
        case 1:
          return of(dedupedElements[0]);
        default:
          return new JdkBackedImmutableSet<E>(
              delegate, ImmutableList.asImmutableList(dedupedElements, distinct));
      }
    }
  }
}