001/*
002 * Copyright (C) 2010 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.collect;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019
020import com.google.common.annotations.Beta;
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.annotations.GwtIncompatible;
023
024import java.util.Collections;
025import java.util.NoSuchElementException;
026import java.util.Set;
027
028/**
029 * A sorted set of contiguous values in a given {@link DiscreteDomain}.
030 *
031 * <p><b>Warning:</b> Be extremely careful what you do with conceptually large instances (such as
032 * {@code ContiguousSet.create(Range.greaterThan(0), DiscreteDomain.integers()}). Certain
033 * operations on such a set can be performed efficiently, but others (such as {@link Set#hashCode}
034 * or {@link Collections#frequency}) can cause major performance problems.
035 *
036 * @author Gregory Kick
037 * @since 10.0
038 */
039@Beta
040@GwtCompatible(emulated = true)
041@SuppressWarnings("rawtypes") // allow ungenerified Comparable types
042public abstract class ContiguousSet<C extends Comparable> extends ImmutableSortedSet<C> {
043  /**
044   * Returns a {@code ContiguousSet} containing the same values in the given domain
045   * {@linkplain Range#contains contained} by the range.
046   *
047   * @throws IllegalArgumentException if neither range nor the domain has a lower bound, or if
048   *     neither has an upper bound
049   *
050   * @since 13.0
051   */
052  public static <C extends Comparable> ContiguousSet<C> create(
053      Range<C> range, DiscreteDomain<C> domain) {
054    checkNotNull(range);
055    checkNotNull(domain);
056    Range<C> effectiveRange = range;
057    try {
058      if (!range.hasLowerBound()) {
059        effectiveRange = effectiveRange.intersection(Range.atLeast(domain.minValue()));
060      }
061      if (!range.hasUpperBound()) {
062        effectiveRange = effectiveRange.intersection(Range.atMost(domain.maxValue()));
063      }
064    } catch (NoSuchElementException e) {
065      throw new IllegalArgumentException(e);
066    }
067
068    // Per class spec, we are allowed to throw CCE if necessary
069    boolean empty =
070        effectiveRange.isEmpty()
071            || Range.compareOrThrow(
072                    range.lowerBound.leastValueAbove(domain),
073                    range.upperBound.greatestValueBelow(domain))
074                > 0;
075
076    return empty
077        ? new EmptyContiguousSet<C>(domain)
078        : new RegularContiguousSet<C>(effectiveRange, domain);
079  }
080
081  final DiscreteDomain<C> domain;
082
083  ContiguousSet(DiscreteDomain<C> domain) {
084    super(Ordering.natural());
085    this.domain = domain;
086  }
087
088  @Override
089  public ContiguousSet<C> headSet(C toElement) {
090    return headSetImpl(checkNotNull(toElement), false);
091  }
092
093  /**
094   * @since 12.0
095   */
096  @GwtIncompatible("NavigableSet")
097  @Override
098  public ContiguousSet<C> headSet(C toElement, boolean inclusive) {
099    return headSetImpl(checkNotNull(toElement), inclusive);
100  }
101
102  @Override
103  public ContiguousSet<C> subSet(C fromElement, C toElement) {
104    checkNotNull(fromElement);
105    checkNotNull(toElement);
106    checkArgument(comparator().compare(fromElement, toElement) <= 0);
107    return subSetImpl(fromElement, true, toElement, false);
108  }
109
110  /**
111   * @since 12.0
112   */
113  @GwtIncompatible("NavigableSet")
114  @Override
115  public ContiguousSet<C> subSet(
116      C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) {
117    checkNotNull(fromElement);
118    checkNotNull(toElement);
119    checkArgument(comparator().compare(fromElement, toElement) <= 0);
120    return subSetImpl(fromElement, fromInclusive, toElement, toInclusive);
121  }
122
123  @Override
124  public ContiguousSet<C> tailSet(C fromElement) {
125    return tailSetImpl(checkNotNull(fromElement), true);
126  }
127
128  /**
129   * @since 12.0
130   */
131  @GwtIncompatible("NavigableSet")
132  @Override
133  public ContiguousSet<C> tailSet(C fromElement, boolean inclusive) {
134    return tailSetImpl(checkNotNull(fromElement), inclusive);
135  }
136
137  /*
138   * These methods perform most headSet, subSet, and tailSet logic, besides parameter validation.
139   */
140  // TODO(kevinb): we can probably make these real @Overrides now
141  /*@Override*/
142  abstract ContiguousSet<C> headSetImpl(C toElement, boolean inclusive);
143
144  /*@Override*/
145  abstract ContiguousSet<C> subSetImpl(
146      C fromElement, boolean fromInclusive, C toElement, boolean toInclusive);
147
148  /*@Override*/
149  abstract ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive);
150
151  /**
152   * Returns the set of values that are contained in both this set and the other.
153   *
154   * <p>This method should always be used instead of
155   * {@link Sets#intersection} for {@link ContiguousSet} instances.
156   */
157  public abstract ContiguousSet<C> intersection(ContiguousSet<C> other);
158
159  /**
160   * Returns a range, closed on both ends, whose endpoints are the minimum and maximum values
161   * contained in this set.  This is equivalent to {@code range(CLOSED, CLOSED)}.
162   *
163   * @throws NoSuchElementException if this set is empty
164   */
165  public abstract Range<C> range();
166
167  /**
168   * Returns the minimal range with the given boundary types for which all values in this set are
169   * {@linkplain Range#contains(Comparable) contained} within the range.
170   *
171   * <p>Note that this method will return ranges with unbounded endpoints if {@link BoundType#OPEN}
172   * is requested for a domain minimum or maximum.  For example, if {@code set} was created from the
173   * range {@code [1..Integer.MAX_VALUE]} then {@code set.range(CLOSED, OPEN)} must return
174   * {@code [1..∞)}.
175   *
176   * @throws NoSuchElementException if this set is empty
177   */
178  public abstract Range<C> range(BoundType lowerBoundType, BoundType upperBoundType);
179
180  /** Returns a short-hand representation of the contents such as {@code "[1..100]"}. */
181  @Override
182  public String toString() {
183    return range().toString();
184  }
185
186  /**
187   * Not supported. {@code ContiguousSet} instances are constructed with {@link #create}. This
188   * method exists only to hide {@link ImmutableSet#builder} from consumers of {@code
189   * ContiguousSet}.
190   *
191   * @throws UnsupportedOperationException always
192   * @deprecated Use {@link #create}.
193   */
194  @Deprecated
195  public static <E> ImmutableSortedSet.Builder<E> builder() {
196    throw new UnsupportedOperationException();
197  }
198}