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