Unnamed repository; edit this file 'description' to name the repository.
Diffstat (limited to 'lib/text-size/src/traits.rs')
| -rw-r--r-- | lib/text-size/src/traits.rs | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/lib/text-size/src/traits.rs b/lib/text-size/src/traits.rs new file mode 100644 index 0000000000..877f057895 --- /dev/null +++ b/lib/text-size/src/traits.rs @@ -0,0 +1,35 @@ +use { + crate::{TextRange, TextSize}, + std::convert::TryInto, +}; + +/// Text-like structures that have a text size. +pub trait TextSized: Copy { + /// The size of this text-alike. + fn text_size(self) -> TextSize; +} + +impl TextSized for &'_ str { + fn text_size(self) -> TextSize { + let len = self.len(); + if let Ok(size) = len.try_into() { + size + } else if cfg!(debug_assertions) { + panic!("overflow when converting to TextSize"); + } else { + TextSize(len as u32) + } + } +} + +impl TextSized for char { + fn text_size(self) -> TextSize { + TextSize(self.len_utf8() as u32) + } +} + +impl TextSized for TextRange { + fn text_size(self) -> TextSize { + self.len() + } +} |