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