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 = effectiveRange.isEmpty()
070        || Range.compareOrThrow(
071            range.lowerBound.leastValueAbove(domain),
072            range.upperBound.greatestValueBelow(domain)) > 0;
073
074    return empty
075        ? new EmptyContiguousSet<C>(domain)
076        : new RegularContiguousSet<C>(effectiveRange, domain);
077  }
078
079  final DiscreteDomain<C> domain;
080
081  ContiguousSet(DiscreteDomain<C> domain) {
082    super(Ordering.natural());
083    this.domain = domain;
084  }
085
086  @Override
087  public ContiguousSet<C> headSet(C toElement) {
088    return headSetImpl(checkNotNull(toElement), false);
089  }
090
091  /**
092   * @since 12.0
093   */
094  @GwtIncompatible("NavigableSet")
095  @Override
096  public ContiguousSet<C> headSet(C toElement, boolean inclusive) {
097    return headSetImpl(checkNotNull(toElement), inclusive);
098  }
099
100  @Override
101  public ContiguousSet<C> subSet(C fromElement, C toElement) {
102    checkNotNull(fromElement);
103    checkNotNull(toElement);
104    checkArgument(comparator().compare(fromElement, toElement) <= 0);
105    return subSetImpl(fromElement, true, toElement, false);
106  }
107
108  /**
109   * @since 12.0
110   */
111  @GwtIncompatible("NavigableSet")
112  @Override
113  public ContiguousSet<C> subSet(
114      C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) {
115    checkNotNull(fromElement);
116    checkNotNull(toElement);
117    checkArgument(comparator().compare(fromElement, toElement) <= 0);
118    return subSetImpl(fromElement, fromInclusive, toElement, toInclusive);
119  }
120
121  @Override
122  public ContiguousSet<C> tailSet(C fromElement) {
123    return tailSetImpl(checkNotNull(fromElement), true);
124  }
125
126  /**
127   * @since 12.0
128   */
129  @GwtIncompatible("NavigableSet")
130  @Override
131  public ContiguousSet<C> tailSet(C fromElement, boolean inclusive) {
132    return tailSetImpl(checkNotNull(fromElement), inclusive);
133  }
134
135  /*
136   * These methods perform most headSet, subSet, and tailSet logic, besides parameter validation.
137   */
138  // TODO(kevinb): we can probably make these real @Overrides now
139  /*@Override*/
140  abstract ContiguousSet<C> headSetImpl(C toElement, boolean inclusive);
141
142  /*@Override*/
143  abstract ContiguousSet<C> subSetImpl(
144      C fromElement, boolean fromInclusive, C toElement, boolean toInclusive);
145
146  /*@Override*/
147  abstract ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive);
148
149  /**
150   * Returns the set of values that are contained in both this set and the other.
151   *
152   * <p>This method should always be used instead of
153   * {@link Sets#intersection} for {@link ContiguousSet} instances.
154   */
155  public abstract ContiguousSet<C> intersection(ContiguousSet<C> other);
156
157  /**
158   * Returns a range, closed on both ends, whose endpoints are the minimum and maximum values
159   * contained in this set.  This is equivalent to {@code range(CLOSED, CLOSED)}.
160   *
161   * @throws NoSuchElementException if this set is empty
162   */
163  public abstract Range<C> range();
164
165  /**
166   * Returns the minimal range with the given boundary types for which all values in this set are
167   * {@linkplain Range#contains(Comparable) contained} within the range.
168   *
169   * <p>Note that this method will return ranges with unbounded endpoints if {@link BoundType#OPEN}
170   * is requested for a domain minimum or maximum.  For example, if {@code set} was created from the
171   * range {@code [1..Integer.MAX_VALUE]} then {@code set.range(CLOSED, OPEN)} must return
172   * {@code [1..∞)}.
173   *
174   * @throws NoSuchElementException if this set is empty
175   */
176  public abstract Range<C> range(BoundType lowerBoundType, BoundType upperBoundType);
177
178  /** Returns a short-hand representation of the contents such as {@code "[1..100]"}. */
179  @Override
180  public String toString() {
181    return range().toString();
182  }
183
184  /**
185   * Not supported. {@code ContiguousSet} instances are constructed with {@link #create}. This
186   * method exists only to hide {@link ImmutableSet#builder} from consumers of {@code
187   * ContiguousSet}.
188   *
189   * @throws UnsupportedOperationException always
190   * @deprecated Use {@link #create}.
191   */
192  @Deprecated
193  public static <E> ImmutableSortedSet.Builder<E> builder() {
194    throw new UnsupportedOperationException();
195  }
196}