Skip to content

Commit 6912386

Browse files
committed
a couple of utility methods
1 parent 16d5285 commit 6912386

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "text_unit"
3-
version = "0.1.4"
3+
version = "0.1.5"
44
authors = ["Aleksey Kladov <[email protected]>"]
55
description = "Newtypes for text offsets"
66
license = "MIT OR Apache-2.0"

src/lib.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use std::{fmt, ops, iter};
1111
pub struct TextUnit(u32);
1212

1313
impl TextUnit {
14+
//TODO: rename to `from_char`: this is not ocaml!
1415
/// `TextUnit` equal to the length of this char.
1516
#[inline(always)]
1617
pub fn of_char(c: char) -> TextUnit {
@@ -33,6 +34,21 @@ impl TextUnit {
3334
pub fn checked_sub(self, other: TextUnit) -> Option<TextUnit> {
3435
self.0.checked_sub(other.0).map(TextUnit)
3536
}
37+
38+
#[inline(always)]
39+
pub fn from_usize(size: usize) -> TextUnit {
40+
#[cfg(debug_assertions)] {
41+
if size > u32::max_value() as usize {
42+
panic!("overflow when converting to TextUnit: {}", size)
43+
}
44+
}
45+
(size as u32).into()
46+
}
47+
48+
#[inline(always)]
49+
pub fn to_usize(self) -> usize {
50+
u32::from(self) as usize
51+
}
3652
}
3753

3854
impl fmt::Debug for TextUnit {
@@ -244,6 +260,7 @@ impl TextRange {
244260
TextRange::from_to(offset, offset + len)
245261
}
246262

263+
// TODO: pass by value
247264
/// The inclusive start of this range
248265
#[inline(always)]
249266
pub fn start(&self) -> TextUnit {
@@ -267,6 +284,12 @@ impl TextRange {
267284
pub fn is_empty(&self) -> bool {
268285
self.start() == self.end()
269286
}
287+
288+
#[inline(always)]
289+
pub fn is_subrange(&self, other: &TextRange) -> bool {
290+
other.start() <= self.start()
291+
&& self.end() <= other.end()
292+
}
270293
}
271294

272295
impl ops::Index<TextRange> for str {
@@ -352,4 +375,13 @@ mod tests {
352375
assert_eq!(r.checked_sub(1.into()), Some(TextRange::from_to(0.into(), 1.into())));
353376
assert_eq!(x.checked_sub(2.into()), None);
354377
}
378+
379+
#[test]
380+
fn test_subrange() {
381+
let r1 = TextRange::from_to(2.into(), 4.into());
382+
let r2 = TextRange::from_to(2.into(), 3.into());
383+
let r3 = TextRange::from_to(1.into(), 3.into());
384+
assert!(r2.is_subrange(&r1));
385+
assert!(!r3.is_subrange(&r1));
386+
}
355387
}

0 commit comments

Comments
 (0)