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