Skip to content

Commit 16d5285

Browse files
committed
checked ops
1 parent 3b379f8 commit 16d5285

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-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.3"
3+
version = "0.1.4"
44
authors = ["Aleksey Kladov <[email protected]>"]
55
description = "Newtypes for text offsets"
66
license = "MIT OR Apache-2.0"

src/lib.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ impl TextUnit {
2828
}
2929
TextUnit(s.len() as u32)
3030
}
31+
32+
#[inline(always)]
33+
pub fn checked_sub(self, other: TextUnit) -> Option<TextUnit> {
34+
self.0.checked_sub(other.0).map(TextUnit)
35+
}
3136
}
3237

3338
impl fmt::Debug for TextUnit {
@@ -199,6 +204,17 @@ pub struct TextRange {
199204
end: TextUnit,
200205
}
201206

207+
impl TextRange {
208+
#[inline(always)]
209+
pub fn checked_sub(self, other: TextUnit) -> Option<TextRange> {
210+
let res = TextRange::offset_len(
211+
self.start().checked_sub(other)?,
212+
self.len()
213+
);
214+
Some(res)
215+
}
216+
}
217+
202218
impl fmt::Debug for TextRange {
203219
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
204220
<Self as fmt::Display>::fmt(self, f)
@@ -325,4 +341,15 @@ mod tests {
325341
TextRange::from_to(5.into(), 15.into()),
326342
);
327343
}
344+
345+
#[test]
346+
fn test_checked_ops() {
347+
let x: TextUnit = 1.into();
348+
assert_eq!(x.checked_sub(1.into()), Some(0.into()));
349+
assert_eq!(x.checked_sub(2.into()), None);
350+
351+
let r = TextRange::from_to(1.into(), 2.into());
352+
assert_eq!(r.checked_sub(1.into()), Some(TextRange::from_to(0.into(), 1.into())));
353+
assert_eq!(x.checked_sub(2.into()), None);
354+
}
328355
}

0 commit comments

Comments
 (0)