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  @SuppressWarnings("MissingOverride") // Supermethod does not exist under GWT.
195  abstract ContiguousSet<C> headSetImpl(C toElement, boolean inclusive);
196
197  @SuppressWarnings("MissingOverride") // Supermethod does not exist under GWT.
198  abstract ContiguousSet<C> subSetImpl(
199      C fromElement, boolean fromInclusive, C toElement, boolean toInclusive);
200
201  @SuppressWarnings("MissingOverride") // Supermethod does not exist under GWT.
202  abstract ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive);
203
204  /**
205   * Returns the set of values that are contained in both this set and the other.
206   *
207   * <p>This method should always be used instead of {@link Sets#intersection} for {@link
208   * ContiguousSet} instances.
209   */
210  public abstract ContiguousSet<C> intersection(ContiguousSet<C> other);
211
212  /**
213   * Returns a range, closed on both ends, whose endpoints are the minimum and maximum values
214   * contained in this set. This is equivalent to {@code range(CLOSED, CLOSED)}.
215   *
216   * @throws NoSuchElementException if this set is empty
217   */
218  public abstract Range<C> range();
219
220  /**
221   * Returns the minimal range with the given boundary types for which all values in this set are
222   * {@linkplain Range#contains(Comparable) contained} within the range.
223   *
224   * <p>Note that this method will return ranges with unbounded endpoints if {@link BoundType#OPEN}
225   * is requested for a domain minimum or maximum. For example, if {@code set} was created from the
226   * range {@code [1..Integer.MAX_VALUE]} then {@code set.range(CLOSED, OPEN)} must return {@code
227   * [1..∞)}.
228   *
229   * @throws NoSuchElementException if this set is empty
230   */
231  public abstract Range<C> range(BoundType lowerBoundType, BoundType upperBoundType);
232
233  @Override
234  @GwtIncompatible // NavigableSet
235  ImmutableSortedSet<C> createDescendingSet() {
236    return new DescendingImmutableSortedSet<C>(this);
237  }
238
239  /** Returns a short-hand representation of the contents such as {@code "[1..100]"}. */
240  @Override
241  public String toString() {
242    return range().toString();
243  }
244
245  /**
246   * Not supported. {@code ContiguousSet} instances are constructed with {@link #create}. This
247   * method exists only to hide {@link ImmutableSet#builder} from consumers of {@code
248   * ContiguousSet}.
249   *
250   * @throws UnsupportedOperationException always
251   * @deprecated Use {@link #create}.
252   */
253  @Deprecated
254  public static <E> ImmutableSortedSet.Builder<E> builder() {
255    throw new UnsupportedOperationException();
256  }
257}