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
056public abstract class ForwardingSortedSet<E extends @Nullable Object> extends ForwardingSet<E>
057    implements SortedSet<E> {
058
059  /** Constructor for use by subclasses. */
060  protected ForwardingSortedSet() {}
061
062  @Override
063  protected abstract SortedSet<E> delegate();
064
065  @Override
066  public @Nullable Comparator<? super E> comparator() {
067    return delegate().comparator();
068  }
069
070  @Override
071  @ParametricNullness
072  public E first() {
073    return delegate().first();
074  }
075
076  @Override
077  public SortedSet<E> headSet(@ParametricNullness E toElement) {
078    return delegate().headSet(toElement);
079  }
080
081  @Override
082  @ParametricNullness
083  public E last() {
084    return delegate().last();
085  }
086
087  @Override
088  public SortedSet<E> subSet(@ParametricNullness E fromElement, @ParametricNullness E toElement) {
089    return delegate().subSet(fromElement, toElement);
090  }
091
092  @Override
093  public SortedSet<E> tailSet(@ParametricNullness E fromElement) {
094    return delegate().tailSet(fromElement);
095  }
096
097  /**
098   * A sensible definition of {@link #contains} in terms of the {@code first()} method of {@link
099   * #tailSet}. If you override {@link #tailSet}, you may wish to override {@link #contains} to
100   * forward to this implementation.
101   *
102   * @since 7.0
103   */
104  @Override
105  protected boolean standardContains(@Nullable Object object) {
106    try {
107      // any ClassCastExceptions and NullPointerExceptions are caught
108      @SuppressWarnings({"unchecked", "nullness"})
109      SortedSet<@Nullable Object> self = (SortedSet<@Nullable Object>) this;
110      Object ceiling = self.tailSet(object).first();
111      return unsafeCompare(comparator(), ceiling, object) == 0;
112    } catch (ClassCastException | NoSuchElementException | NullPointerException e) {
113      return false;
114    }
115  }
116
117  /**
118   * A sensible definition of {@link #remove} in terms of the {@code iterator()} method of {@link
119   * #tailSet}. If you override {@link #tailSet}, you may wish to override {@link #remove} to
120   * forward to this implementation.
121   *
122   * @since 7.0
123   */
124  @Override
125  protected boolean standardRemove(@Nullable Object object) {
126    try {
127      // any ClassCastExceptions and NullPointerExceptions are caught
128      @SuppressWarnings({"unchecked", "nullness"})
129      SortedSet<@Nullable Object> self = (SortedSet<@Nullable Object>) this;
130      Iterator<?> iterator = self.tailSet(object).iterator();
131      if (iterator.hasNext()) {
132        Object ceiling = iterator.next();
133        if (unsafeCompare(comparator(), ceiling, object) == 0) {
134          iterator.remove();
135          return true;
136        }
137      }
138    } catch (ClassCastException | NullPointerException e) {
139      return false;
140    }
141    return false;
142  }
143
144  /**
145   * A sensible default implementation of {@link #subSet(Object, Object)} in terms of {@link
146   * #headSet(Object)} and {@link #tailSet(Object)}. In some situations, you may wish to override
147   * {@link #subSet(Object, Object)} to forward to this implementation.
148   *
149   * @since 7.0
150   */
151  protected SortedSet<E> standardSubSet(
152      @ParametricNullness E fromElement, @ParametricNullness E toElement) {
153    return tailSet(fromElement).headSet(toElement);
154  }
155}