Skip to content

Commit e4d0f2b

Browse files
committed
Allow binary-searching an array of disjoint ranges
1 parent 066e82f commit e4d0f2b

File tree

3 files changed

+52
-2
lines changed

3 files changed

+52
-2
lines changed

CHANGELOG.md

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
# Changelog
22

3+
## 1.1.0
4+
5+
* add `TextRange::ordering` method
6+
37
## 1.0.0 :tada:
48

5-
* the carate is renmaed to `text-size` from `text_unit`
9+
* the carate is renamed to `text-size` from `text_unit`
610

711
Transition table:
812
- `TextUnit::of_char(c)``TextSize::of(c)`

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "text-size"
3-
version = "1.0.0"
3+
version = "1.1.0"
44
edition = "2018"
55

66
authors = [

src/range.rs

+46
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use cmp::Ordering;
2+
13
use {
24
crate::TextSize,
35
std::{
@@ -294,6 +296,50 @@ impl TextRange {
294296
end: self.end.checked_sub(offset)?,
295297
})
296298
}
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+
}
297343
}
298344

299345
impl Index<TextRange> for str {

0 commit comments

Comments
 (0)