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;
023import java.util.Collections;
024import java.util.NoSuchElementException;
025import java.util.Set;
026
027/**
028 * A sorted set of contiguous values in a given {@link DiscreteDomain}. Example:
029 *
030 * <pre>{@code
031 * ContiguousSet.create(Range.closed(5, 42), DiscreteDomain.integers())
032 * }</pre>
033 *
034 * <p>Note that because bounded ranges over {@code int} and {@code long} values are so common, this
035 * particular example can be written as just:
036 *
037 * <pre>{@code
038 * ContiguousSet.closed(5, 42)
039 * }</pre>
040 *
041 * <p><b>Warning:</b> Be extremely careful what you do with conceptually large instances (such as
042 * {@code ContiguousSet.create(Range.greaterThan(0), DiscreteDomain.integers()}). Certain operations
043 * on such a set can be performed efficiently, but others (such as {@link Set#hashCode} or {@link
044 * Collections#frequency}) can cause major performance problems.
045 *
046 * @author Gregory Kick
047 * @since 10.0
048 */
049@GwtCompatible(emulated = true)
050@SuppressWarnings("rawtypes") // allow ungenerified Comparable types
051public abstract class ContiguousSet<C extends Comparable> extends ImmutableSortedSet<C> {
052  /**
053   * Returns a {@code ContiguousSet} containing the same values in the given domain {@linkplain
054   * Range#contains contained} by the range.
055   *
056   * @throws IllegalArgumentException if neither range nor the domain has a lower bound, or if
057   *     neither has an upper bound
058   * @since 13.0
059   */
060  public static <C extends Comparable> ContiguousSet<C> create(
061      Range<C> range, DiscreteDomain<C> domain) {
062    checkNotNull(range);
063    checkNotNull(domain);
064    Range<C> effectiveRange = range;
065    try {
066      if (!range.hasLowerBound()) {
067        effectiveRange = effectiveRange.intersection(Range.atLeast(domain.minValue()));
068      }
069      if (!range.hasUpperBound()) {
070        effectiveRange = effectiveRange.intersection(Range.atMost(domain.maxValue()));
071      }
072    } catch (NoSuchElementException e) {
073      throw new IllegalArgumentException(e);
074    }
075
076    // Per class spec, we are allowed to throw CCE if necessary
077    boolean empty =
078        effectiveRange.isEmpty()
079            || Range.compareOrThrow(
080                    range.lowerBound.leastValueAbove(domain),
081                    range.upperBound.greatestValueBelow(domain))
082                > 0;
083
084    return empty
085        ? new EmptyContiguousSet<C>(domain)
086        : new RegularContiguousSet<C>(effectiveRange, domain);
087  }
088
089  /**
090   * Returns a nonempty contiguous set containing all {@code int} values from {@code lower}
091   * (inclusive) to {@code upper} (inclusive). (These are the same values contained in {@code
092   * Range.closed(lower, upper)}.)
093   *
094   * @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
095   * @since 23.0
096   */
097  @Beta
098  public static ContiguousSet<Integer> closed(int lower, int upper) {
099    return create(Range.closed(lower, upper), DiscreteDomain.integers());
100  }
101
102  /**
103   * Returns a nonempty contiguous set containing all {@code long} values from {@code lower}
104   * (inclusive) to {@code upper} (inclusive). (These are the same values contained in {@code
105   * Range.closed(lower, upper)}.)
106   *
107   * @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
108   * @since 23.0
109   */
110  @Beta
111  public static ContiguousSet<Long> closed(long lower, long upper) {
112    return create(Range.closed(lower, upper), DiscreteDomain.longs());
113  }
114
115  /**
116   * Returns a contiguous set containing all {@code int} values from {@code lower} (inclusive) to
117   * {@code upper} (exclusive). If the endpoints are equal, an empty set is returned. (These are the
118   * same values contained in {@code Range.closedOpen(lower, upper)}.)
119   *
120   * @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
121   * @since 23.0
122   */
123  @Beta
124  public static ContiguousSet<Integer> closedOpen(int lower, int upper) {
125    return create(Range.closedOpen(lower, upper), DiscreteDomain.integers());
126  }
127
128  /**
129   * Returns a contiguous set containing all {@code long} values from {@code lower} (inclusive) to
130   * {@code upper} (exclusive). If the endpoints are equal, an empty set is returned. (These are the
131   * same values contained in {@code Range.closedOpen(lower, upper)}.)
132   *
133   * @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
134   * @since 23.0
135   */
136  @Beta
137  public static ContiguousSet<Long> closedOpen(long lower, long upper) {
138    return create(Range.closedOpen(lower, upper), DiscreteDomain.longs());
139  }
140
141  final DiscreteDomain<C> domain;
142
143  ContiguousSet(DiscreteDomain<C> domain) {
144    super(Ordering.natural());
145    this.domain = domain;
146  }
147
148  @Override
149  public ContiguousSet<C> headSet(C toElement) {
150    return headSetImpl(checkNotNull(toElement), false);
151  }
152
153  /** @since 12.0 */
154  @GwtIncompatible // NavigableSet
155  @Override
156  public ContiguousSet<C> headSet(C toElement, boolean inclusive) {
157    return headSetImpl(checkNotNull(toElement), inclusive);
158  }
159
160  @Override
161  public ContiguousSet<C> subSet(C fromElement, C toElement) {
162    checkNotNull(fromElement);
163    checkNotNull(toElement);
164    checkArgument(comparator().compare(fromElement, toElement) <= 0);
165    return subSetImpl(fromElement, true, toElement, false);
166  }
167
168  /** @since 12.0 */
169  @GwtIncompatible // NavigableSet
170  @Override
171  public ContiguousSet<C> subSet(
172      C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) {
173    checkNotNull(fromElement);
174    checkNotNull(toElement);
175    checkArgument(comparator().compare(fromElement, toElement) <= 0);
176    return subSetImpl(fromElement, fromInclusive, toElement, toInclusive);
177  }
178
179  @Override
180  public ContiguousSet<C> tailSet(C fromElement) {
181    return tailSetImpl(checkNotNull(fromElement), true);
182  }
183
184  /** @since 12.0 */
185  @GwtIncompatible // NavigableSet
186  @Override
187  public ContiguousSet<C> tailSet(C fromElement, boolean inclusive) {
188    return tailSetImpl(checkNotNull(fromElement), inclusive);
189  }
190
191  /*
192   * These methods perform most headSet, subSet, and tailSet logic, besides parameter validation.
193   */
194  // TODO(kevinb): we can probably make these real @Overrides now
195  /* @Override */
196  abstract ContiguousSet<C> headSetImpl(C toElement, boolean inclusive);
197
198  /* @Override */
199  abstract ContiguousSet<C> subSetImpl(
200      C fromElement, boolean fromInclusive, C toElement, boolean toInclusive);
201
202  /* @Override */
203  abstract ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive);
204
205  /**
206   * Returns the set of values that are contained in both this set and the other.
207   *
208   * <p>This method should always be used instead of {@link Sets#intersection} for {@link
209   * ContiguousSet} instances.
210   */
211  public abstract ContiguousSet<C> intersection(ContiguousSet<C> other);
212
213  /**
214   * Returns a range, closed on both ends, whose endpoints are the minimum and maximum values
215   * contained in this set. This is equivalent to {@code range(CLOSED, CLOSED)}.
216   *
217   * @throws NoSuchElementException if this set is empty
218   */
219  public abstract Range<C> range();
220
221  /**
222   * Returns the minimal range with the given boundary types for which all values in this set are
223   * {@linkplain Range#contains(Comparable) contained} within the range.
224   *
225   * <p>Note that this method will return ranges with unbounded endpoints if {@link BoundType#OPEN}
226   * is requested for a domain minimum or maximum. For example, if {@code set} was created from the
227   * range {@code [1..Integer.MAX_VALUE]} then {@code set.range(CLOSED, OPEN)} must return {@code
228   * [1..∞)}.
229   *
230   * @throws NoSuchElementException if this set is empty
231   */
232  public abstract Range<C> range(BoundType lowerBoundType, BoundType upperBoundType);
233
234  @Override
235  @GwtIncompatible // NavigableSet
236  ImmutableSortedSet<C> createDescendingSet() {
237    return new DescendingImmutableSortedSet<C>(this);
238  }
239
240  /** Returns a short-hand representation of the contents such as {@code "[1..100]"}. */
241  @Override
242  public String toString() {
243    return range().toString();
244  }
245
246  /**
247   * Not supported. {@code ContiguousSet} instances are constructed with {@link #create}. This
248   * method exists only to hide {@link ImmutableSet#builder} from consumers of {@code
249   * ContiguousSet}.
250   *
251   * @throws UnsupportedOperationException always
252   * @deprecated Use {@link #create}.
253   */
254  @Deprecated
255  public static <E> ImmutableSortedSet.Builder<E> builder() {
256    throw new UnsupportedOperationException();
257  }
258}