001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.collect.ObjectArrays.checkElementsNotNull;
022
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import com.google.errorprone.annotations.concurrent.LazyInit;
027import java.io.InvalidObjectException;
028import java.io.ObjectInputStream;
029import java.io.Serializable;
030import java.util.Arrays;
031import java.util.Collection;
032import java.util.Collections;
033import java.util.Comparator;
034import java.util.Iterator;
035import java.util.NavigableSet;
036import java.util.SortedSet;
037import java.util.Spliterator;
038import java.util.Spliterators;
039import java.util.function.Consumer;
040import java.util.stream.Collector;
041import org.checkerframework.checker.nullness.qual.Nullable;
042
043/**
044 * A {@link NavigableSet} whose contents will never change, with many other important properties
045 * detailed at {@link ImmutableCollection}.
046 *
047 * <p><b>Warning:</b> as with any sorted collection, you are strongly advised not to use a {@link
048 * Comparator} or {@link Comparable} type whose comparison behavior is <i>inconsistent with
049 * equals</i>. That is, {@code a.compareTo(b)} or {@code comparator.compare(a, b)} should equal zero
050 * <i>if and only if</i> {@code a.equals(b)}. If this advice is not followed, the resulting
051 * collection will not correctly obey its specification.
052 *
053 * <p>See the Guava User Guide article on <a href=
054 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>.
055 *
056 * @author Jared Levy
057 * @author Louis Wasserman
058 * @since 2.0 (implements {@code NavigableSet} since 12.0)
059 */
060// TODO(benyu): benchmark and optimize all creation paths, which are a mess now
061@GwtCompatible(serializable = true, emulated = true)
062@SuppressWarnings("serial") // we're overriding default serialization
063public abstract class ImmutableSortedSet<E> extends ImmutableSortedSetFauxverideShim<E>
064    implements NavigableSet<E>, SortedIterable<E> {
065  static final int SPLITERATOR_CHARACTERISTICS =
066      ImmutableSet.SPLITERATOR_CHARACTERISTICS | Spliterator.SORTED;
067
068  /**
069   * Returns a {@code Collector} that accumulates the input elements into a new {@code
070   * ImmutableSortedSet}, ordered by the specified comparator.
071   *
072   * <p>If the elements contain duplicates (according to the comparator), only the first duplicate
073   * in encounter order will appear in the result.
074   *
075   * @since 21.0
076   */
077  public static <E> Collector<E, ?, ImmutableSortedSet<E>> toImmutableSortedSet(
078      Comparator<? super E> comparator) {
079    return CollectCollectors.toImmutableSortedSet(comparator);
080  }
081
082  static <E> RegularImmutableSortedSet<E> emptySet(Comparator<? super E> comparator) {
083    if (Ordering.natural().equals(comparator)) {
084      return (RegularImmutableSortedSet<E>) RegularImmutableSortedSet.NATURAL_EMPTY_SET;
085    } else {
086      return new RegularImmutableSortedSet<E>(ImmutableList.<E>of(), comparator);
087    }
088  }
089
090  /** Returns the empty immutable sorted set. */
091  public static <E> ImmutableSortedSet<E> of() {
092    return (ImmutableSortedSet<E>) RegularImmutableSortedSet.NATURAL_EMPTY_SET;
093  }
094
095  /** Returns an immutable sorted set containing a single element. */
096  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E element) {
097    return new RegularImmutableSortedSet<E>(ImmutableList.of(element), Ordering.natural());
098  }
099
100  /**
101   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
102   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
103   * one specified is included.
104   *
105   * @throws NullPointerException if any element is null
106   */
107  @SuppressWarnings("unchecked")
108  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2) {
109    return construct(Ordering.natural(), 2, e1, e2);
110  }
111
112  /**
113   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
114   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
115   * one specified is included.
116   *
117   * @throws NullPointerException if any element is null
118   */
119  @SuppressWarnings("unchecked")
120  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2, E e3) {
121    return construct(Ordering.natural(), 3, e1, e2, e3);
122  }
123
124  /**
125   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
126   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
127   * one specified is included.
128   *
129   * @throws NullPointerException if any element is null
130   */
131  @SuppressWarnings("unchecked")
132  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(E e1, E e2, E e3, E e4) {
133    return construct(Ordering.natural(), 4, e1, e2, e3, e4);
134  }
135
136  /**
137   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
138   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
139   * one specified is included.
140   *
141   * @throws NullPointerException if any element is null
142   */
143  @SuppressWarnings("unchecked")
144  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
145      E e1, E e2, E e3, E e4, E e5) {
146    return construct(Ordering.natural(), 5, e1, e2, e3, e4, e5);
147  }
148
149  /**
150   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
151   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
152   * one specified is included.
153   *
154   * @throws NullPointerException if any element is null
155   * @since 3.0 (source-compatible since 2.0)
156   */
157  @SuppressWarnings("unchecked")
158  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> of(
159      E e1, E e2, E e3, E e4, E e5, E e6, E... remaining) {
160    Comparable[] contents = new Comparable[6 + remaining.length];
161    contents[0] = e1;
162    contents[1] = e2;
163    contents[2] = e3;
164    contents[3] = e4;
165    contents[4] = e5;
166    contents[5] = e6;
167    System.arraycopy(remaining, 0, contents, 6, remaining.length);
168    return construct(Ordering.natural(), contents.length, (E[]) contents);
169  }
170
171  // TODO(kevinb): Consider factory methods that reject duplicates
172
173  /**
174   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
175   * When multiple elements are equivalent according to {@link Comparable#compareTo}, only the first
176   * one specified is included.
177   *
178   * @throws NullPointerException if any of {@code elements} is null
179   * @since 3.0
180   */
181  public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf(E[] elements) {
182    return construct(Ordering.natural(), elements.length, elements.clone());
183  }
184
185  /**
186   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
187   * When multiple elements are equivalent according to {@code compareTo()}, only the first one
188   * specified is included. To create a copy of a {@code SortedSet} that preserves the comparator,
189   * call {@link #copyOfSorted} instead. This method iterates over {@code elements} at most once.
190   *
191   * <p>Note that if {@code s} is a {@code Set<String>}, then {@code ImmutableSortedSet.copyOf(s)}
192   * returns an {@code ImmutableSortedSet<String>} containing each of the strings in {@code s},
193   * while {@code ImmutableSortedSet.of(s)} returns an {@code ImmutableSortedSet<Set<String>>}
194   * containing one element (the given set itself).
195   *
196   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
197   * safe to do so. The exact circumstances under which a copy will or will not be performed are
198   * undocumented and subject to change.
199   *
200   * <p>This method is not type-safe, as it may be called on elements that are not mutually
201   * comparable.
202   *
203   * @throws ClassCastException if the elements are not mutually comparable
204   * @throws NullPointerException if any of {@code elements} is null
205   */
206  public static <E> ImmutableSortedSet<E> copyOf(Iterable<? extends E> elements) {
207    // Hack around E not being a subtype of Comparable.
208    // Unsafe, see ImmutableSortedSetFauxverideShim.
209    @SuppressWarnings("unchecked")
210    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
211    return copyOf(naturalOrder, elements);
212  }
213
214  /**
215   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
216   * When multiple elements are equivalent according to {@code compareTo()}, only the first one
217   * specified is included. To create a copy of a {@code SortedSet} that preserves the comparator,
218   * call {@link #copyOfSorted} instead. This method iterates over {@code elements} at most once.
219   *
220   * <p>Note that if {@code s} is a {@code Set<String>}, then {@code ImmutableSortedSet.copyOf(s)}
221   * returns an {@code ImmutableSortedSet<String>} containing each of the strings in {@code s},
222   * while {@code ImmutableSortedSet.of(s)} returns an {@code ImmutableSortedSet<Set<String>>}
223   * containing one element (the given set itself).
224   *
225   * <p><b>Note:</b> Despite what the method name suggests, if {@code elements} is an {@code
226   * ImmutableSortedSet}, it may be returned instead of a copy.
227   *
228   * <p>This method is not type-safe, as it may be called on elements that are not mutually
229   * comparable.
230   *
231   * <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
232   * collection that is currently being modified by another thread.
233   *
234   * @throws ClassCastException if the elements are not mutually comparable
235   * @throws NullPointerException if any of {@code elements} is null
236   * @since 7.0 (source-compatible since 2.0)
237   */
238  public static <E> ImmutableSortedSet<E> copyOf(Collection<? extends E> elements) {
239    // Hack around E not being a subtype of Comparable.
240    // Unsafe, see ImmutableSortedSetFauxverideShim.
241    @SuppressWarnings("unchecked")
242    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
243    return copyOf(naturalOrder, elements);
244  }
245
246  /**
247   * Returns an immutable sorted set containing the given elements sorted by their natural ordering.
248   * When multiple elements are equivalent according to {@code compareTo()}, only the first one
249   * specified is included.
250   *
251   * <p>This method is not type-safe, as it may be called on elements that are not mutually
252   * comparable.
253   *
254   * @throws ClassCastException if the elements are not mutually comparable
255   * @throws NullPointerException if any of {@code elements} is null
256   */
257  public static <E> ImmutableSortedSet<E> copyOf(Iterator<? extends E> elements) {
258    // Hack around E not being a subtype of Comparable.
259    // Unsafe, see ImmutableSortedSetFauxverideShim.
260    @SuppressWarnings("unchecked")
261    Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
262    return copyOf(naturalOrder, elements);
263  }
264
265  /**
266   * Returns an immutable sorted set containing the given elements sorted by the given {@code
267   * Comparator}. When multiple elements are equivalent according to {@code compareTo()}, only the
268   * first one specified is included.
269   *
270   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
271   */
272  public static <E> ImmutableSortedSet<E> copyOf(
273      Comparator<? super E> comparator, Iterator<? extends E> elements) {
274    return new Builder<E>(comparator).addAll(elements).build();
275  }
276
277  /**
278   * Returns an immutable sorted set containing the given elements sorted by the given {@code
279   * Comparator}. When multiple elements are equivalent according to {@code compare()}, only the
280   * first one specified is included. This method iterates over {@code elements} at most once.
281   *
282   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
283   * safe to do so. The exact circumstances under which a copy will or will not be performed are
284   * undocumented and subject to change.
285   *
286   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
287   */
288  public static <E> ImmutableSortedSet<E> copyOf(
289      Comparator<? super E> comparator, Iterable<? extends E> elements) {
290    checkNotNull(comparator);
291    boolean hasSameComparator = SortedIterables.hasSameComparator(comparator, elements);
292
293    if (hasSameComparator && (elements instanceof ImmutableSortedSet)) {
294      @SuppressWarnings("unchecked")
295      ImmutableSortedSet<E> original = (ImmutableSortedSet<E>) elements;
296      if (!original.isPartialView()) {
297        return original;
298      }
299    }
300    @SuppressWarnings("unchecked") // elements only contains E's; it's safe.
301    E[] array = (E[]) Iterables.toArray(elements);
302    return construct(comparator, array.length, array);
303  }
304
305  /**
306   * Returns an immutable sorted set containing the given elements sorted by the given {@code
307   * Comparator}. When multiple elements are equivalent according to {@code compareTo()}, only the
308   * first one specified is included.
309   *
310   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
311   * safe to do so. The exact circumstances under which a copy will or will not be performed are
312   * undocumented and subject to change.
313   *
314   * <p>This method is safe to use even when {@code elements} is a synchronized or concurrent
315   * collection that is currently being modified by another thread.
316   *
317   * @throws NullPointerException if {@code comparator} or any of {@code elements} is null
318   * @since 7.0 (source-compatible since 2.0)
319   */
320  public static <E> ImmutableSortedSet<E> copyOf(
321      Comparator<? super E> comparator, Collection<? extends E> elements) {
322    return copyOf(comparator, (Iterable<? extends E>) elements);
323  }
324
325  /**
326   * Returns an immutable sorted set containing the elements of a sorted set, sorted by the same
327   * {@code Comparator}. That behavior differs from {@link #copyOf(Iterable)}, which always uses the
328   * natural ordering of the elements.
329   *
330   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
331   * safe to do so. The exact circumstances under which a copy will or will not be performed are
332   * undocumented and subject to change.
333   *
334   * <p>This method is safe to use even when {@code sortedSet} is a synchronized or concurrent
335   * collection that is currently being modified by another thread.
336   *
337   * @throws NullPointerException if {@code sortedSet} or any of its elements is null
338   */
339  public static <E> ImmutableSortedSet<E> copyOfSorted(SortedSet<E> sortedSet) {
340    Comparator<? super E> comparator = SortedIterables.comparator(sortedSet);
341    ImmutableList<E> list = ImmutableList.copyOf(sortedSet);
342    if (list.isEmpty()) {
343      return emptySet(comparator);
344    } else {
345      return new RegularImmutableSortedSet<E>(list, comparator);
346    }
347  }
348
349  /**
350   * Constructs an {@code ImmutableSortedSet} from the first {@code n} elements of {@code contents}.
351   * If {@code k} is the size of the returned {@code ImmutableSortedSet}, then the sorted unique
352   * elements are in the first {@code k} positions of {@code contents}, and {@code contents[i] ==
353   * null} for {@code k <= i < n}.
354   *
355   * <p>If {@code k == contents.length}, then {@code contents} may no longer be safe for
356   * modification.
357   *
358   * @throws NullPointerException if any of the first {@code n} elements of {@code contents} is null
359   */
360  static <E> ImmutableSortedSet<E> construct(
361      Comparator<? super E> comparator, int n, E... contents) {
362    if (n == 0) {
363      return emptySet(comparator);
364    }
365    checkElementsNotNull(contents, n);
366    Arrays.sort(contents, 0, n, comparator);
367    int uniques = 1;
368    for (int i = 1; i < n; i++) {
369      E cur = contents[i];
370      E prev = contents[uniques - 1];
371      if (comparator.compare(cur, prev) != 0) {
372        contents[uniques++] = cur;
373      }
374    }
375    Arrays.fill(contents, uniques, n, null);
376    return new RegularImmutableSortedSet<E>(
377        ImmutableList.<E>asImmutableList(contents, uniques), comparator);
378  }
379
380  /**
381   * Returns a builder that creates immutable sorted sets with an explicit comparator. If the
382   * comparator has a more general type than the set being generated, such as creating a {@code
383   * SortedSet<Integer>} with a {@code Comparator<Number>}, use the {@link Builder} constructor
384   * instead.
385   *
386   * @throws NullPointerException if {@code comparator} is null
387   */
388  public static <E> Builder<E> orderedBy(Comparator<E> comparator) {
389    return new Builder<E>(comparator);
390  }
391
392  /**
393   * Returns a builder that creates immutable sorted sets whose elements are ordered by the reverse
394   * of their natural ordering.
395   */
396  public static <E extends Comparable<?>> Builder<E> reverseOrder() {
397    return new Builder<E>(Collections.reverseOrder());
398  }
399
400  /**
401   * Returns a builder that creates immutable sorted sets whose elements are ordered by their
402   * natural ordering. The sorted sets use {@link Ordering#natural()} as the comparator. This method
403   * provides more type-safety than {@link #builder}, as it can be called only for classes that
404   * implement {@link Comparable}.
405   */
406  public static <E extends Comparable<?>> Builder<E> naturalOrder() {
407    return new Builder<E>(Ordering.natural());
408  }
409
410  /**
411   * A builder for creating immutable sorted set instances, especially {@code public static final}
412   * sets ("constant sets"), with a given comparator. Example:
413   *
414   * <pre>{@code
415   * public static final ImmutableSortedSet<Number> LUCKY_NUMBERS =
416   *     new ImmutableSortedSet.Builder<Number>(ODDS_FIRST_COMPARATOR)
417   *         .addAll(SINGLE_DIGIT_PRIMES)
418   *         .add(42)
419   *         .build();
420   * }</pre>
421   *
422   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
423   * multiple sets in series. Each set is a superset of the set created before it.
424   *
425   * @since 2.0
426   */
427  public static final class Builder<E> extends ImmutableSet.Builder<E> {
428    private final Comparator<? super E> comparator;
429    private E[] elements;
430    private int n;
431
432    /**
433     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
434     * ImmutableSortedSet#orderedBy}.
435     */
436    public Builder(Comparator<? super E> comparator) {
437      super(true); // don't construct guts of hash-based set builder
438      this.comparator = checkNotNull(comparator);
439      this.elements = (E[]) new Object[ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY];
440      this.n = 0;
441    }
442
443    @Override
444    void copy() {
445      elements = Arrays.copyOf(elements, elements.length);
446    }
447
448    private void sortAndDedup() {
449      if (n == 0) {
450        return;
451      }
452      Arrays.sort(elements, 0, n, comparator);
453      int unique = 1;
454      for (int i = 1; i < n; i++) {
455        int cmp = comparator.compare(elements[unique - 1], elements[i]);
456        if (cmp < 0) {
457          elements[unique++] = elements[i];
458        } else if (cmp > 0) {
459          throw new AssertionError(
460              "Comparator " + comparator + " compare method violates its contract");
461        }
462      }
463      Arrays.fill(elements, unique, n, null);
464      n = unique;
465    }
466
467    /**
468     * Adds {@code element} to the {@code ImmutableSortedSet}. If the {@code ImmutableSortedSet}
469     * already contains {@code element}, then {@code add} has no effect. (only the previously added
470     * element is retained).
471     *
472     * @param element the element to add
473     * @return this {@code Builder} object
474     * @throws NullPointerException if {@code element} is null
475     */
476    @CanIgnoreReturnValue
477    @Override
478    public Builder<E> add(E element) {
479      checkNotNull(element);
480      copyIfNecessary();
481      if (n == elements.length) {
482        sortAndDedup();
483        /*
484         * Sorting operations can only be allowed to occur once every O(n) operations to keep
485         * amortized O(n log n) performance.  Therefore, ensure there are at least O(n) *unused*
486         * spaces in the builder array.
487         */
488        int newLength = ImmutableCollection.Builder.expandedCapacity(n, n + 1);
489        if (newLength > elements.length) {
490          elements = Arrays.copyOf(elements, newLength);
491        }
492      }
493      elements[n++] = element;
494      return this;
495    }
496
497    /**
498     * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
499     * elements (only the first duplicate element is added).
500     *
501     * @param elements the elements to add
502     * @return this {@code Builder} object
503     * @throws NullPointerException if {@code elements} contains a null element
504     */
505    @CanIgnoreReturnValue
506    @Override
507    public Builder<E> add(E... elements) {
508      checkElementsNotNull(elements);
509      for (E e : elements) {
510        add(e);
511      }
512      return this;
513    }
514
515    /**
516     * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
517     * elements (only the first duplicate element is added).
518     *
519     * @param elements the elements to add to the {@code ImmutableSortedSet}
520     * @return this {@code Builder} object
521     * @throws NullPointerException if {@code elements} contains a null element
522     */
523    @CanIgnoreReturnValue
524    @Override
525    public Builder<E> addAll(Iterable<? extends E> elements) {
526      super.addAll(elements);
527      return this;
528    }
529
530    /**
531     * Adds each element of {@code elements} to the {@code ImmutableSortedSet}, ignoring duplicate
532     * elements (only the first duplicate element is added).
533     *
534     * @param elements the elements to add to the {@code ImmutableSortedSet}
535     * @return this {@code Builder} object
536     * @throws NullPointerException if {@code elements} contains a null element
537     */
538    @CanIgnoreReturnValue
539    @Override
540    public Builder<E> addAll(Iterator<? extends E> elements) {
541      super.addAll(elements);
542      return this;
543    }
544
545    @CanIgnoreReturnValue
546    @Override
547    Builder<E> combine(ImmutableSet.Builder<E> builder) {
548      copyIfNecessary();
549      Builder<E> other = (Builder<E>) builder;
550      for (int i = 0; i < other.n; i++) {
551        add(other.elements[i]);
552      }
553      return this;
554    }
555
556    /**
557     * Returns a newly-created {@code ImmutableSortedSet} based on the contents of the {@code
558     * Builder} and its comparator.
559     */
560    @Override
561    public ImmutableSortedSet<E> build() {
562      sortAndDedup();
563      if (n == 0) {
564        return emptySet(comparator);
565      } else {
566        forceCopy = true;
567        return new RegularImmutableSortedSet<E>(
568            ImmutableList.asImmutableList(elements, n), comparator);
569      }
570    }
571  }
572
573  int unsafeCompare(Object a, Object b) {
574    return unsafeCompare(comparator, a, b);
575  }
576
577  static int unsafeCompare(Comparator<?> comparator, Object a, Object b) {
578    // Pretend the comparator can compare anything. If it turns out it can't
579    // compare a and b, we should get a CCE on the subsequent line. Only methods
580    // that are spec'd to throw CCE should call this.
581    @SuppressWarnings("unchecked")
582    Comparator<Object> unsafeComparator = (Comparator<Object>) comparator;
583    return unsafeComparator.compare(a, b);
584  }
585
586  final transient Comparator<? super E> comparator;
587
588  ImmutableSortedSet(Comparator<? super E> comparator) {
589    this.comparator = comparator;
590  }
591
592  /**
593   * Returns the comparator that orders the elements, which is {@link Ordering#natural()} when the
594   * natural ordering of the elements is used. Note that its behavior is not consistent with {@link
595   * SortedSet#comparator()}, which returns {@code null} to indicate natural ordering.
596   */
597  @Override
598  public Comparator<? super E> comparator() {
599    return comparator;
600  }
601
602  @Override // needed to unify the iterator() methods in Collection and SortedIterable
603  public abstract UnmodifiableIterator<E> iterator();
604
605  /**
606   * {@inheritDoc}
607   *
608   * <p>This method returns a serializable {@code ImmutableSortedSet}.
609   *
610   * <p>The {@link SortedSet#headSet} documentation states that a subset of a subset throws an
611   * {@link IllegalArgumentException} if passed a {@code toElement} greater than an earlier {@code
612   * toElement}. However, this method doesn't throw an exception in that situation, but instead
613   * keeps the original {@code toElement}.
614   */
615  @Override
616  public ImmutableSortedSet<E> headSet(E toElement) {
617    return headSet(toElement, false);
618  }
619
620  /** @since 12.0 */
621  @Override
622  public ImmutableSortedSet<E> headSet(E toElement, boolean inclusive) {
623    return headSetImpl(checkNotNull(toElement), inclusive);
624  }
625
626  /**
627   * {@inheritDoc}
628   *
629   * <p>This method returns a serializable {@code ImmutableSortedSet}.
630   *
631   * <p>The {@link SortedSet#subSet} documentation states that a subset of a subset throws an {@link
632   * IllegalArgumentException} if passed a {@code fromElement} smaller than an earlier {@code
633   * fromElement}. However, this method doesn't throw an exception in that situation, but instead
634   * keeps the original {@code fromElement}. Similarly, this method keeps the original {@code
635   * toElement}, instead of throwing an exception, if passed a {@code toElement} greater than an
636   * earlier {@code toElement}.
637   */
638  @Override
639  public ImmutableSortedSet<E> subSet(E fromElement, E toElement) {
640    return subSet(fromElement, true, toElement, false);
641  }
642
643  /** @since 12.0 */
644  @GwtIncompatible // NavigableSet
645  @Override
646  public ImmutableSortedSet<E> subSet(
647      E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
648    checkNotNull(fromElement);
649    checkNotNull(toElement);
650    checkArgument(comparator.compare(fromElement, toElement) <= 0);
651    return subSetImpl(fromElement, fromInclusive, toElement, toInclusive);
652  }
653
654  /**
655   * {@inheritDoc}
656   *
657   * <p>This method returns a serializable {@code ImmutableSortedSet}.
658   *
659   * <p>The {@link SortedSet#tailSet} documentation states that a subset of a subset throws an
660   * {@link IllegalArgumentException} if passed a {@code fromElement} smaller than an earlier {@code
661   * fromElement}. However, this method doesn't throw an exception in that situation, but instead
662   * keeps the original {@code fromElement}.
663   */
664  @Override
665  public ImmutableSortedSet<E> tailSet(E fromElement) {
666    return tailSet(fromElement, true);
667  }
668
669  /** @since 12.0 */
670  @Override
671  public ImmutableSortedSet<E> tailSet(E fromElement, boolean inclusive) {
672    return tailSetImpl(checkNotNull(fromElement), inclusive);
673  }
674
675  /*
676   * These methods perform most headSet, subSet, and tailSet logic, besides
677   * parameter validation.
678   */
679  abstract ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive);
680
681  abstract ImmutableSortedSet<E> subSetImpl(
682      E fromElement, boolean fromInclusive, E toElement, boolean toInclusive);
683
684  abstract ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive);
685
686  /** @since 12.0 */
687  @GwtIncompatible // NavigableSet
688  @Override
689  public E lower(E e) {
690    return Iterators.getNext(headSet(e, false).descendingIterator(), null);
691  }
692
693  /** @since 12.0 */
694  @Override
695  public E floor(E e) {
696    return Iterators.getNext(headSet(e, true).descendingIterator(), null);
697  }
698
699  /** @since 12.0 */
700  @Override
701  public E ceiling(E e) {
702    return Iterables.getFirst(tailSet(e, true), null);
703  }
704
705  /** @since 12.0 */
706  @GwtIncompatible // NavigableSet
707  @Override
708  public E higher(E e) {
709    return Iterables.getFirst(tailSet(e, false), null);
710  }
711
712  @Override
713  public E first() {
714    return iterator().next();
715  }
716
717  @Override
718  public E last() {
719    return descendingIterator().next();
720  }
721
722  /**
723   * Guaranteed to throw an exception and leave the set unmodified.
724   *
725   * @since 12.0
726   * @throws UnsupportedOperationException always
727   * @deprecated Unsupported operation.
728   */
729  @CanIgnoreReturnValue
730  @Deprecated
731  @GwtIncompatible // NavigableSet
732  @Override
733  public final E pollFirst() {
734    throw new UnsupportedOperationException();
735  }
736
737  /**
738   * Guaranteed to throw an exception and leave the set unmodified.
739   *
740   * @since 12.0
741   * @throws UnsupportedOperationException always
742   * @deprecated Unsupported operation.
743   */
744  @CanIgnoreReturnValue
745  @Deprecated
746  @GwtIncompatible // NavigableSet
747  @Override
748  public final E pollLast() {
749    throw new UnsupportedOperationException();
750  }
751
752  @GwtIncompatible // NavigableSet
753  @LazyInit
754  transient ImmutableSortedSet<E> descendingSet;
755
756  /** @since 12.0 */
757  @GwtIncompatible // NavigableSet
758  @Override
759  public ImmutableSortedSet<E> descendingSet() {
760    // racy single-check idiom
761    ImmutableSortedSet<E> result = descendingSet;
762    if (result == null) {
763      result = descendingSet = createDescendingSet();
764      result.descendingSet = this;
765    }
766    return result;
767  }
768
769  // Most classes should implement this as new DescendingImmutableSortedSet<E>(this),
770  // but we push down that implementation because ProGuard can't eliminate it even when it's always
771  // overridden.
772  @GwtIncompatible // NavigableSet
773  abstract ImmutableSortedSet<E> createDescendingSet();
774
775  @Override
776  public Spliterator<E> spliterator() {
777    return new Spliterators.AbstractSpliterator<E>(
778        size(), SPLITERATOR_CHARACTERISTICS | Spliterator.SIZED) {
779      final UnmodifiableIterator<E> iterator = iterator();
780
781      @Override
782      public boolean tryAdvance(Consumer<? super E> action) {
783        if (iterator.hasNext()) {
784          action.accept(iterator.next());
785          return true;
786        } else {
787          return false;
788        }
789      }
790
791      @Override
792      public Comparator<? super E> getComparator() {
793        return comparator;
794      }
795    };
796  }
797
798  /** @since 12.0 */
799  @GwtIncompatible // NavigableSet
800  @Override
801  public abstract UnmodifiableIterator<E> descendingIterator();
802
803  /** Returns the position of an element within the set, or -1 if not present. */
804  abstract int indexOf(@Nullable Object target);
805
806  /*
807   * This class is used to serialize all ImmutableSortedSet instances,
808   * regardless of implementation type. It captures their "logical contents"
809   * only. This is necessary to ensure that the existence of a particular
810   * implementation type is an implementation detail.
811   */
812  private static class SerializedForm<E> implements Serializable {
813    final Comparator<? super E> comparator;
814    final Object[] elements;
815
816    public SerializedForm(Comparator<? super E> comparator, Object[] elements) {
817      this.comparator = comparator;
818      this.elements = elements;
819    }
820
821    @SuppressWarnings("unchecked")
822    Object readResolve() {
823      return new Builder<E>(comparator).add((E[]) elements).build();
824    }
825
826    private static final long serialVersionUID = 0;
827  }
828
829  private void readObject(ObjectInputStream unused) throws InvalidObjectException {
830    throw new InvalidObjectException("Use SerializedForm");
831  }
832
833  @Override
834  Object writeReplace() {
835    return new SerializedForm<E>(comparator, toArray());
836  }
837}