Skip to main content

workflow_terminal/
unicode.rs

1/// A character-indexed string stored as a vector of [`char`]s, allowing
2/// indexing and editing by Unicode scalar value rather than by byte offset.
3#[derive(Default, Debug, Clone)]
4pub struct UnicodeString(pub Vec<char>);
5
6impl std::fmt::Display for UnicodeString {
7    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8        let s: String = self.0.iter().collect();
9        write!(f, "{}", s)
10    }
11}
12
13impl UnicodeString {
14    /// Removes all characters, leaving the string empty.
15    pub fn clear(&mut self) {
16        self.0.clear();
17    }
18
19    /// Removes and returns the last character, or `None` if the string is empty.
20    pub fn pop(&mut self) -> Option<char> {
21        self.0.pop()
22    }
23
24    /// Removes and returns the character at the given index, shifting subsequent characters left.
25    pub fn remove(&mut self, index: usize) -> char {
26        self.0.remove(index)
27    }
28
29    /// Returns the number of characters in the string.
30    pub fn len(&self) -> usize {
31        self.0.len()
32    }
33
34    /// Returns `true` if the string contains no characters.
35    pub fn is_empty(&self) -> bool {
36        self.0.is_empty()
37    }
38
39    /// Returns `true` if the string contains at least one character.
40    pub fn is_not_empty(&self) -> bool {
41        !self.0.is_empty()
42    }
43
44    /// Appends a single character to the end of the string.
45    pub fn push(&mut self, c: char) {
46        self.0.push(c);
47    }
48
49    /// Inserts a single character at the given character index, shifting subsequent characters right.
50    pub fn insert_char(&mut self, index: usize, c: char) {
51        self.0.insert(index, c);
52    }
53
54    /// Inserts all characters of `us` at the given character index, shifting subsequent characters right.
55    pub fn insert(&mut self, index: usize, us: UnicodeString) {
56        self.0.splice(index..index, us.0);
57    }
58
59    /// Appends all characters of `us` to the end of this string.
60    pub fn extend(&mut self, us: UnicodeString) {
61        self.0.extend(us.0);
62    }
63
64    /// Returns an iterator over the characters in the string.
65    pub fn iter(&self) -> impl Iterator<Item = &char> {
66        self.0.iter()
67    }
68}
69
70impl From<Vec<char>> for UnicodeString {
71    fn from(v: Vec<char>) -> Self {
72        Self(v)
73    }
74}
75
76impl From<&[char]> for UnicodeString {
77    fn from(v: &[char]) -> Self {
78        Self(v.to_vec())
79    }
80}
81
82impl From<&str> for UnicodeString {
83    fn from(s: &str) -> Self {
84        Self(s.chars().collect())
85    }
86}
87
88impl From<String> for UnicodeString {
89    fn from(s: String) -> Self {
90        Self(s.chars().collect())
91    }
92}