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    
015    package com.google.common.collect;
016    
017    import static com.google.common.base.Preconditions.checkArgument;
018    import static com.google.common.base.Preconditions.checkNotNull;
019    
020    import com.google.common.annotations.Beta;
021    import com.google.common.annotations.GwtCompatible;
022    import com.google.common.annotations.GwtIncompatible;
023    
024    import java.util.Collections;
025    import java.util.NoSuchElementException;
026    import 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(Ranges.greaterThan(0), DiscreteDomains.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
042    public 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(Ranges.atLeast(domain.minValue()));
060          }
061          if (!range.hasUpperBound()) {
062            effectiveRange = effectiveRange.intersection(Ranges.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 public ContiguousSet<C> headSet(C toElement) {
087        return headSetImpl(checkNotNull(toElement), false);
088      }
089    
090      /**
091       * @since 12.0
092       */
093      @GwtIncompatible("NavigableSet")
094      @Override public ContiguousSet<C> headSet(C toElement, boolean inclusive) {
095        return headSetImpl(checkNotNull(toElement), inclusive);
096      }
097    
098      @Override public ContiguousSet<C> subSet(C fromElement, C toElement) {
099        checkNotNull(fromElement);
100        checkNotNull(toElement);
101        checkArgument(comparator().compare(fromElement, toElement) <= 0);
102        return subSetImpl(fromElement, true, toElement, false);
103      }
104    
105      /**
106       * @since 12.0
107       */
108      @GwtIncompatible("NavigableSet")
109      @Override public ContiguousSet<C> subSet(C fromElement, boolean fromInclusive, C toElement,
110          boolean toInclusive) {
111        checkNotNull(fromElement);
112        checkNotNull(toElement);
113        checkArgument(comparator().compare(fromElement, toElement) <= 0);
114        return subSetImpl(fromElement, fromInclusive, toElement, toInclusive);
115      }
116    
117      @Override public ContiguousSet<C> tailSet(C fromElement) {
118        return tailSetImpl(checkNotNull(fromElement), true);
119      }
120    
121      /**
122       * @since 12.0
123       */
124      @GwtIncompatible("NavigableSet")
125      @Override public ContiguousSet<C> tailSet(C fromElement, boolean inclusive) {
126        return tailSetImpl(checkNotNull(fromElement), inclusive);
127      }
128    
129      /*
130       * These methods perform most headSet, subSet, and tailSet logic, besides parameter validation.
131       */
132      /*@Override*/ abstract ContiguousSet<C> headSetImpl(C toElement, boolean inclusive);
133    
134      /*@Override*/ abstract ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive,
135          C toElement, boolean toInclusive);
136    
137      /*@Override*/ abstract ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive);
138    
139      /**
140       * Returns the set of values that are contained in both this set and the other.
141       *
142       * <p>This method should always be used instead of
143       * {@link Sets#intersection} for {@link ContiguousSet} instances.
144       */
145      public abstract ContiguousSet<C> intersection(ContiguousSet<C> other);
146    
147      /**
148       * Returns a range, closed on both ends, whose endpoints are the minimum and maximum values
149       * contained in this set.  This is equivalent to {@code range(CLOSED, CLOSED)}.
150       *
151       * @throws NoSuchElementException if this set is empty
152       */
153      public abstract Range<C> range();
154    
155      /**
156       * Returns the minimal range with the given boundary types for which all values in this set are
157       * {@linkplain Range#contains(Comparable) contained} within the range.
158       *
159       * <p>Note that this method will return ranges with unbounded endpoints if {@link BoundType#OPEN}
160       * is requested for a domain minimum or maximum.  For example, if {@code set} was created from the
161       * range {@code [1..Integer.MAX_VALUE]} then {@code set.range(CLOSED, OPEN)} must return
162       * {@code [1..∞)}.
163       *
164       * @throws NoSuchElementException if this set is empty
165       */
166      public abstract Range<C> range(BoundType lowerBoundType, BoundType upperBoundType);
167    
168      /** Returns a short-hand representation of the contents such as {@code "[1..100]"}. */
169      @Override public String toString() {
170        return range().toString();
171      }
172    }