1use std::fmt;
4use std::sync::{Arc, LazyLock, OnceLock};
5
6use regex_syntax::hir::{Class, HirKind};
7use unicode_normalization::UnicodeNormalization;
8use unicode_segmentation::UnicodeSegmentation;
9
10use crate::error::StructureError;
11use crate::int::Int;
12use crate::tree::{self, Along, Measure, Node, Shape};
13
14pub const UNICODE_VERSION: (u8, u8, u8) = (16, 0, 0);
24
25const CAPITAL_SIGMA: char = '\u{3a3}';
28
29const FINAL_SIGMA: char = '\u{3c2}';
32
33static CASED: LazyLock<Vec<(char, char)>> = LazyLock::new(|| property("Cased"));
35
36static CASE_IGNORABLE: LazyLock<Vec<(char, char)>> = LazyLock::new(|| property("Case_Ignorable"));
38
39fn property(name: &str) -> Vec<(char, char)> {
42 let class = regex_syntax::Parser::new()
43 .parse(&format!(r"\p{{{name}}}"))
44 .map(regex_syntax::hir::Hir::into_kind);
45 match class {
46 Ok(HirKind::Class(Class::Unicode(class))) => class
47 .ranges()
48 .iter()
49 .map(|range| (range.start(), range.end()))
50 .collect(),
51 _ => unreachable!("regex-syntax knows the binary property {name}"),
52 }
53}
54
55fn has(ranges: &[(char, char)], code_point: char) -> bool {
58 ranges
59 .binary_search_by(|&(start, end)| {
60 if end < code_point {
61 std::cmp::Ordering::Less
62 } else if start > code_point {
63 std::cmp::Ordering::Greater
64 } else {
65 std::cmp::Ordering::Equal
66 }
67 })
68 .is_ok()
69}
70
71fn after_a_cased_letter(before: &str) -> bool {
75 for code_point in before.chars().rev() {
76 if has(&CASED, code_point) {
77 return true;
78 }
79 if !has(&CASE_IGNORABLE, code_point) {
80 return false;
81 }
82 }
83 false
84}
85
86fn before_a_cased_letter(after: &str) -> bool {
89 for code_point in after.chars() {
90 if has(&CASED, code_point) {
91 return true;
92 }
93 if !has(&CASE_IGNORABLE, code_point) {
94 return false;
95 }
96 }
97 false
98}
99
100fn push_mapped(out: &mut String, code_point: char, mapped: &[u32]) {
103 if mapped[0] == 0 {
104 out.push(code_point);
105 } else {
106 out.extend(
107 mapped
108 .iter()
109 .take_while(|&&unit| unit != 0)
110 .filter_map(|&unit| char::from_u32(unit)),
111 );
112 }
113}
114
115#[derive(Clone, Default)]
144pub struct Text {
145 root: Option<Node<Run>>,
146 flat: Option<Arc<OnceLock<Arc<str>>>>,
150}
151
152#[derive(Clone, Debug)]
155pub struct Run {
156 block: Block,
157 from: usize,
158 to: usize,
159 length: usize,
161 places: OnceLock<Places>,
165}
166
167#[derive(Clone, Debug)]
171struct Places {
172 starts: Arc<[usize]>,
173 first: usize,
176}
177
178#[derive(Clone, Copy, PartialEq, Eq, Debug)]
181pub struct Span {
182 bytes: usize,
183 length: usize,
184}
185
186impl Measure for Span {
187 const EMPTY: Span = Span {
188 bytes: 0,
189 length: 0,
190 };
191
192 fn join(self, other: Span) -> Span {
193 Span {
194 bytes: self.bytes + other.bytes,
195 length: self.length + other.length,
196 }
197 }
198}
199
200const SHORT: usize = 64;
204
205const STRIDE: usize = 64;
209
210#[cfg(test)]
211thread_local! {
212 pub(crate) static WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
215}
216
217fn walked(count: usize) {
219 #[cfg(test)]
220 WALKED.with(|walked| walked.set(walked.get() + count));
221 #[cfg(not(test))]
222 let _ = count;
223}
224
225impl Run {
226 fn new(block: Block, from: usize, to: usize, length: usize) -> Run {
229 Run {
230 block,
231 from,
232 to,
233 length,
234 places: OnceLock::new(),
235 }
236 }
237
238 fn whole(utf8: Arc<str>) -> Run {
240 let length = utf8.chars().count();
241 let to = utf8.len();
242 Run::new(Block(utf8), 0, to, length)
243 }
244
245 pub fn block(&self) -> &Block {
247 &self.block
248 }
249
250 pub fn from(&self) -> usize {
252 self.from
253 }
254
255 pub fn to(&self) -> usize {
257 self.to
258 }
259
260 pub fn as_str(&self) -> &str {
262 &self.block.0[self.from..self.to]
263 }
264
265 pub(crate) fn span(&self) -> Span {
267 Span {
268 bytes: self.to - self.from,
269 length: self.length,
270 }
271 }
272
273 fn piece(&self, from: usize, to: usize, skipped: usize, length: usize) -> Run {
277 let places = self.places.get().map(|places| Places {
278 starts: Arc::clone(&places.starts),
279 first: places.first + skipped,
280 });
281 Run {
282 block: self.block.clone(),
283 from: self.from + from,
284 to: self.from + to,
285 length,
286 places: places.map_or_else(OnceLock::new, OnceLock::from),
287 }
288 }
289
290 fn offset(&self, position: usize) -> usize {
293 let text = self.as_str();
294 if self.length == text.len() {
295 return position;
296 }
297 let places = self.places.get_or_init(|| {
298 walked(self.length);
299 Places {
300 starts: text
301 .char_indices()
302 .step_by(STRIDE)
303 .map(|(at, _)| self.from + at)
304 .collect(),
305 first: 0,
306 }
307 });
308 let at = places.first + position;
309 let Some(&near) = places.starts.get(at / STRIDE) else {
310 return text.len();
311 };
312 walked(at % STRIDE);
313 let block = self.block.as_str();
314 block[near..]
315 .char_indices()
316 .nth(at % STRIDE)
317 .map_or(self.to, |(found, _)| near + found)
318 - self.from
319 }
320}
321
322struct ByByte;
325
326impl Along<Run> for ByByte {
327 fn node(&self, tree: &Node<Run>) -> usize {
328 tree.measure().bytes
329 }
330
331 fn item(&self, run: &Run) -> usize {
332 run.span().bytes
333 }
334
335 fn cut(&self, run: &Run, at: usize) -> Option<(Run, Run)> {
336 let length = run.as_str().get(..at)?.chars().count();
337 Some((
338 run.piece(0, at, 0, length),
339 run.piece(at, run.span().bytes, length, run.length - length),
340 ))
341 }
342}
343
344struct ByCodePoint;
346
347impl Along<Run> for ByCodePoint {
348 fn node(&self, tree: &Node<Run>) -> usize {
349 tree.measure().length
350 }
351
352 fn item(&self, run: &Run) -> usize {
353 run.span().length
354 }
355
356 fn cut(&self, run: &Run, at: usize) -> Option<(Run, Run)> {
357 let middle = run.offset(at);
358 Some((
359 run.piece(0, middle, 0, at),
360 run.piece(middle, run.span().bytes, at, run.length - at),
361 ))
362 }
363}
364
365impl Text {
366 pub fn new(code_points: &str) -> Self {
368 Text::whole(Arc::from(code_points))
369 }
370
371 fn whole(utf8: Arc<str>) -> Self {
373 Text::of_run(Run::whole(utf8))
374 }
375
376 fn of_run(run: Run) -> Self {
378 Text::of((run.from < run.to).then(|| tree::leaf(vec![run])))
379 }
380
381 fn of(root: Option<Node<Run>>) -> Self {
383 let flat = root
384 .as_ref()
385 .is_some_and(|root| root.len() > 1)
386 .then(|| Arc::new(OnceLock::new()));
387 Text { root, flat }
388 }
389
390 pub fn root(&self) -> Option<&Node<Run>> {
392 self.root.as_ref()
393 }
394
395 pub fn run(&self) -> Option<&Run> {
397 match self.root.as_ref()?.shape() {
398 Shape::Leaf([run]) => Some(run),
399 Shape::Leaf(_) | Shape::Branch(..) => None,
400 }
401 }
402
403 fn span(&self) -> Span {
405 self.root.as_ref().map_or(Span::EMPTY, Node::measure)
406 }
407
408 pub fn as_str(&self) -> &str {
410 match (&self.flat, self.run()) {
411 (Some(flat), _) => self.flat(flat),
412 (None, Some(run)) => run.as_str(),
413 (None, None) => "",
414 }
415 }
416
417 fn flat<'a>(&self, flat: &'a OnceLock<Arc<str>>) -> &'a Arc<str> {
419 flat.get_or_init(|| Arc::from(self.blocks().collect::<String>()))
420 }
421
422 pub fn to_shared(&self) -> Arc<str> {
426 match (&self.flat, self.run()) {
427 (Some(flat), _) => Arc::clone(self.flat(flat)),
428 (None, Some(run)) if run.from == 0 && run.to == run.block.len() => {
429 Arc::clone(&run.block.0)
430 }
431 (None, Some(run)) => Arc::from(run.as_str()),
432 (None, None) => Arc::from(""),
433 }
434 }
435
436 pub fn blocks(&self) -> impl Iterator<Item = &str> {
438 let count = self.root.as_ref().map_or(0, Node::len);
439 tree::Iter::new(self.root.as_ref(), 0, count).map(Run::as_str)
440 }
441
442 pub fn len(&self) -> usize {
444 self.span().length
445 }
446
447 pub fn is_empty(&self) -> bool {
449 self.root.is_none()
450 }
451
452 pub fn byte_len(&self) -> usize {
454 self.span().bytes
455 }
456
457 pub fn of_block(block: Block, from: usize, to: usize) -> Result<Text, StructureError> {
467 let length = block
468 .0
469 .get(from..to)
470 .ok_or(StructureError::Run)?
471 .chars()
472 .count();
473 Ok(Text::of_run(Run::new(block, from, to, length)))
474 }
475
476 pub fn join_shared(left: Text, right: Text) -> Text {
485 match (left.root, right.root) {
486 (Some(left), Some(right)) => Text::of(Some(Node::branch(left, right))),
487 (left, right) => Text::of(left.or(right)),
488 }
489 }
490
491 pub fn byte_window(&self, from: usize, to: usize) -> Result<Text, StructureError> {
499 if from > to || to > self.byte_len() {
500 return Err(StructureError::Run);
501 }
502 self.part(from, to, &ByByte).ok_or(StructureError::Run)
503 }
504
505 pub(crate) fn id(&self) -> usize {
508 self.root.as_ref().map_or(0, Node::id)
509 }
510
511 #[must_use]
517 pub fn concat(&self, other: &Text) -> Text {
518 let (Some(left), Some(right)) = (&self.root, &other.root) else {
519 return if other.is_empty() {
520 self.clone()
521 } else {
522 other.clone()
523 };
524 };
525 let short = |left: &Node<Run>, right: &Node<Run>| {
526 (left.measure().bytes + right.measure().bytes <= SHORT).then(|| {
527 let copied = format!("{}{}", Text::from(left.clone()), Text::from(right.clone()));
528 tree::leaf(vec![Run::whole(Arc::from(copied))])
529 })
530 };
531 Text::of(Some(tree::join_with(left.clone(), right.clone(), &short)))
532 }
533
534 pub fn slice(&self, start: &Int, end: &Int) -> Option<Text> {
537 let start = start.to_index()?;
538 let end = end.to_index()?;
539 if start > end || end > self.len() {
540 return None;
541 }
542 self.part(start, end, &ByCodePoint)
543 }
544
545 fn part(&self, start: usize, end: usize, along: &impl Along<Run>) -> Option<Text> {
549 let Some(root) = &self.root else {
550 return Some(Text::default());
551 };
552 if start == 0 && end == along.node(root) {
553 return Some(self.clone());
554 }
555 let (_, rest) = tree::cut(root.clone(), start, along)?;
556 let Some(rest) = rest else {
557 return Some(Text::default());
558 };
559 Some(Text::of(tree::cut(rest, end - start, along)?.0))
560 }
561
562 pub fn find_from(&self, needle: &Text, from: &Int) -> Option<usize> {
566 let from = from.to_index()?;
567 if from > self.len() {
568 return None;
569 }
570 let start = self.part(0, from, &ByCodePoint)?.byte_len();
573 let rest = &self.as_str()[start..];
574 let at = rest.find(needle.as_str())?;
575 Some(from + rest[..at].chars().count())
576 }
577
578 pub fn code_points(&self) -> Vec<Text> {
580 self.blocks()
581 .flat_map(str::chars)
582 .map(|code_point| Text::new(code_point.encode_utf8(&mut [0; 4])))
583 .collect()
584 }
585
586 pub fn graphemes(&self) -> Vec<Text> {
588 self.as_str().graphemes(true).map(Text::new).collect()
589 }
590
591 #[must_use]
593 pub fn normalize(&self) -> Text {
594 Text::from(self.blocks().flat_map(str::chars).nfc().collect::<String>())
595 }
596
597 #[must_use]
602 pub fn lowercase(&self) -> Text {
603 let utf8 = self.as_str();
604 let mut out = String::with_capacity(utf8.len());
605 for (at, code_point) in utf8.char_indices() {
606 if code_point == CAPITAL_SIGMA
607 && after_a_cased_letter(&utf8[..at])
608 && !before_a_cased_letter(&utf8[at + CAPITAL_SIGMA.len_utf8()..])
609 {
610 out.push(FINAL_SIGMA);
611 } else {
612 push_mapped(
613 &mut out,
614 code_point,
615 &unicode_case_mapping::to_lowercase(code_point),
616 );
617 }
618 }
619 Text::from(out)
620 }
621
622 #[must_use]
625 pub fn uppercase(&self) -> Text {
626 let mut out = String::with_capacity(self.byte_len());
627 for code_point in self.blocks().flat_map(str::chars) {
628 push_mapped(
629 &mut out,
630 code_point,
631 &unicode_case_mapping::to_uppercase(code_point),
632 );
633 }
634 Text::from(out)
635 }
636
637 #[cfg(test)]
639 pub(crate) fn block_of(&self) -> Option<&Arc<str>> {
640 self.run().map(|run| &run.block.0)
641 }
642
643 pub fn to_bytes(&self) -> Bytes {
645 Bytes::new(self.as_str().as_bytes())
646 }
647}
648
649#[derive(Clone, Debug)]
652pub struct Block(Arc<str>);
653
654impl Block {
655 pub fn new(utf8: Arc<str>) -> Block {
657 Block(utf8)
658 }
659
660 pub fn id(&self) -> usize {
664 Arc::as_ptr(&self.0).cast::<u8>().addr()
665 }
666
667 pub fn as_str(&self) -> &str {
669 &self.0
670 }
671
672 pub fn len(&self) -> usize {
674 self.0.len()
675 }
676
677 pub fn is_empty(&self) -> bool {
679 self.0.is_empty()
680 }
681}
682
683impl PartialEq for Text {
684 fn eq(&self, other: &Text) -> bool {
685 self.id() == other.id()
686 || (self.byte_len() == other.byte_len() && self.as_str() == other.as_str())
687 }
688}
689
690impl Eq for Text {}
691
692impl PartialOrd for Text {
693 fn partial_cmp(&self, other: &Text) -> Option<std::cmp::Ordering> {
694 Some(self.cmp(other))
695 }
696}
697
698impl Ord for Text {
699 fn cmp(&self, other: &Text) -> std::cmp::Ordering {
700 if self.id() == other.id() {
701 return std::cmp::Ordering::Equal;
702 }
703 self.as_str().cmp(other.as_str())
704 }
705}
706
707impl From<String> for Text {
708 fn from(code_points: String) -> Self {
709 Text::whole(Arc::from(code_points))
710 }
711}
712
713impl From<Node<Run>> for Text {
714 fn from(root: Node<Run>) -> Self {
715 Text::of(Some(root))
716 }
717}
718
719impl fmt::Display for Text {
720 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
721 self.blocks().try_for_each(|block| f.write_str(block))
722 }
723}
724
725impl fmt::Debug for Text {
726 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
727 fmt::Debug::fmt(self.as_str(), f)
728 }
729}
730
731#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
734pub struct Bytes(Arc<[u8]>);
735
736impl Bytes {
737 pub fn new(contents: &[u8]) -> Self {
739 Bytes(Arc::from(contents))
740 }
741
742 pub fn as_slice(&self) -> &[u8] {
744 &self.0
745 }
746
747 pub(crate) fn id(&self) -> usize {
749 Arc::as_ptr(&self.0).cast::<u8>().addr()
750 }
751
752 pub fn len(&self) -> usize {
754 self.0.len()
755 }
756
757 pub fn is_empty(&self) -> bool {
759 self.0.is_empty()
760 }
761
762 pub fn to_text(&self) -> Option<Text> {
765 std::str::from_utf8(&self.0).ok().map(Text::new)
766 }
767
768 pub fn to_base64(&self) -> String {
771 const ALPHABET: &[u8; 64] =
772 b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
773 let mut out = String::with_capacity(self.0.len().div_ceil(3) * 4);
774 for chunk in self.0.chunks(3) {
775 let first = chunk[0];
776 let second = chunk.get(1).copied();
777 let third = chunk.get(2).copied();
778 let group = (u32::from(first) << 16)
780 + (u32::from(second.unwrap_or(0)) << 8)
781 + u32::from(third.unwrap_or(0));
782 let sextet = |shift: u32| {
783 char::from(ALPHABET[usize::from(((group >> shift) & 0x3f).to_le_bytes()[0])])
784 };
785 out.push(sextet(18));
786 out.push(sextet(12));
787 out.push(second.map_or('=', |_| sextet(6)));
788 out.push(third.map_or('=', |_| sextet(0)));
789 }
790 out
791 }
792}
793
794impl From<Vec<u8>> for Bytes {
795 fn from(contents: Vec<u8>) -> Self {
796 Bytes(Arc::from(contents))
797 }
798}
799
800impl fmt::Debug for Bytes {
801 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802 write!(f, "bytes({})", self.to_base64())
803 }
804}