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