001/*
002 * Copyright (C) 2007 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.collect.ForwardingSortedMap.unsafeCompare;
020
021import com.google.common.annotations.GwtCompatible;
022import java.util.Comparator;
023import java.util.Iterator;
024import java.util.NoSuchElementException;
025import java.util.SortedSet;
026import org.jspecify.annotations.Nullable;
027
028/**
029 * A sorted set which forwards all its method calls to another sorted set. Subclasses should
030 * override one or more methods to modify the behavior of the backing sorted set as desired per the
031 * <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
032 *
033 * <p><b>Warning:</b> The methods of {@code ForwardingSortedSet} forward <i>indiscriminately</i> to
034 * the methods of the delegate. For example, overriding {@link #add} alone <i>will not</i> change
035 * the behavior of {@link #addAll}, which can lead to unexpected behavior. In this case, you should
036 * override {@code addAll} as well, either providing your own implementation, or delegating to the
037 * provided {@code standardAddAll} method.
038 *
039 * <p><b>{@code default} method warning:</b> This class does <i>not</i> forward calls to {@code
040 * default} methods. Instead, it inherits their default implementations. When those implementations
041 * invoke methods, they invoke methods on the {@code ForwardingSortedSet}.
042 *
043 * <p>Each of the {@code standard} methods, where appropriate, uses the set's comparator (or the
044 * natural ordering of the elements, if there is no comparator) to test element equality. As a
045 * result, if the comparator is not consistent with equals, some of the standard implementations may
046 * violate the {@code Set} contract.
047 *
048 * <p>The {@code standard} methods and the collection views they return are not guaranteed to be
049 * thread-safe, even when all of the methods that they depend on are thread-safe.
050 *
051 * @author Mike Bostock
052 * @author Louis Wasserman
053 * @since 2.0
054 */
055@GwtCompatible
056/*
057 * We provide and encourage use of ForwardingNavigableSet over this class, but we still provide this
058 * one to preserve compatibility.
059 */
060@SuppressWarnings("JdkObsolete")
061public abstract class ForwardingSortedSet<E extends @Nullable Object> extends ForwardingSet<E>
062    implements SortedSet<E> {
063
064  /** Constructor for use by subclasses. */
065  protected ForwardingSortedSet() {}
066
067  @Override
068  protected abstract SortedSet<E> delegate();
069
070  @Override
071  public @Nullable Comparator<? super E> comparator() {
072    return delegate().comparator();
073  }
074
075  @Override
076  @ParametricNullness
077  public E first() {
078    return delegate().first();
079  }
080
081  @Override
082  public SortedSet<E> headSet(@ParametricNullness E toElement) {
083    return delegate().headSet(toElement);
084  }
085
086  @Override
087  @ParametricNullness
088  public E last() {
089    return delegate().last();
090  }
091
092  @Override
093  public SortedSet<E> subSet(@ParametricNullness E fromElement, @ParametricNullness E toElement) {
094    return delegate().subSet(fromElement, toElement);
095  }
096
097  @Override
098  public SortedSet<E> tailSet(@ParametricNullness E fromElement) {
099    return delegate().tailSet(fromElement);
100  }
101
102  /**
103   * A sensible definition of {@link #contains} in terms of the {@code first()} method of {@link
104   * #tailSet}. If you override {@link #tailSet}, you may wish to override {@link #contains} to
105   * forward to this implementation.
106   *
107   * @since 7.0
108   */
109  @Override
110  protected boolean standardContains(@Nullable Object object) {
111    try {
112      // any ClassCastExceptions and NullPointerExceptions are caught
113      @SuppressWarnings({"unchecked", "nullness"})
114      SortedSet<@Nullable Object> self = (SortedSet<@Nullable Object>) this;
115      Object ceiling = self.tailSet(object).first();
116      return unsafeCompare(comparator(), ceiling, object) == 0;
117    } catch (ClassCastException | NoSuchElementException | NullPointerException e) {
118      return false;
119    }
120  }
121
122  /**
123   * A sensible definition of {@link #remove} in terms of the {@code iterator()} method of {@link
124   * #tailSet}. If you override {@link #tailSet}, you may wish to override {@link #remove} to
125   * forward to this implementation.
126   *
127   * @since 7.0
128   */
129  @Override
130  protected boolean standardRemove(@Nullable Object object) {
131    try {
132      // any ClassCastExceptions and NullPointerExceptions are caught
133      @SuppressWarnings({"unchecked", "nullness"})
134      SortedSet<@Nullable Object> self = (SortedSet<@Nullable Object>) this;
135      Iterator<?> iterator = self.tailSet(object).iterator();
136      if (iterator.hasNext()) {
137        Object ceiling = iterator.next();
138        if (unsafeCompare(comparator(), ceiling, object) == 0) {
139          iterator.remove();
140          return true;
141        }
142      }
143    } catch (ClassCastException | NullPointerException e) {
144      return false;
145    }
146    return false;
147  }
148
149  /**
150   * A sensible default implementation of {@link #subSet(Object, Object)} in terms of {@link
151   * #headSet(Object)} and {@link #tailSet(Object)}. In some situations, you may wish to override
152   * {@link #subSet(Object, Object)} to forward to this implementation.
153   *
154   * @since 7.0
155   */
156  protected SortedSet<E> standardSubSet(
157      @ParametricNullness E fromElement, @ParametricNullness E toElement) {
158    return tailSet(fromElement).headSet(toElement);
159  }
160}