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.base.Preconditions.checkArgument;
020
021import com.google.common.annotations.Beta;
022import com.google.common.annotations.GwtCompatible;
023import java.util.Comparator;
024import java.util.NoSuchElementException;
025import java.util.SortedMap;
026import javax.annotation.CheckForNull;
027import org.checkerframework.checker.nullness.qual.Nullable;
028
029/**
030 * A sorted map which forwards all its method calls to another sorted map. Subclasses should
031 * override one or more methods to modify the behavior of the backing sorted map as desired per the
032 * <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
033 *
034 * <p><b>Warning:</b> The methods of {@code ForwardingSortedMap} forward <i>indiscriminately</i> to
035 * the methods of the delegate. For example, overriding {@link #put} alone <i>will not</i> change
036 * the behavior of {@link #putAll}, which can lead to unexpected behavior. In this case, you should
037 * override {@code putAll} as well, either providing your own implementation, or delegating to the
038 * provided {@code standardPutAll} method.
039 *
040 * <p><b>{@code default} method warning:</b> This class does <i>not</i> forward calls to {@code
041 * default} methods. Instead, it inherits their default implementations. When those implementations
042 * invoke methods, they invoke methods on the {@code ForwardingSortedMap}.
043 *
044 * <p>Each of the {@code standard} methods, where appropriate, use the comparator of the map to test
045 * equality for both keys and values, unlike {@code ForwardingMap}.
046 *
047 * <p>The {@code standard} methods and the collection views they return are not guaranteed to be
048 * thread-safe, even when all of the methods that they depend on are thread-safe.
049 *
050 * @author Mike Bostock
051 * @author Louis Wasserman
052 * @since 2.0
053 */
054@GwtCompatible
055@ElementTypesAreNonnullByDefault
056public abstract class ForwardingSortedMap<K extends @Nullable Object, V extends @Nullable Object>
057    extends ForwardingMap<K, V> implements SortedMap<K, V> {
058  // TODO(lowasser): identify places where thread safety is actually lost
059
060  /** Constructor for use by subclasses. */
061  protected ForwardingSortedMap() {}
062
063  @Override
064  protected abstract SortedMap<K, V> delegate();
065
066  @Override
067  @CheckForNull
068  public Comparator<? super K> comparator() {
069    return delegate().comparator();
070  }
071
072  @Override
073  @ParametricNullness
074  public K firstKey() {
075    return delegate().firstKey();
076  }
077
078  @Override
079  public SortedMap<K, V> headMap(@ParametricNullness K toKey) {
080    return delegate().headMap(toKey);
081  }
082
083  @Override
084  @ParametricNullness
085  public K lastKey() {
086    return delegate().lastKey();
087  }
088
089  @Override
090  public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
091    return delegate().subMap(fromKey, toKey);
092  }
093
094  @Override
095  public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) {
096    return delegate().tailMap(fromKey);
097  }
098
099  /**
100   * A sensible implementation of {@link SortedMap#keySet} in terms of the methods of {@code
101   * ForwardingSortedMap}. In many cases, you may wish to override {@link
102   * ForwardingSortedMap#keySet} to forward to this implementation or a subclass thereof.
103   *
104   * @since 15.0
105   */
106  @Beta
107  protected class StandardKeySet extends Maps.SortedKeySet<K, V> {
108    /** Constructor for use by subclasses. */
109    public StandardKeySet() {
110      super(ForwardingSortedMap.this);
111    }
112  }
113
114  // unsafe, but worst case is a CCE or NPE is thrown, which callers will be expecting
115  @SuppressWarnings({"unchecked", "nullness"})
116  static int unsafeCompare(
117      @CheckForNull Comparator<?> comparator, @CheckForNull Object o1, @CheckForNull Object o2) {
118    if (comparator == null) {
119      return ((Comparable<@Nullable Object>) o1).compareTo(o2);
120    } else {
121      return ((Comparator<@Nullable Object>) comparator).compare(o1, o2);
122    }
123  }
124
125  /**
126   * A sensible definition of {@link #containsKey} in terms of the {@code firstKey()} method of
127   * {@link #tailMap}. If you override {@link #tailMap}, you may wish to override {@link
128   * #containsKey} to forward to this implementation.
129   *
130   * @since 7.0
131   */
132  @Override
133  @Beta
134  protected boolean standardContainsKey(@CheckForNull Object key) {
135    try {
136      // any CCE or NPE will be caught
137      @SuppressWarnings({"unchecked", "nullness"})
138      SortedMap<@Nullable Object, V> self = (SortedMap<@Nullable Object, V>) this;
139      Object ceilingKey = self.tailMap(key).firstKey();
140      return unsafeCompare(comparator(), ceilingKey, key) == 0;
141    } catch (ClassCastException | NoSuchElementException | NullPointerException e) {
142      return false;
143    }
144  }
145
146  /**
147   * A sensible default implementation of {@link #subMap(Object, Object)} in terms of {@link
148   * #headMap(Object)} and {@link #tailMap(Object)}. In some situations, you may wish to override
149   * {@link #subMap(Object, Object)} to forward to this implementation.
150   *
151   * @since 7.0
152   */
153  @Beta
154  protected SortedMap<K, V> standardSubMap(K fromKey, K toKey) {
155    checkArgument(unsafeCompare(comparator(), fromKey, toKey) <= 0, "fromKey must be <= toKey");
156    return tailMap(fromKey).headMap(toKey);
157  }
158}