1use std::fmt;
4use std::sync::{Arc, LazyLock};
5
6use regex_syntax::hir::{Class, HirKind};
7use unicode_normalization::UnicodeNormalization;
8use unicode_segmentation::UnicodeSegmentation;
9
10use crate::int::Int;
11
12pub const UNICODE_VERSION: (u8, u8, u8) = (16, 0, 0);
23
24const CAPITAL_SIGMA: char = '\u{3a3}';
27
28const FINAL_SIGMA: char = '\u{3c2}';
31
32static CASED: LazyLock<Vec<(char, char)>> = LazyLock::new(|| property("Cased"));
34
35static CASE_IGNORABLE: LazyLock<Vec<(char, char)>> = LazyLock::new(|| property("Case_Ignorable"));
37
38fn property(name: &str) -> Vec<(char, char)> {
41 let class = regex_syntax::Parser::new()
42 .parse(&format!(r"\p{{{name}}}"))
43 .map(regex_syntax::hir::Hir::into_kind);
44 match class {
45 Ok(HirKind::Class(Class::Unicode(class))) => class
46 .ranges()
47 .iter()
48 .map(|range| (range.start(), range.end()))
49 .collect(),
50 _ => unreachable!("regex-syntax knows the binary property {name}"),
51 }
52}
53
54fn has(ranges: &[(char, char)], code_point: char) -> bool {
57 ranges
58 .binary_search_by(|&(start, end)| {
59 if end < code_point {
60 std::cmp::Ordering::Less
61 } else if start > code_point {
62 std::cmp::Ordering::Greater
63 } else {
64 std::cmp::Ordering::Equal
65 }
66 })
67 .is_ok()
68}
69
70fn after_a_cased_letter(before: &str) -> bool {
74 for code_point in before.chars().rev() {
75 if has(&CASED, code_point) {
76 return true;
77 }
78 if !has(&CASE_IGNORABLE, code_point) {
79 return false;
80 }
81 }
82 false
83}
84
85fn before_a_cased_letter(after: &str) -> bool {
88 for code_point in after.chars() {
89 if has(&CASED, code_point) {
90 return true;
91 }
92 if !has(&CASE_IGNORABLE, code_point) {
93 return false;
94 }
95 }
96 false
97}
98
99fn push_mapped(out: &mut String, code_point: char, mapped: &[u32]) {
102 if mapped[0] == 0 {
103 out.push(code_point);
104 } else {
105 out.extend(
106 mapped
107 .iter()
108 .take_while(|&&unit| unit != 0)
109 .filter_map(|&unit| char::from_u32(unit)),
110 );
111 }
112}
113
114#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
126pub struct Text {
127 utf8: Arc<str>,
128 length: usize,
129}
130
131impl Text {
132 pub fn new(code_points: &str) -> Self {
134 Text {
135 utf8: Arc::from(code_points),
136 length: code_points.chars().count(),
137 }
138 }
139
140 pub fn as_str(&self) -> &str {
142 &self.utf8
143 }
144
145 pub fn len(&self) -> usize {
147 self.length
148 }
149
150 pub fn is_empty(&self) -> bool {
152 self.length == 0
153 }
154
155 #[must_use]
157 pub fn concat(&self, other: &Text) -> Text {
158 let mut joined = String::from(&*self.utf8);
159 joined.push_str(&other.utf8);
160 Text {
161 utf8: Arc::from(joined),
162 length: self.length + other.length,
163 }
164 }
165
166 pub fn slice(&self, start: &Int, end: &Int) -> Option<Text> {
169 let start = start.to_index()?;
170 let end = end.to_index()?;
171 if start > end || end > self.length {
172 return None;
173 }
174 let from = self.byte_offset(start);
175 let to = self.byte_offset(end);
176 Some(Text {
177 utf8: Arc::from(&self.utf8[from..to]),
178 length: end - start,
179 })
180 }
181
182 pub fn code_points(&self) -> Vec<Text> {
184 let mut buffer = [0; 4];
185 self.utf8
186 .chars()
187 .map(|code_point| Text {
188 utf8: Arc::from(&*code_point.encode_utf8(&mut buffer)),
189 length: 1,
190 })
191 .collect()
192 }
193
194 pub fn graphemes(&self) -> Vec<Text> {
196 self.utf8.graphemes(true).map(Text::new).collect()
197 }
198
199 #[must_use]
201 pub fn normalize(&self) -> Text {
202 Text::from(self.utf8.nfc().collect::<String>())
203 }
204
205 #[must_use]
210 pub fn lowercase(&self) -> Text {
211 let mut out = String::with_capacity(self.utf8.len());
212 for (at, code_point) in self.utf8.char_indices() {
213 if code_point == CAPITAL_SIGMA
214 && after_a_cased_letter(&self.utf8[..at])
215 && !before_a_cased_letter(&self.utf8[at + CAPITAL_SIGMA.len_utf8()..])
216 {
217 out.push(FINAL_SIGMA);
218 } else {
219 push_mapped(
220 &mut out,
221 code_point,
222 &unicode_case_mapping::to_lowercase(code_point),
223 );
224 }
225 }
226 Text::from(out)
227 }
228
229 #[must_use]
232 pub fn uppercase(&self) -> Text {
233 let mut out = String::with_capacity(self.utf8.len());
234 for code_point in self.utf8.chars() {
235 push_mapped(
236 &mut out,
237 code_point,
238 &unicode_case_mapping::to_uppercase(code_point),
239 );
240 }
241 Text::from(out)
242 }
243
244 pub fn byte_len(&self) -> usize {
246 self.utf8.len()
247 }
248
249 pub fn to_bytes(&self) -> Bytes {
251 Bytes::new(self.utf8.as_bytes())
252 }
253
254 fn byte_offset(&self, position: usize) -> usize {
257 if self.length == self.utf8.len() {
258 return position;
260 }
261 self.utf8
262 .char_indices()
263 .nth(position)
264 .map_or(self.utf8.len(), |(offset, _)| offset)
265 }
266}
267
268impl From<String> for Text {
269 fn from(code_points: String) -> Self {
270 let length = code_points.chars().count();
271 Text {
272 utf8: Arc::from(code_points),
273 length,
274 }
275 }
276}
277
278impl fmt::Display for Text {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 f.write_str(&self.utf8)
281 }
282}
283
284impl fmt::Debug for Text {
285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286 fmt::Debug::fmt(&*self.utf8, f)
287 }
288}
289
290#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
293pub struct Bytes(Arc<[u8]>);
294
295impl Bytes {
296 pub fn new(contents: &[u8]) -> Self {
298 Bytes(Arc::from(contents))
299 }
300
301 pub fn as_slice(&self) -> &[u8] {
303 &self.0
304 }
305
306 pub fn len(&self) -> usize {
308 self.0.len()
309 }
310
311 pub fn is_empty(&self) -> bool {
313 self.0.is_empty()
314 }
315
316 pub fn to_text(&self) -> Option<Text> {
319 std::str::from_utf8(&self.0).ok().map(Text::new)
320 }
321
322 pub fn to_base64(&self) -> String {
325 const ALPHABET: &[u8; 64] =
326 b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
327 let mut out = String::with_capacity(self.0.len().div_ceil(3) * 4);
328 for chunk in self.0.chunks(3) {
329 let first = chunk[0];
330 let second = chunk.get(1).copied();
331 let third = chunk.get(2).copied();
332 let group = (u32::from(first) << 16)
334 + (u32::from(second.unwrap_or(0)) << 8)
335 + u32::from(third.unwrap_or(0));
336 let sextet = |shift: u32| char::from(ALPHABET[((group >> shift) & 0x3f) as usize]);
337 out.push(sextet(18));
338 out.push(sextet(12));
339 out.push(second.map_or('=', |_| sextet(6)));
340 out.push(third.map_or('=', |_| sextet(0)));
341 }
342 out
343 }
344}
345
346impl From<Vec<u8>> for Bytes {
347 fn from(contents: Vec<u8>) -> Self {
348 Bytes(Arc::from(contents))
349 }
350}
351
352impl fmt::Debug for Bytes {
353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354 write!(f, "bytes({})", self.to_base64())
355 }
356}