Skip to main content

telexide_fork/model/utils/
text.rs

1use serde::{Deserialize, Serialize};
2
3/// An object describing a part of a text
4#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5pub struct TextBlock {
6    /// Offset in UTF-16 code units to the start of the entity
7    pub offset: usize,
8    /// Length of the entity in UTF-16 code units
9    pub length: usize,
10}
11
12impl TextBlock {
13    /// Gets the part of the text described by the `TextBlock`
14    pub fn get_text(&self, text: &str) -> String {
15        let mut res: Vec<u16> = Vec::with_capacity(self.length);
16
17        for (i, point) in text.encode_utf16().enumerate() {
18            if (self.offset + self.length) <= i {
19                break;
20            }
21            if self.offset <= i {
22                res.push(point);
23            }
24        }
25
26        String::from_utf16_lossy(res.as_slice())
27    }
28}