|
| 1 | +use cmp::Ordering; |
| 2 | + |
1 | 3 | use {
|
2 | 4 | crate::TextSize,
|
3 | 5 | std::{
|
@@ -294,6 +296,50 @@ impl TextRange {
|
294 | 296 | end: self.end.checked_sub(offset)?,
|
295 | 297 | })
|
296 | 298 | }
|
| 299 | + |
| 300 | + /// Relative order of the two ranges (overlapping ranges are considered |
| 301 | + /// equal). |
| 302 | + /// |
| 303 | + /// |
| 304 | + /// This is useful when, for example, binary searching an array of disjoint |
| 305 | + /// ranges. |
| 306 | + /// |
| 307 | + /// # Examples |
| 308 | + /// |
| 309 | + /// ``` |
| 310 | + /// # use text_size::*; |
| 311 | + /// # use std::cmp::Ordering; |
| 312 | + /// |
| 313 | + /// let a = TextRange::new(0.into(), 3.into()); |
| 314 | + /// let b = TextRange::new(4.into(), 5.into()); |
| 315 | + /// assert_eq!(a.ordering(b), Ordering::Less); |
| 316 | + /// |
| 317 | + /// let a = TextRange::new(0.into(), 3.into()); |
| 318 | + /// let b = TextRange::new(3.into(), 5.into()); |
| 319 | + /// assert_eq!(a.ordering(b), Ordering::Less); |
| 320 | + /// |
| 321 | + /// let a = TextRange::new(0.into(), 3.into()); |
| 322 | + /// let b = TextRange::new(2.into(), 5.into()); |
| 323 | + /// assert_eq!(a.ordering(b), Ordering::Equal); |
| 324 | + /// |
| 325 | + /// let a = TextRange::new(0.into(), 3.into()); |
| 326 | + /// let b = TextRange::new(2.into(), 2.into()); |
| 327 | + /// assert_eq!(a.ordering(b), Ordering::Equal); |
| 328 | + /// |
| 329 | + /// let a = TextRange::new(2.into(), 3.into()); |
| 330 | + /// let b = TextRange::new(2.into(), 2.into()); |
| 331 | + /// assert_eq!(a.ordering(b), Ordering::Greater); |
| 332 | + /// ``` |
| 333 | + #[inline] |
| 334 | + pub fn ordering(self, other: TextRange) -> Ordering { |
| 335 | + if self.end() <= other.start() { |
| 336 | + Ordering::Less |
| 337 | + } else if other.end() <= self.start() { |
| 338 | + Ordering::Greater |
| 339 | + } else { |
| 340 | + Ordering::Equal |
| 341 | + } |
| 342 | + } |
297 | 343 | }
|
298 | 344 |
|
299 | 345 | impl Index<TextRange> for str {
|
|
0 commit comments