1use serde::{Deserialize, Serialize};
2use std::fmt;
3
4#[derive(Clone, Default, PartialEq, Serialize, Deserialize)]
11pub struct String16 {
12 utf16: Vec<u16>,
13}
14
15impl String16 {
16 pub fn new() -> Self {
18 String16 { utf16: vec![] }
19 }
20
21 #[inline]
31 pub fn len(&self) -> usize {
32 self.utf16.len()
33 }
34
35 pub fn as_bytes(&self) -> &[u16] {
37 &self.utf16
38 }
39
40 pub fn as_bytes_mut(&mut self) -> &mut [u16] {
42 &mut self.utf16
43 }
44
45 pub fn insert_str(&mut self, idx: usize, string: &str) {
47 let mut counter = idx;
48 for u in string.encode_utf16() {
49 self.utf16.insert(counter, u);
50 counter += 1;
51 }
52 }
53
54 pub fn push(&mut self, ch: char) {
56 let mut buf = [0; 2];
57
58 for part in ch.encode_utf16(&mut buf) {
59 self.utf16.push(*part)
60 }
61 }
62
63 pub fn remove(&mut self, idx: usize) {
65 self.utf16.remove(idx);
66 }
67
68 pub fn is_empty(&self) -> bool {
70 self.utf16.is_empty()
71 }
72
73 pub fn ends_with(&self, pat: &str) -> bool {
75 self.as_string().ends_with(pat)
76 }
77
78 pub fn clear(&mut self) {
80 self.utf16.clear()
81 }
82
83 pub fn get_string(&self, start: usize, end: usize) -> Option<String> {
85 self.utf16.get(start..end).map(String::from_utf16_lossy)
86 }
87
88 pub fn as_string(&self) -> String {
90 String::from_utf16_lossy(&self.utf16)
91 }
92}
93
94impl From<&str> for String16 {
95 fn from(s: &str) -> Self {
96 String16 {
97 utf16: s.encode_utf16().collect(),
98 }
99 }
100}
101
102impl From<String> for String16 {
103 fn from(string: String) -> Self {
104 String16 {
105 utf16: string.encode_utf16().collect(),
106 }
107 }
108}
109
110impl fmt::Debug for String16 {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 write!(f, "String16 {}", self.as_string())
113 }
114}
115
116impl fmt::Display for String16 {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 write!(f, "{}", self.as_string())
119 }
120}
121
122#[cfg(test)]
123mod tests {
124 use super::*;
125 #[test]
126 fn from_string() {
127 let string16 = String16::from(String::from("Übung"));
128 assert_eq!(string16.len(), 5);
129
130 let string16 = String16::from(String::from("World"));
131 assert_eq!(string16.len(), 5);
132 }
133
134 #[test]
135 fn from_str() {
136 let string16 = String16::from("Übung");
137 assert_eq!(string16.len(), 5);
138
139 let string16 = String16::from("World");
140 assert_eq!(string16.len(), 5);
141 }
142
143 #[test]
144 fn push() {
145 let mut string16 = String16::from("Fo");
147 string16.push('o');
148 assert_eq!(string16, String16::from("Foo"));
149
150 let mut string16 = String16::from("Bar");
152 string16.push('𝕊');
153 assert_eq!(string16, String16::from("Bar𝕊"));
154 }
155}