glory_render/
text_selection.rs1#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5pub enum SelectionDirection {
6 #[default]
7 None,
8 Forward,
9 Backward,
10}
11impl SelectionDirection {
12 pub fn as_str(self) -> &'static str {
13 match self {
14 Self::None => "none",
15 Self::Forward => "forward",
16 Self::Backward => "backward",
17 }
18 }
19}
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub struct TextSelection {
22 pub start: usize,
23 pub end: usize,
24 pub direction: SelectionDirection,
25}
26impl TextSelection {
27 pub fn validate(self, utf16_len: usize) -> Result<(), crate::Error> {
28 if self.start <= self.end && self.end <= utf16_len {
29 Ok(())
30 } else {
31 Err(crate::Error::InvalidProps("invalid UTF-16 text selection"))
32 }
33 }
34
35 pub fn byte_range(self, text: &str) -> Result<std::ops::Range<usize>, crate::Error> {
39 let invalid = || crate::Error::InvalidProps("invalid UTF-16 text selection boundary");
40 if self.start > self.end {
41 return Err(invalid());
42 }
43 let mut start = None;
44 let mut units = 0;
45 for (byte, ch) in text.char_indices() {
46 if units == self.start {
47 start = Some(byte);
48 }
49 if units == self.end {
50 return Ok(start.ok_or_else(invalid)?..byte);
51 }
52 units += ch.len_utf16();
53 if units > self.end {
54 return Err(invalid());
55 }
56 }
57 if units == self.start {
58 start = Some(text.len());
59 }
60 if units == self.end {
61 Ok(start.ok_or_else(invalid)?..text.len())
62 } else {
63 Err(invalid())
64 }
65 }
66}