Compute the intersection of this interval with the given interval. If the intersection is empty, return `None`. If the two intervals have different data types, both are coerced to a common comparison type via [`comparison_coercion`] before computing the intersection.
(&self, other: T)
| 650 | /// common comparison type via [`comparison_coercion`] before computing the |
| 651 | /// intersection. |
| 652 | pub fn intersect<T: Borrow<Self>>(&self, other: T) -> Result<Option<Self>> { |
| 653 | let rhs = other.borrow(); |
| 654 | let (lhs_owned, rhs_owned) = coerce_for_comparison(self, rhs)?; |
| 655 | let lhs = lhs_owned.as_ref().unwrap_or(self); |
| 656 | let rhs = rhs_owned.as_ref().unwrap_or(rhs); |
| 657 | |
| 658 | // If it is evident that the result is an empty interval, short-circuit |
| 659 | // and directly return `None`. |
| 660 | if (!(lhs.lower.is_null() || rhs.upper.is_null()) && lhs.lower > rhs.upper) |
| 661 | || (!(lhs.upper.is_null() || rhs.lower.is_null()) && lhs.upper < rhs.lower) |
| 662 | { |
| 663 | return Ok(None); |
| 664 | } |
| 665 | |
| 666 | let lower = max_of_bounds(&lhs.lower, &rhs.lower); |
| 667 | let upper = min_of_bounds(&lhs.upper, &rhs.upper); |
| 668 | |
| 669 | // New lower and upper bounds must always construct a valid interval. |
| 670 | debug_assert!( |
| 671 | (lower.is_null() || upper.is_null() || (lower <= upper)), |
| 672 | "The intersection of two intervals can not be an invalid interval" |
| 673 | ); |
| 674 | |
| 675 | Ok(Some(Self { lower, upper })) |
| 676 | } |
| 677 | |
| 678 | /// Compute the union of this interval with the given interval. |
| 679 | /// |