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  static class LowerBoundFn implements Function<Range, Cut> {
123    static final LowerBoundFn INSTANCE = new LowerBoundFn();
124    @Override
125    public Cut apply(Range range) {
126      return range.lowerBound;
127    }
128  }
129
130  static class UpperBoundFn implements Function<Range, Cut> {
131    static final UpperBoundFn INSTANCE = new UpperBoundFn();
132    @Override
133    public Cut apply(Range range) {
134      return range.upperBound;
135    }
136  }
137
138  @SuppressWarnings("unchecked")
139  static <C extends Comparable<?>> Function<Range<C>, Cut<C>> lowerBoundFn() {
140    return (Function) LowerBoundFn.INSTANCE;
141  }
142
143  @SuppressWarnings("unchecked")
144  static <C extends Comparable<?>> Function<Range<C>, Cut<C>> upperBoundFn() {
145    return (Function) UpperBoundFn.INSTANCE;
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 SortedSet) {
337      SortedSet<? extends C> set = cast(values);
338      Comparator<?> comparator = set.comparator();
339      if (Ordering.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.natural().min(min, value);
349      max = Ordering.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  /**
368   * Returns {@code true} if this range has a lower endpoint.
369   */
370  public boolean hasLowerBound() {
371    return lowerBound != Cut.belowAll();
372  }
373
374  /**
375   * Returns the lower endpoint of this range.
376   *
377   * @throws IllegalStateException if this range is unbounded below (that is, {@link
378   *     #hasLowerBound()} returns {@code false})
379   */
380  public C lowerEndpoint() {
381    return lowerBound.endpoint();
382  }
383
384  /**
385   * Returns the type of this range's lower bound: {@link BoundType#CLOSED} if the range includes
386   * its lower endpoint, {@link BoundType#OPEN} if it does not.
387   *
388   * @throws IllegalStateException if this range is unbounded below (that is, {@link
389   *     #hasLowerBound()} returns {@code false})
390   */
391  public BoundType lowerBoundType() {
392    return lowerBound.typeAsLowerBound();
393  }
394
395  /**
396   * Returns {@code true} if this range has an upper endpoint.
397   */
398  public boolean hasUpperBound() {
399    return upperBound != Cut.aboveAll();
400  }
401
402  /**
403   * Returns the upper endpoint of this range.
404   *
405   * @throws IllegalStateException if this range is unbounded above (that is, {@link
406   *     #hasUpperBound()} returns {@code false})
407   */
408  public C upperEndpoint() {
409    return upperBound.endpoint();
410  }
411
412  /**
413   * Returns the type of this range's upper bound: {@link BoundType#CLOSED} if the range includes
414   * its upper endpoint, {@link BoundType#OPEN} if it does not.
415   *
416   * @throws IllegalStateException if this range is unbounded above (that is, {@link
417   *     #hasUpperBound()} returns {@code false})
418   */
419  public BoundType upperBoundType() {
420    return upperBound.typeAsUpperBound();
421  }
422
423  /**
424   * Returns {@code true} if this range is of the form {@code [v..v)} or {@code (v..v]}. (This does
425   * not encompass ranges of the form {@code (v..v)}, because such ranges are <i>invalid</i> and
426   * can't be constructed at all.)
427   *
428   * <p>Note that certain discrete ranges such as the integer range {@code (3..4)} are <b>not</b>
429   * considered empty, even though they contain no actual values.  In these cases, it may be
430   * helpful to preprocess ranges with {@link #canonical(DiscreteDomain)}.
431   */
432  public boolean isEmpty() {
433    return lowerBound.equals(upperBound);
434  }
435
436  /**
437   * Returns {@code true} if {@code value} is within the bounds of this range. For example, on the
438   * range {@code [0..2)}, {@code contains(1)} returns {@code true}, while {@code contains(2)}
439   * returns {@code false}.
440   */
441  public boolean contains(C value) {
442    checkNotNull(value);
443    // let this throw CCE if there is some trickery going on
444    return lowerBound.isLessThan(value) && !upperBound.isLessThan(value);
445  }
446
447  /**
448   * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #contains}
449   *     instead.
450   */
451  @Deprecated
452  @Override
453  public boolean apply(C input) {
454    return contains(input);
455  }
456
457  /**
458   * Returns {@code true} if every element in {@code values} is {@linkplain #contains contained} in
459   * this range.
460   */
461  public boolean containsAll(Iterable<? extends C> values) {
462    if (Iterables.isEmpty(values)) {
463      return true;
464    }
465
466    // this optimizes testing equality of two range-backed sets
467    if (values instanceof SortedSet) {
468      SortedSet<? extends C> set = cast(values);
469      Comparator<?> comparator = set.comparator();
470      if (Ordering.natural().equals(comparator) || comparator == null) {
471        return contains(set.first()) && contains(set.last());
472      }
473    }
474
475    for (C value : values) {
476      if (!contains(value)) {
477        return false;
478      }
479    }
480    return true;
481  }
482
483  /**
484   * Returns {@code true} if the bounds of {@code other} do not extend outside the bounds of this
485   * range. Examples:
486   *
487   * <ul>
488   * <li>{@code [3..6]} encloses {@code [4..5]}
489   * <li>{@code (3..6)} encloses {@code (3..6)}
490   * <li>{@code [3..6]} encloses {@code [4..4)} (even though the latter is empty)
491   * <li>{@code (3..6]} does not enclose {@code [3..6]}
492   * <li>{@code [4..5]} does not enclose {@code (3..6)} (even though it contains every value
493   *     contained by the latter range)
494   * <li>{@code [3..6]} does not enclose {@code (1..1]} (even though it contains every value
495   *     contained by the latter range)
496   * </ul>
497   *
498   * <p>Note that if {@code a.encloses(b)}, then {@code b.contains(v)} implies
499   * {@code a.contains(v)}, but as the last two examples illustrate, the converse is not always
500   * true.
501   *
502   * <p>Being reflexive, antisymmetric and transitive, the {@code encloses} relation defines a
503   * <i>partial order</i> over ranges. There exists a unique {@linkplain Range#all maximal} range
504   * according to this relation, and also numerous {@linkplain #isEmpty minimal} ranges. Enclosure
505   * also implies {@linkplain #isConnected connectedness}.
506   */
507  public boolean encloses(Range<C> other) {
508    return lowerBound.compareTo(other.lowerBound) <= 0
509        && upperBound.compareTo(other.upperBound) >= 0;
510  }
511
512  /**
513   * Returns {@code true} if there exists a (possibly empty) range which is {@linkplain #encloses
514   * enclosed} by both this range and {@code other}.
515   *
516   * <p>For example,
517   * <ul>
518   * <li>{@code [2, 4)} and {@code [5, 7)} are not connected
519   * <li>{@code [2, 4)} and {@code [3, 5)} are connected, because both enclose {@code [3, 4)}
520   * <li>{@code [2, 4)} and {@code [4, 6)} are connected, because both enclose the empty range
521   *     {@code [4, 4)}
522   * </ul>
523   *
524   * <p>Note that this range and {@code other} have a well-defined {@linkplain #span union} and
525   * {@linkplain #intersection intersection} (as a single, possibly-empty range) if and only if this
526   * method returns {@code true}.
527   *
528   * <p>The connectedness relation is both reflexive and symmetric, but does not form an {@linkplain
529   * Equivalence equivalence relation} as it is not transitive.
530   *
531   * <p>Note that certain discrete ranges are not considered connected, even though there are no
532   * elements "between them."  For example, {@code [3, 5]} is not considered connected to {@code
533   * [6, 10]}.  In these cases, it may be desirable for both input ranges to be preprocessed with
534   * {@link #canonical(DiscreteDomain)} before testing for connectedness.
535   */
536  public boolean isConnected(Range<C> other) {
537    return lowerBound.compareTo(other.upperBound) <= 0
538        && other.lowerBound.compareTo(upperBound) <= 0;
539  }
540
541  /**
542   * Returns the maximal range {@linkplain #encloses enclosed} by both this range and {@code
543   * connectedRange}, if such a range exists.
544   *
545   * <p>For example, the intersection of {@code [1..5]} and {@code (3..7)} is {@code (3..5]}. The
546   * resulting range may be empty; for example, {@code [1..5)} intersected with {@code [5..7)}
547   * yields the empty range {@code [5..5)}.
548   *
549   * <p>The intersection exists if and only if the two ranges are {@linkplain #isConnected
550   * connected}.
551   *
552   * <p>The intersection operation is commutative, associative and idempotent, and its identity
553   * element is {@link Range#all}).
554   *
555   * @throws IllegalArgumentException if {@code isConnected(connectedRange)} is {@code false}
556   */
557  public Range<C> intersection(Range<C> connectedRange) {
558    int lowerCmp = lowerBound.compareTo(connectedRange.lowerBound);
559    int upperCmp = upperBound.compareTo(connectedRange.upperBound);
560    if (lowerCmp >= 0 && upperCmp <= 0) {
561      return this;
562    } else if (lowerCmp <= 0 && upperCmp >= 0) {
563      return connectedRange;
564    } else {
565      Cut<C> newLower = (lowerCmp >= 0) ? lowerBound : connectedRange.lowerBound;
566      Cut<C> newUpper = (upperCmp <= 0) ? upperBound : connectedRange.upperBound;
567      return create(newLower, newUpper);
568    }
569  }
570
571  /**
572   * Returns the minimal range that {@linkplain #encloses encloses} both this range and {@code
573   * other}. For example, the span of {@code [1..3]} and {@code (5..7)} is {@code [1..7)}.
574   *
575   * <p><i>If</i> the input ranges are {@linkplain #isConnected connected}, the returned range can
576   * also be called their <i>union</i>. If they are not, note that the span might contain values
577   * that are not contained in either input range.
578   *
579   * <p>Like {@link #intersection(Range) intersection}, this operation is commutative, associative
580   * and idempotent. Unlike it, it is always well-defined for any two input ranges.
581   */
582  public Range<C> span(Range<C> other) {
583    int lowerCmp = lowerBound.compareTo(other.lowerBound);
584    int upperCmp = upperBound.compareTo(other.upperBound);
585    if (lowerCmp <= 0 && upperCmp >= 0) {
586      return this;
587    } else if (lowerCmp >= 0 && upperCmp <= 0) {
588      return other;
589    } else {
590      Cut<C> newLower = (lowerCmp <= 0) ? lowerBound : other.lowerBound;
591      Cut<C> newUpper = (upperCmp >= 0) ? upperBound : other.upperBound;
592      return create(newLower, newUpper);
593    }
594  }
595
596  /**
597   * Returns the canonical form of this range in the given domain. The canonical form has the
598   * following properties:
599   *
600   * <ul>
601   * <li>equivalence: {@code a.canonical().contains(v) == a.contains(v)} for all {@code v} (in other
602   *     words, {@code ContiguousSet.create(a.canonical(domain), domain).equals(
603   *     ContiguousSet.create(a, domain))}
604   * <li>uniqueness: unless {@code a.isEmpty()},
605   *     {@code ContiguousSet.create(a, domain).equals(ContiguousSet.create(b, domain))} implies
606   *     {@code a.canonical(domain).equals(b.canonical(domain))}
607   * <li>idempotence: {@code a.canonical(domain).canonical(domain).equals(a.canonical(domain))}
608   * </ul>
609   *
610   * <p>Furthermore, this method guarantees that the range returned will be one of the following
611   * canonical forms:
612   *
613   * <ul>
614   * <li>[start..end)
615   * <li>[start..+∞)
616   * <li>(-∞..end) (only if type {@code C} is unbounded below)
617   * <li>(-∞..+∞) (only if type {@code C} is unbounded below)
618   * </ul>
619   */
620  public Range<C> canonical(DiscreteDomain<C> domain) {
621    checkNotNull(domain);
622    Cut<C> lower = lowerBound.canonical(domain);
623    Cut<C> upper = upperBound.canonical(domain);
624    return (lower == lowerBound && upper == upperBound) ? this : create(lower, upper);
625  }
626
627  /**
628   * Returns {@code true} if {@code object} is a range having the same endpoints and bound types as
629   * this range. Note that discrete ranges such as {@code (1..4)} and {@code [2..3]} are <b>not</b>
630   * equal to one another, despite the fact that they each contain precisely the same set of values.
631   * Similarly, empty ranges are not equal unless they have exactly the same representation, so
632   * {@code [3..3)}, {@code (3..3]}, {@code (4..4]} are all unequal.
633   */
634  @Override
635  public boolean equals(@Nullable Object object) {
636    if (object instanceof Range) {
637      Range<?> other = (Range<?>) object;
638      return lowerBound.equals(other.lowerBound) && upperBound.equals(other.upperBound);
639    }
640    return false;
641  }
642
643  /** Returns a hash code for this range. */
644  @Override
645  public int hashCode() {
646    return lowerBound.hashCode() * 31 + upperBound.hashCode();
647  }
648
649  /**
650   * Returns a string representation of this range, such as {@code "[3..5)"} (other examples are
651   * listed in the class documentation).
652   */
653  @Override
654  public String toString() {
655    return toString(lowerBound, upperBound);
656  }
657
658  private static String toString(Cut<?> lowerBound, Cut<?> upperBound) {
659    StringBuilder sb = new StringBuilder(16);
660    lowerBound.describeAsLowerBound(sb);
661    sb.append("..");
662    upperBound.describeAsUpperBound(sb);
663    return sb.toString();
664  }
665
666  /**
667   * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
668   */
669  private static <T> SortedSet<T> cast(Iterable<T> iterable) {
670    return (SortedSet<T>) iterable;
671  }
672
673  Object readResolve() {
674    if (this.equals(ALL)) {
675      return all();
676    } else {
677      return this;
678    }
679  }
680
681  @SuppressWarnings("unchecked") // this method may throw CCE
682  static int compareOrThrow(Comparable left, Comparable right) {
683    return left.compareTo(right);
684  }
685
686  /**
687   * Needed to serialize sorted collections of Ranges.
688   */
689  private static class RangeLexOrdering extends Ordering<Range<?>> implements Serializable {
690    static final Ordering<Range<?>> INSTANCE = new RangeLexOrdering();
691
692    @Override
693    public int compare(Range<?> left, Range<?> right) {
694      return ComparisonChain.start()
695          .compare(left.lowerBound, right.lowerBound)
696          .compare(left.upperBound, right.upperBound)
697          .result();
698    }
699
700    private static final long serialVersionUID = 0;
701  }
702
703  private static final long serialVersionUID = 0;
704}