Unnamed repository; edit this file 'description' to name the repository.
checked ops
Aleksey Kladov 2018-08-29
parent 42a9f79 · commit cb3dbf2
-rw-r--r--lib/text-size/Cargo.toml2
-rw-r--r--lib/text-size/src/lib.rs27
2 files changed, 28 insertions, 1 deletions
diff --git a/lib/text-size/Cargo.toml b/lib/text-size/Cargo.toml
index 6122a304dd..99fed3d728 100644
--- a/lib/text-size/Cargo.toml
+++ b/lib/text-size/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "text_unit"
-version = "0.1.3"
+version = "0.1.4"
authors = ["Aleksey Kladov <[email protected]>"]
description = "Newtypes for text offsets"
license = "MIT OR Apache-2.0"
diff --git a/lib/text-size/src/lib.rs b/lib/text-size/src/lib.rs
index 00027ce69e..28b2e4d10e 100644
--- a/lib/text-size/src/lib.rs
+++ b/lib/text-size/src/lib.rs
@@ -28,6 +28,11 @@ impl TextUnit {
}
TextUnit(s.len() as u32)
}
+
+ #[inline(always)]
+ pub fn checked_sub(self, other: TextUnit) -> Option<TextUnit> {
+ self.0.checked_sub(other.0).map(TextUnit)
+ }
}
impl fmt::Debug for TextUnit {
@@ -199,6 +204,17 @@ pub struct TextRange {
end: TextUnit,
}
+impl TextRange {
+ #[inline(always)]
+ pub fn checked_sub(self, other: TextUnit) -> Option<TextRange> {
+ let res = TextRange::offset_len(
+ self.start().checked_sub(other)?,
+ self.len()
+ );
+ Some(res)
+ }
+}
+
impl fmt::Debug for TextRange {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
<Self as fmt::Display>::fmt(self, f)
@@ -325,4 +341,15 @@ mod tests {
TextRange::from_to(5.into(), 15.into()),
);
}
+
+ #[test]
+ fn test_checked_ops() {
+ let x: TextUnit = 1.into();
+ assert_eq!(x.checked_sub(1.into()), Some(0.into()));
+ assert_eq!(x.checked_sub(2.into()), None);
+
+ let r = TextRange::from_to(1.into(), 2.into());
+ assert_eq!(r.checked_sub(1.into()), Some(TextRange::from_to(0.into(), 1.into())));
+ assert_eq!(x.checked_sub(2.into()), None);
+ }
}