001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.base.Equivalence;
023import com.google.common.base.Function;
024import com.google.common.base.Predicate;
025import java.io.Serializable;
026import java.util.Comparator;
027import java.util.Iterator;
028import java.util.NoSuchElementException;
029import java.util.SortedSet;
030import org.checkerframework.checker.nullness.compatqual.NullableDecl;
031
032/**
033 * A range (or "interval") defines the <i>boundaries</i> around a contiguous span of values of some
034 * {@code Comparable} type; for example, "integers from 1 to 100 inclusive." Note that it is not
035 * possible to <i>iterate</i> over these contained values. To do so, pass this range instance and an
036 * appropriate {@link DiscreteDomain} to {@link ContiguousSet#create}.
037 *
038 * <h3>Types of ranges</h3>
039 *
040 * <p>Each end of the range may be bounded or unbounded. If bounded, there is an associated
041 * <i>endpoint</i> value, and the range is considered to be either <i>open</i> (does not include the
042 * endpoint) or <i>closed</i> (includes the endpoint) on that side. With three possibilities on each
043 * side, this yields nine basic types of ranges, enumerated below. (Notation: a square bracket
044 * ({@code [ ]}) indicates that the range is closed on that side; a parenthesis ({@code ( )}) means
045 * it is either open or unbounded. The construct {@code {x | statement}} is read "the set of all
046 * <i>x</i> such that <i>statement</i>.")
047 *
048 * <blockquote>
049 *
050 * <table>
051 * <caption>Range Types</caption>
052 * <tr><th>Notation        <th>Definition               <th>Factory method
053 * <tr><td>{@code (a..b)}  <td>{@code {x | a < x < b}}  <td>{@link Range#open open}
054 * <tr><td>{@code [a..b]}  <td>{@code {x | a <= x <= b}}<td>{@link Range#closed closed}
055 * <tr><td>{@code (a..b]}  <td>{@code {x | a < x <= b}} <td>{@link Range#openClosed openClosed}
056 * <tr><td>{@code [a..b)}  <td>{@code {x | a <= x < b}} <td>{@link Range#closedOpen closedOpen}
057 * <tr><td>{@code (a..+∞)} <td>{@code {x | x > a}}      <td>{@link Range#greaterThan greaterThan}
058 * <tr><td>{@code [a..+∞)} <td>{@code {x | x >= a}}     <td>{@link Range#atLeast atLeast}
059 * <tr><td>{@code (-∞..b)} <td>{@code {x | x < b}}      <td>{@link Range#lessThan lessThan}
060 * <tr><td>{@code (-∞..b]} <td>{@code {x | x <= b}}     <td>{@link Range#atMost atMost}
061 * <tr><td>{@code (-∞..+∞)}<td>{@code {x}}              <td>{@link Range#all all}
062 * </table>
063 *
064 * </blockquote>
065 *
066 * <p>When both endpoints exist, the upper endpoint may not be less than the lower. The endpoints
067 * may be equal only if at least one of the bounds is closed:
068 *
069 * <ul>
070 *   <li>{@code [a..a]} : a singleton range
071 *   <li>{@code [a..a); (a..a]} : {@linkplain #isEmpty empty} ranges; also valid
072 *   <li>{@code (a..a)} : <b>invalid</b>; an exception will be thrown
073 * </ul>
074 *
075 * <h3>Warnings</h3>
076 *
077 * <ul>
078 *   <li>Use immutable value types only, if at all possible. If you must use a mutable type, <b>do
079 *       not</b> allow the endpoint instances to mutate after the range is created!
080 *   <li>Your value type's comparison method should be {@linkplain Comparable consistent with
081 *       equals} if at all possible. Otherwise, be aware that concepts used throughout this
082 *       documentation such as "equal", "same", "unique" and so on actually refer to whether {@link
083 *       Comparable#compareTo compareTo} returns zero, not whether {@link Object#equals equals}
084 *       returns {@code true}.
085 *   <li>A class which implements {@code Comparable<UnrelatedType>} is very broken, and will cause
086 *       undefined horrible things to happen in {@code Range}. For now, the Range API does not
087 *       prevent its use, because this would also rule out all ungenerified (pre-JDK1.5) data types.
088 *       <b>This may change in the future.</b>
089 * </ul>
090 *
091 * <h3>Other notes</h3>
092 *
093 * <ul>
094 *   <li>Instances of this type are obtained using the static factory methods in this class.
095 *   <li>Ranges are <i>convex</i>: whenever two values are contained, all values in between them
096 *       must also be contained. More formally, for any {@code c1 <= c2 <= c3} of type {@code C},
097 *       {@code r.contains(c1) && r.contains(c3)} implies {@code r.contains(c2)}). This means that a
098 *       {@code Range<Integer>} can never be used to represent, say, "all <i>prime</i> numbers from
099 *       1 to 100."
100 *   <li>When evaluated as a {@link Predicate}, a range yields the same result as invoking {@link
101 *       #contains}.
102 *   <li>Terminology note: a range {@code a} is said to be the <i>maximal</i> range having property
103 *       <i>P</i> if, for all ranges {@code b} also having property <i>P</i>, {@code a.encloses(b)}.
104 *       Likewise, {@code a} is <i>minimal</i> when {@code b.encloses(a)} for all {@code b} having
105 *       property <i>P</i>. See, for example, the definition of {@link #intersection intersection}.
106 * </ul>
107 *
108 * <h3>Further reading</h3>
109 *
110 * <p>See the Guava User Guide article on <a
111 * href="https://github.com/google/guava/wiki/RangesExplained">{@code Range}</a>.
112 *
113 * @author Kevin Bourrillion
114 * @author Gregory Kick
115 * @since 10.0
116 */
117@GwtCompatible
118@SuppressWarnings("rawtypes")
119public final class Range<C extends Comparable> extends RangeGwtSerializationDependencies
120    implements Predicate<C>, Serializable {
121
122  static class LowerBoundFn implements Function<Range, Cut> {
123    static final LowerBoundFn INSTANCE = new LowerBoundFn();
124
125    @Override
126    public Cut apply(Range range) {
127      return range.lowerBound;
128    }
129  }
130
131  static class UpperBoundFn implements Function<Range, Cut> {
132    static final UpperBoundFn INSTANCE = new UpperBoundFn();
133
134    @Override
135    public Cut apply(Range range) {
136      return range.upperBound;
137    }
138  }
139
140  @SuppressWarnings("unchecked")
141  static <C extends Comparable<?>> Function<Range<C>, Cut<C>> lowerBoundFn() {
142    return (Function) LowerBoundFn.INSTANCE;
143  }
144
145  @SuppressWarnings("unchecked")
146  static <C extends Comparable<?>> Function<Range<C>, Cut<C>> upperBoundFn() {
147    return (Function) UpperBoundFn.INSTANCE;
148  }
149
150  static <C extends Comparable<?>> Ordering<Range<C>> rangeLexOrdering() {
151    return (Ordering<Range<C>>) (Ordering) RangeLexOrdering.INSTANCE;
152  }
153
154  static <C extends Comparable<?>> Range<C> create(Cut<C> lowerBound, Cut<C> upperBound) {
155    return new Range<C>(lowerBound, upperBound);
156  }
157
158  /**
159   * Returns a range that contains all values strictly greater than {@code lower} and strictly less
160   * than {@code upper}.
161   *
162   * @throws IllegalArgumentException if {@code lower} is greater than <i>or equal to</i> {@code
163   *     upper}
164   * @since 14.0
165   */
166  public static <C extends Comparable<?>> Range<C> open(C lower, C upper) {
167    return create(Cut.aboveValue(lower), Cut.belowValue(upper));
168  }
169
170  /**
171   * Returns a range that contains all values greater than or equal to {@code lower} and less than
172   * or equal to {@code upper}.
173   *
174   * @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
175   * @since 14.0
176   */
177  public static <C extends Comparable<?>> Range<C> closed(C lower, C upper) {
178    return create(Cut.belowValue(lower), Cut.aboveValue(upper));
179  }
180
181  /**
182   * Returns a range that contains all values greater than or equal to {@code lower} and strictly
183   * less than {@code upper}.
184   *
185   * @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
186   * @since 14.0
187   */
188  public static <C extends Comparable<?>> Range<C> closedOpen(C lower, C upper) {
189    return create(Cut.belowValue(lower), Cut.belowValue(upper));
190  }
191
192  /**
193   * Returns a range that contains all values strictly greater than {@code lower} and less than or
194   * equal to {@code upper}.
195   *
196   * @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
197   * @since 14.0
198   */
199  public static <C extends Comparable<?>> Range<C> openClosed(C lower, C upper) {
200    return create(Cut.aboveValue(lower), Cut.aboveValue(upper));
201  }
202
203  /**
204   * Returns a range that contains any value from {@code lower} to {@code upper}, where each
205   * endpoint may be either inclusive (closed) or exclusive (open).
206   *
207   * @throws IllegalArgumentException if {@code lower} is greater than {@code upper}
208   * @since 14.0
209   */
210  public static <C extends Comparable<?>> Range<C> range(
211      C lower, BoundType lowerType, C upper, BoundType upperType) {
212    checkNotNull(lowerType);
213    checkNotNull(upperType);
214
215    Cut<C> lowerBound =
216        (lowerType == BoundType.OPEN) ? Cut.aboveValue(lower) : Cut.belowValue(lower);
217    Cut<C> upperBound =
218        (upperType == BoundType.OPEN) ? Cut.belowValue(upper) : Cut.aboveValue(upper);
219    return create(lowerBound, upperBound);
220  }
221
222  /**
223   * Returns a range that contains all values strictly less than {@code endpoint}.
224   *
225   * @since 14.0
226   */
227  public static <C extends Comparable<?>> Range<C> lessThan(C endpoint) {
228    return create(Cut.<C>belowAll(), Cut.belowValue(endpoint));
229  }
230
231  /**
232   * Returns a range that contains all values less than or equal to {@code endpoint}.
233   *
234   * @since 14.0
235   */
236  public static <C extends Comparable<?>> Range<C> atMost(C endpoint) {
237    return create(Cut.<C>belowAll(), Cut.aboveValue(endpoint));
238  }
239
240  /**
241   * Returns a range with no lower bound up to the given endpoint, which may be either inclusive
242   * (closed) or exclusive (open).
243   *
244   * @since 14.0
245   */
246  public static <C extends Comparable<?>> Range<C> upTo(C endpoint, BoundType boundType) {
247    switch (boundType) {
248      case OPEN:
249        return lessThan(endpoint);
250      case CLOSED:
251        return atMost(endpoint);
252      default:
253        throw new AssertionError();
254    }
255  }
256
257  /**
258   * Returns a range that contains all values strictly greater than {@code endpoint}.
259   *
260   * @since 14.0
261   */
262  public static <C extends Comparable<?>> Range<C> greaterThan(C endpoint) {
263    return create(Cut.aboveValue(endpoint), Cut.<C>aboveAll());
264  }
265
266  /**
267   * Returns a range that contains all values greater than or equal to {@code endpoint}.
268   *
269   * @since 14.0
270   */
271  public static <C extends Comparable<?>> Range<C> atLeast(C endpoint) {
272    return create(Cut.belowValue(endpoint), Cut.<C>aboveAll());
273  }
274
275  /**
276   * Returns a range from the given endpoint, which may be either inclusive (closed) or exclusive
277   * (open), with no upper bound.
278   *
279   * @since 14.0
280   */
281  public static <C extends Comparable<?>> Range<C> downTo(C endpoint, BoundType boundType) {
282    switch (boundType) {
283      case OPEN:
284        return greaterThan(endpoint);
285      case CLOSED:
286        return atLeast(endpoint);
287      default:
288        throw new AssertionError();
289    }
290  }
291
292  private static final Range<Comparable> ALL = new Range<>(Cut.belowAll(), Cut.aboveAll());
293
294  /**
295   * Returns a range that contains every value of type {@code C}.
296   *
297   * @since 14.0
298   */
299  @SuppressWarnings("unchecked")
300  public static <C extends Comparable<?>> Range<C> all() {
301    return (Range) ALL;
302  }
303
304  /**
305   * Returns a range that {@linkplain Range#contains(Comparable) contains} only the given value. The
306   * returned range is {@linkplain BoundType#CLOSED closed} on both ends.
307   *
308   * @since 14.0
309   */
310  public static <C extends Comparable<?>> Range<C> singleton(C value) {
311    return closed(value, value);
312  }
313
314  /**
315   * Returns the minimal range that {@linkplain Range#contains(Comparable) contains} all of the
316   * given values. The returned range is {@linkplain BoundType#CLOSED closed} on both ends.
317   *
318   * @throws ClassCastException if the parameters are not <i>mutually comparable</i>
319   * @throws NoSuchElementException if {@code values} is empty
320   * @throws NullPointerException if any of {@code values} is null
321   * @since 14.0
322   */
323  public static <C extends Comparable<?>> Range<C> encloseAll(Iterable<C> values) {
324    checkNotNull(values);
325    if (values instanceof SortedSet) {
326      SortedSet<? extends C> set = cast(values);
327      Comparator<?> comparator = set.comparator();
328      if (Ordering.natural().equals(comparator) || comparator == null) {
329        return closed(set.first(), set.last());
330      }
331    }
332    Iterator<C> valueIterator = values.iterator();
333    C min = checkNotNull(valueIterator.next());
334    C max = min;
335    while (valueIterator.hasNext()) {
336      C value = checkNotNull(valueIterator.next());
337      min = Ordering.natural().min(min, value);
338      max = Ordering.natural().max(max, value);
339    }
340    return closed(min, max);
341  }
342
343  final Cut<C> lowerBound;
344  final Cut<C> upperBound;
345
346  private Range(Cut<C> lowerBound, Cut<C> upperBound) {
347    this.lowerBound = checkNotNull(lowerBound);
348    this.upperBound = checkNotNull(upperBound);
349    if (lowerBound.compareTo(upperBound) > 0
350        || lowerBound == Cut.<C>aboveAll()
351        || upperBound == Cut.<C>belowAll()) {
352      throw new IllegalArgumentException("Invalid range: " + toString(lowerBound, upperBound));
353    }
354  }
355
356  /** Returns {@code true} if this range has a lower endpoint. */
357  public boolean hasLowerBound() {
358    return lowerBound != Cut.belowAll();
359  }
360
361  /**
362   * Returns the lower endpoint of this range.
363   *
364   * @throws IllegalStateException if this range is unbounded below (that is, {@link
365   *     #hasLowerBound()} returns {@code false})
366   */
367  public C lowerEndpoint() {
368    return lowerBound.endpoint();
369  }
370
371  /**
372   * Returns the type of this range's lower bound: {@link BoundType#CLOSED} if the range includes
373   * its lower endpoint, {@link BoundType#OPEN} if it does not.
374   *
375   * @throws IllegalStateException if this range is unbounded below (that is, {@link
376   *     #hasLowerBound()} returns {@code false})
377   */
378  public BoundType lowerBoundType() {
379    return lowerBound.typeAsLowerBound();
380  }
381
382  /** Returns {@code true} if this range has an upper endpoint. */
383  public boolean hasUpperBound() {
384    return upperBound != Cut.aboveAll();
385  }
386
387  /**
388   * Returns the upper endpoint of this range.
389   *
390   * @throws IllegalStateException if this range is unbounded above (that is, {@link
391   *     #hasUpperBound()} returns {@code false})
392   */
393  public C upperEndpoint() {
394    return upperBound.endpoint();
395  }
396
397  /**
398   * Returns the type of this range's upper bound: {@link BoundType#CLOSED} if the range includes
399   * its upper endpoint, {@link BoundType#OPEN} if it does not.
400   *
401   * @throws IllegalStateException if this range is unbounded above (that is, {@link
402   *     #hasUpperBound()} returns {@code false})
403   */
404  public BoundType upperBoundType() {
405    return upperBound.typeAsUpperBound();
406  }
407
408  /**
409   * Returns {@code true} if this range is of the form {@code [v..v)} or {@code (v..v]}. (This does
410   * not encompass ranges of the form {@code (v..v)}, because such ranges are <i>invalid</i> and
411   * can't be constructed at all.)
412   *
413   * <p>Note that certain discrete ranges such as the integer range {@code (3..4)} are <b>not</b>
414   * considered empty, even though they contain no actual values. In these cases, it may be helpful
415   * to preprocess ranges with {@link #canonical(DiscreteDomain)}.
416   */
417  public boolean isEmpty() {
418    return lowerBound.equals(upperBound);
419  }
420
421  /**
422   * Returns {@code true} if {@code value} is within the bounds of this range. For example, on the
423   * range {@code [0..2)}, {@code contains(1)} returns {@code true}, while {@code contains(2)}
424   * returns {@code false}.
425   */
426  public boolean contains(C value) {
427    checkNotNull(value);
428    // let this throw CCE if there is some trickery going on
429    return lowerBound.isLessThan(value) && !upperBound.isLessThan(value);
430  }
431
432  /**
433   * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #contains}
434   *     instead.
435   */
436  @Deprecated
437  @Override
438  public boolean apply(C input) {
439    return contains(input);
440  }
441
442  /**
443   * Returns {@code true} if every element in {@code values} is {@linkplain #contains contained} in
444   * this range.
445   */
446  public boolean containsAll(Iterable<? extends C> values) {
447    if (Iterables.isEmpty(values)) {
448      return true;
449    }
450
451    // this optimizes testing equality of two range-backed sets
452    if (values instanceof SortedSet) {
453      SortedSet<? extends C> set = cast(values);
454      Comparator<?> comparator = set.comparator();
455      if (Ordering.natural().equals(comparator) || comparator == null) {
456        return contains(set.first()) && contains(set.last());
457      }
458    }
459
460    for (C value : values) {
461      if (!contains(value)) {
462        return false;
463      }
464    }
465    return true;
466  }
467
468  /**
469   * Returns {@code true} if the bounds of {@code other} do not extend outside the bounds of this
470   * range. Examples:
471   *
472   * <ul>
473   *   <li>{@code [3..6]} encloses {@code [4..5]}
474   *   <li>{@code (3..6)} encloses {@code (3..6)}
475   *   <li>{@code [3..6]} encloses {@code [4..4)} (even though the latter is empty)
476   *   <li>{@code (3..6]} does not enclose {@code [3..6]}
477   *   <li>{@code [4..5]} does not enclose {@code (3..6)} (even though it contains every value
478   *       contained by the latter range)
479   *   <li>{@code [3..6]} does not enclose {@code (1..1]} (even though it contains every value
480   *       contained by the latter range)
481   * </ul>
482   *
483   * <p>Note that if {@code a.encloses(b)}, then {@code b.contains(v)} implies {@code
484   * a.contains(v)}, but as the last two examples illustrate, the converse is not always true.
485   *
486   * <p>Being reflexive, antisymmetric and transitive, the {@code encloses} relation defines a
487   * <i>partial order</i> over ranges. There exists a unique {@linkplain Range#all maximal} range
488   * according to this relation, and also numerous {@linkplain #isEmpty minimal} ranges. Enclosure
489   * also implies {@linkplain #isConnected connectedness}.
490   */
491  public boolean encloses(Range<C> other) {
492    return lowerBound.compareTo(other.lowerBound) <= 0
493        && upperBound.compareTo(other.upperBound) >= 0;
494  }
495
496  /**
497   * Returns {@code true} if there exists a (possibly empty) range which is {@linkplain #encloses
498   * enclosed} by both this range and {@code other}.
499   *
500   * <p>For example,
501   *
502   * <ul>
503   *   <li>{@code [2, 4)} and {@code [5, 7)} are not connected
504   *   <li>{@code [2, 4)} and {@code [3, 5)} are connected, because both enclose {@code [3, 4)}
505   *   <li>{@code [2, 4)} and {@code [4, 6)} are connected, because both enclose the empty range
506   *       {@code [4, 4)}
507   * </ul>
508   *
509   * <p>Note that this range and {@code other} have a well-defined {@linkplain #span union} and
510   * {@linkplain #intersection intersection} (as a single, possibly-empty range) if and only if this
511   * method returns {@code true}.
512   *
513   * <p>The connectedness relation is both reflexive and symmetric, but does not form an {@linkplain
514   * Equivalence equivalence relation} as it is not transitive.
515   *
516   * <p>Note that certain discrete ranges are not considered connected, even though there are no
517   * elements "between them." For example, {@code [3, 5]} is not considered connected to {@code [6,
518   * 10]}. In these cases, it may be desirable for both input ranges to be preprocessed with {@link
519   * #canonical(DiscreteDomain)} before testing for connectedness.
520   */
521  public boolean isConnected(Range<C> other) {
522    return lowerBound.compareTo(other.upperBound) <= 0
523        && other.lowerBound.compareTo(upperBound) <= 0;
524  }
525
526  /**
527   * Returns the maximal range {@linkplain #encloses enclosed} by both this range and {@code
528   * connectedRange}, if such a range exists.
529   *
530   * <p>For example, the intersection of {@code [1..5]} and {@code (3..7)} is {@code (3..5]}. The
531   * resulting range may be empty; for example, {@code [1..5)} intersected with {@code [5..7)}
532   * yields the empty range {@code [5..5)}.
533   *
534   * <p>The intersection exists if and only if the two ranges are {@linkplain #isConnected
535   * connected}.
536   *
537   * <p>The intersection operation is commutative, associative and idempotent, and its identity
538   * element is {@link Range#all}).
539   *
540   * @throws IllegalArgumentException if {@code isConnected(connectedRange)} is {@code false}
541   */
542  public Range<C> intersection(Range<C> connectedRange) {
543    int lowerCmp = lowerBound.compareTo(connectedRange.lowerBound);
544    int upperCmp = upperBound.compareTo(connectedRange.upperBound);
545    if (lowerCmp >= 0 && upperCmp <= 0) {
546      return this;
547    } else if (lowerCmp <= 0 && upperCmp >= 0) {
548      return connectedRange;
549    } else {
550      Cut<C> newLower = (lowerCmp >= 0) ? lowerBound : connectedRange.lowerBound;
551      Cut<C> newUpper = (upperCmp <= 0) ? upperBound : connectedRange.upperBound;
552      return create(newLower, newUpper);
553    }
554  }
555
556  /**
557   * Returns the maximal range lying between this range and {@code otherRange}, if such a range
558   * exists. The resulting range may be empty if the two ranges are adjacent but non-overlapping.
559   *
560   * <p>For example, the gap of {@code [1..5]} and {@code (7..10)} is {@code (5..7]}. The resulting
561   * range may be empty; for example, the gap between {@code [1..5)} {@code [5..7)} yields the empty
562   * range {@code [5..5)}.
563   *
564   * <p>The gap exists if and only if the two ranges are either disconnected or immediately adjacent
565   * (any intersection must be an empty range).
566   *
567   * <p>The gap operation is commutative.
568   *
569   * @throws IllegalArgumentException if this range and {@code otherRange} have a nonempty
570   *     intersection
571   * @since 27.0
572   */
573  public Range<C> gap(Range<C> otherRange) {
574    boolean isThisFirst = this.lowerBound.compareTo(otherRange.lowerBound) < 0;
575    Range<C> firstRange = isThisFirst ? this : otherRange;
576    Range<C> secondRange = isThisFirst ? otherRange : this;
577    return create(firstRange.upperBound, secondRange.lowerBound);
578  }
579
580  /**
581   * Returns the minimal range that {@linkplain #encloses encloses} both this range and {@code
582   * other}. For example, the span of {@code [1..3]} and {@code (5..7)} is {@code [1..7)}.
583   *
584   * <p><i>If</i> the input ranges are {@linkplain #isConnected connected}, the returned range can
585   * also be called their <i>union</i>. If they are not, note that the span might contain values
586   * that are not contained in either input range.
587   *
588   * <p>Like {@link #intersection(Range) intersection}, this operation is commutative, associative
589   * and idempotent. Unlike it, it is always well-defined for any two input ranges.
590   */
591  public Range<C> span(Range<C> other) {
592    int lowerCmp = lowerBound.compareTo(other.lowerBound);
593    int upperCmp = upperBound.compareTo(other.upperBound);
594    if (lowerCmp <= 0 && upperCmp >= 0) {
595      return this;
596    } else if (lowerCmp >= 0 && upperCmp <= 0) {
597      return other;
598    } else {
599      Cut<C> newLower = (lowerCmp <= 0) ? lowerBound : other.lowerBound;
600      Cut<C> newUpper = (upperCmp >= 0) ? upperBound : other.upperBound;
601      return create(newLower, newUpper);
602    }
603  }
604
605  /**
606   * Returns the canonical form of this range in the given domain. The canonical form has the
607   * following properties:
608   *
609   * <ul>
610   *   <li>equivalence: {@code a.canonical().contains(v) == a.contains(v)} for all {@code v} (in
611   *       other words, {@code ContiguousSet.create(a.canonical(domain), domain).equals(
612   *       ContiguousSet.create(a, domain))}
613   *   <li>uniqueness: unless {@code a.isEmpty()}, {@code ContiguousSet.create(a,
614   *       domain).equals(ContiguousSet.create(b, domain))} implies {@code
615   *       a.canonical(domain).equals(b.canonical(domain))}
616   *   <li>idempotence: {@code a.canonical(domain).canonical(domain).equals(a.canonical(domain))}
617   * </ul>
618   *
619   * <p>Furthermore, this method guarantees that the range returned will be one of the following
620   * canonical forms:
621   *
622   * <ul>
623   *   <li>[start..end)
624   *   <li>[start..+∞)
625   *   <li>(-∞..end) (only if type {@code C} is unbounded below)
626   *   <li>(-∞..+∞) (only if type {@code C} is unbounded below)
627   * </ul>
628   */
629  public Range<C> canonical(DiscreteDomain<C> domain) {
630    checkNotNull(domain);
631    Cut<C> lower = lowerBound.canonical(domain);
632    Cut<C> upper = upperBound.canonical(domain);
633    return (lower == lowerBound && upper == upperBound) ? this : create(lower, upper);
634  }
635
636  /**
637   * Returns {@code true} if {@code object} is a range having the same endpoints and bound types as
638   * this range. Note that discrete ranges such as {@code (1..4)} and {@code [2..3]} are <b>not</b>
639   * equal to one another, despite the fact that they each contain precisely the same set of values.
640   * Similarly, empty ranges are not equal unless they have exactly the same representation, so
641   * {@code [3..3)}, {@code (3..3]}, {@code (4..4]} are all unequal.
642   */
643  @Override
644  public boolean equals(@NullableDecl Object object) {
645    if (object instanceof Range) {
646      Range<?> other = (Range<?>) object;
647      return lowerBound.equals(other.lowerBound) && upperBound.equals(other.upperBound);
648    }
649    return false;
650  }
651
652  /** Returns a hash code for this range. */
653  @Override
654  public int hashCode() {
655    return lowerBound.hashCode() * 31 + upperBound.hashCode();
656  }
657
658  /**
659   * Returns a string representation of this range, such as {@code "[3..5)"} (other examples are
660   * listed in the class documentation).
661   */
662  @Override
663  public String toString() {
664    return toString(lowerBound, upperBound);
665  }
666
667  private static String toString(Cut<?> lowerBound, Cut<?> upperBound) {
668    StringBuilder sb = new StringBuilder(16);
669    lowerBound.describeAsLowerBound(sb);
670    sb.append("..");
671    upperBound.describeAsUpperBound(sb);
672    return sb.toString();
673  }
674
675  /** Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */
676  private static <T> SortedSet<T> cast(Iterable<T> iterable) {
677    return (SortedSet<T>) iterable;
678  }
679
680  Object readResolve() {
681    if (this.equals(ALL)) {
682      return all();
683    } else {
684      return this;
685    }
686  }
687
688  @SuppressWarnings("unchecked") // this method may throw CCE
689  static int compareOrThrow(Comparable left, Comparable right) {
690    return left.compareTo(right);
691  }
692
693  /** Needed to serialize sorted collections of Ranges. */
694  private static class RangeLexOrdering extends Ordering<Range<?>> implements Serializable {
695    static final Ordering<Range<?>> INSTANCE = new RangeLexOrdering();
696
697    @Override
698    public int compare(Range<?> left, Range<?> right) {
699      return ComparisonChain.start()
700          .compare(left.lowerBound, right.lowerBound)
701          .compare(left.upperBound, right.upperBound)
702          .result();
703    }
704
705    private static final long serialVersionUID = 0;
706  }
707
708  private static final long serialVersionUID = 0;
709}