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