1use crate::entities::{CharVerticalAlignment, UnderlineStyle};
25use serde::{Deserialize, Serialize};
26use thiserror::Error;
27
28#[derive(Debug, Clone, PartialEq, Eq, Error)]
36pub enum FormatRunError {
37 #[error("byte range {start}..{end} is reversed")]
38 ReversedRange { start: u32, end: u32 },
39
40 #[error(
41 "replacement run {run_start}..{run_end} falls outside the spliced range \
42 {range_start}..{range_end}"
43 )]
44 ReplacementOutsideRange {
45 run_start: u32,
46 run_end: u32,
47 range_start: u32,
48 range_end: u32,
49 },
50
51 #[error("run {start}..{end} is empty or reversed")]
52 EmptyRun { start: u32, end: u32 },
53
54 #[error("runs overlap or are out of order at index {index}: {left:?} then {right:?}")]
55 RunsOverlap {
56 index: usize,
57 left: Box<FormatRun>,
58 right: Box<FormatRun>,
59 },
60
61 #[error("adjacent runs with identical formatting were left uncoalesced at index {index}")]
62 RunsNotCoalesced { index: usize },
63
64 #[error("run {start}..{end} runs past the end of the block's {text_len} bytes")]
65 RunPastEndOfBlock {
66 start: u32,
67 end: u32,
68 text_len: usize,
69 },
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
83pub enum ReplaceFormatPolicy {
84 #[default]
95 InheritPreceding,
96
97 PreserveIfFullyCovered,
102
103 KeepDominantRun,
109
110 PreserveNothing,
112}
113
114#[derive(Serialize, Deserialize, Default, Clone, Debug, PartialEq, Eq)]
116pub enum InlineContent {
117 #[default]
118 Empty,
119 Text(String),
120 FootnoteRef {
133 label: String,
134 },
135 Image {
136 name: String,
137 #[serde(default)]
148 alt: String,
149 width: i64,
150 height: i64,
151 quality: i64,
152 },
153}
154
155#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
164pub struct InlineSegment {
165 pub content: InlineContent,
166 pub fmt_font_family: Option<String>,
167 pub fmt_font_point_size: Option<i64>,
168 pub fmt_font_weight: Option<i64>,
169 pub fmt_font_bold: Option<bool>,
170 pub fmt_font_italic: Option<bool>,
171 pub fmt_font_underline: Option<bool>,
172 pub fmt_font_overline: Option<bool>,
173 pub fmt_font_strikeout: Option<bool>,
174 pub fmt_letter_spacing: Option<i64>,
175 pub fmt_word_spacing: Option<i64>,
176 pub fmt_anchor_href: Option<String>,
177 pub fmt_anchor_names: Vec<String>,
178 pub fmt_is_anchor: Option<bool>,
179 pub fmt_tooltip: Option<String>,
180 pub fmt_underline_style: Option<UnderlineStyle>,
181 pub fmt_vertical_alignment: Option<CharVerticalAlignment>,
182}
183
184#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
189pub struct CharacterFormat {
190 pub font_family: Option<String>,
191 pub font_point_size: Option<i64>,
192 pub font_weight: Option<i64>,
193 pub font_bold: Option<bool>,
194 pub font_italic: Option<bool>,
195 pub font_underline: Option<bool>,
196 pub font_overline: Option<bool>,
197 pub font_strikeout: Option<bool>,
198 pub letter_spacing: Option<i64>,
199 pub word_spacing: Option<i64>,
200 pub anchor_href: Option<String>,
201 pub anchor_names: Vec<String>,
202 pub is_anchor: Option<bool>,
203 pub tooltip: Option<String>,
204 pub underline_style: Option<UnderlineStyle>,
205 pub vertical_alignment: Option<CharVerticalAlignment>,
206}
207
208#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
212pub struct FormatRun {
213 pub byte_start: u32,
214 pub byte_end: u32,
215 pub format: CharacterFormat,
216}
217
218#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
225pub struct ImageAnchor {
226 pub byte_offset: u32,
227 pub name: String,
228 #[serde(default)]
231 pub alt: String,
232 pub width: i64,
233 pub height: i64,
234 pub quality: i64,
235 pub format: CharacterFormat,
236}
237
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252pub struct FootnoteRefAnchor {
253 pub byte_offset: u32,
254 pub label: String,
257 pub format: CharacterFormat,
258}
259
260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
267pub enum BlockAnchor<'a> {
268 Image(&'a ImageAnchor),
269 FootnoteRef(&'a FootnoteRefAnchor),
270}
271
272impl BlockAnchor<'_> {
273 pub fn byte_offset(&self) -> u32 {
275 match self {
276 BlockAnchor::Image(i) => i.byte_offset,
277 BlockAnchor::FootnoteRef(f) => f.byte_offset,
278 }
279 }
280}
281
282pub fn block_anchors<'a>(
288 images: &'a [ImageAnchor],
289 footnote_refs: &'a [FootnoteRefAnchor],
290) -> Vec<BlockAnchor<'a>> {
291 let mut anchors: Vec<BlockAnchor<'a>> = Vec::with_capacity(images.len() + footnote_refs.len());
292 anchors.extend(images.iter().map(BlockAnchor::Image));
293 anchors.extend(footnote_refs.iter().map(BlockAnchor::FootnoteRef));
294 anchors.sort_by_key(|a| a.byte_offset());
295 anchors
296}
297
298pub fn debug_assert_well_formed(runs: &[FormatRun], block_text_len: usize) {
311 if cfg!(debug_assertions)
313 && let Err(e) = check_well_formed(runs, block_text_len)
314 {
315 debug_assert!(false, "format runs are malformed: {e}");
316 }
317}
318
319pub fn check_well_formed(runs: &[FormatRun], block_text_len: usize) -> Result<(), FormatRunError> {
326 if runs.is_empty() {
327 return Ok(());
328 }
329 for run in runs {
330 if run.byte_start >= run.byte_end {
331 return Err(FormatRunError::EmptyRun {
332 start: run.byte_start,
333 end: run.byte_end,
334 });
335 }
336 }
337 for i in 0..runs.len() - 1 {
338 if runs[i].byte_end > runs[i + 1].byte_start {
339 return Err(FormatRunError::RunsOverlap {
340 index: i,
341 left: Box::new(runs[i].clone()),
342 right: Box::new(runs[i + 1].clone()),
343 });
344 }
345 if runs[i].byte_end == runs[i + 1].byte_start && runs[i].format == runs[i + 1].format {
346 return Err(FormatRunError::RunsNotCoalesced { index: i });
347 }
348 }
349 let last = runs.last().expect("non-empty");
350 if last.byte_end as usize > block_text_len {
351 return Err(FormatRunError::RunPastEndOfBlock {
352 start: last.byte_start,
353 end: last.byte_end,
354 text_len: block_text_len,
355 });
356 }
357 Ok(())
358}
359
360pub fn coalesce_in_place(runs: &mut Vec<FormatRun>) {
362 if runs.len() < 2 {
363 return;
364 }
365 let mut write = 0usize;
366 for read in 1..runs.len() {
367 if runs[write].byte_end == runs[read].byte_start && runs[write].format == runs[read].format
368 {
369 runs[write].byte_end = runs[read].byte_end;
370 } else {
371 write += 1;
372 if write != read {
373 runs[write] = runs[read].clone();
374 }
375 }
376 }
377 runs.truncate(write + 1);
378}
379
380pub fn splice_range(
390 runs: &mut Vec<FormatRun>,
391 range: std::ops::Range<u32>,
392 replacement: Vec<FormatRun>,
393) {
394 if let Err(e) = try_splice_range(runs, range, replacement) {
395 debug_assert!(false, "splice_range contract violated: {e}");
404 }
405}
406
407pub fn try_splice_range(
412 runs: &mut Vec<FormatRun>,
413 range: std::ops::Range<u32>,
414 replacement: Vec<FormatRun>,
415) -> Result<(), FormatRunError> {
416 if range.start > range.end {
417 return Err(FormatRunError::ReversedRange {
418 start: range.start,
419 end: range.end,
420 });
421 }
422 for r in &replacement {
423 if r.byte_start >= r.byte_end {
424 return Err(FormatRunError::EmptyRun {
425 start: r.byte_start,
426 end: r.byte_end,
427 });
428 }
429 if r.byte_start < range.start || r.byte_end > range.end {
430 return Err(FormatRunError::ReplacementOutsideRange {
431 run_start: r.byte_start,
432 run_end: r.byte_end,
433 range_start: range.start,
434 range_end: range.end,
435 });
436 }
437 }
438 for i in 1..replacement.len() {
439 if replacement[i - 1].byte_end > replacement[i].byte_start {
440 return Err(FormatRunError::RunsOverlap {
441 index: i - 1,
442 left: Box::new(replacement[i - 1].clone()),
443 right: Box::new(replacement[i].clone()),
444 });
445 }
446 }
447
448 let mut result: Vec<FormatRun> = Vec::with_capacity(runs.len() + replacement.len());
449
450 for run in runs.iter() {
452 if run.byte_end <= range.start {
453 result.push(run.clone());
454 } else if run.byte_start < range.start {
455 result.push(FormatRun {
457 byte_start: run.byte_start,
458 byte_end: range.start,
459 format: run.format.clone(),
460 });
461 }
462 }
463
464 result.extend(replacement);
466
467 for run in runs.iter() {
469 if run.byte_start >= range.end {
470 result.push(run.clone());
471 } else if run.byte_end > range.end {
472 result.push(FormatRun {
474 byte_start: range.end,
475 byte_end: run.byte_end,
476 format: run.format.clone(),
477 });
478 }
479 }
480
481 coalesce_in_place(&mut result);
482 *runs = result;
483 Ok(())
484}
485
486pub fn capture_runs_in_range(runs: &[FormatRun], start: u32, end: u32) -> Vec<FormatRun> {
497 let mut out = Vec::new();
498 for run in runs {
499 if run.byte_end <= start || run.byte_start >= end {
500 continue;
501 }
502 let clipped_start = std::cmp::max(run.byte_start, start);
503 let clipped_end = std::cmp::min(run.byte_end, end);
504 if clipped_start < clipped_end {
505 out.push(FormatRun {
506 byte_start: clipped_start,
507 byte_end: clipped_end,
508 format: run.format.clone(),
509 });
510 }
511 }
512 out
513}
514
515pub fn capture_image_formats_in_range(
519 images: &[ImageAnchor],
520 start: u32,
521 end: u32,
522) -> Vec<(u32, CharacterFormat)> {
523 let mut out = Vec::new();
524 for img in images {
525 if img.byte_offset >= start && img.byte_offset < end {
526 out.push((img.byte_offset, img.format.clone()));
527 }
528 }
529 out
530}
531
532pub fn shift_after(runs: &mut [FormatRun], threshold: u32, delta: i32) {
540 for run in runs.iter_mut() {
541 if run.byte_start >= threshold {
542 let new_start = (run.byte_start as i64) + (delta as i64);
543 let new_end = (run.byte_end as i64) + (delta as i64);
544 debug_assert!(new_start >= 0 && new_end >= new_start);
545 run.byte_start = new_start as u32;
546 run.byte_end = new_end as u32;
547 }
548 }
549}
550
551pub fn synth_element_id(block_id: u64, byte_start: u32) -> u64 {
567 const SYNTH_TAG: u64 = 0x4000_0000_0000_0000;
568 SYNTH_TAG | ((block_id & 0x3FFF_FFFF) << 32) | (byte_start as u64)
569}
570
571pub fn shift_images_after(images: &mut [ImageAnchor], threshold: u32, delta: i32) {
574 for img in images.iter_mut() {
575 if img.byte_offset >= threshold {
576 let new_off = (img.byte_offset as i64) + (delta as i64);
577 debug_assert!(new_off >= 0);
578 img.byte_offset = new_off as u32;
579 }
580 }
581}
582
583pub fn shift_runs_for_insert(runs: &mut [FormatRun], byte_offset: u32, inserted_bytes: u32) {
594 if inserted_bytes == 0 {
595 return;
596 }
597 for run in runs.iter_mut() {
598 if run.byte_start >= byte_offset {
599 run.byte_start += inserted_bytes;
600 run.byte_end += inserted_bytes;
601 } else if run.byte_end >= byte_offset {
602 run.byte_end += inserted_bytes;
606 }
607 }
608}
609
610pub fn shift_runs_for_typed_insert(
625 runs: &mut Vec<FormatRun>,
626 byte_offset: u32,
627 inserted_bytes: u32,
628) {
629 if inserted_bytes == 0 {
630 return;
631 }
632 let first = runs
633 .iter()
634 .position(|run| run.byte_start == 0 && run.byte_end > 0);
635 let Some(first) = first.filter(|_| byte_offset == 0) else {
636 shift_runs_for_insert(runs, byte_offset, inserted_bytes);
637 return;
638 };
639 let format = &runs[first].format;
640 let inherited = CharacterFormat {
641 anchor_href: None,
642 anchor_names: Vec::new(),
643 is_anchor: None,
644 tooltip: None,
645 ..format.clone()
646 };
647 if inherited == *format {
648 for (index, run) in runs.iter_mut().enumerate() {
649 if index != first {
650 run.byte_start += inserted_bytes;
651 }
652 run.byte_end += inserted_bytes;
653 }
654 return;
655 }
656 for run in runs.iter_mut() {
657 run.byte_start += inserted_bytes;
658 run.byte_end += inserted_bytes;
659 }
660 if inherited != CharacterFormat::default() {
661 runs.insert(
662 0,
663 FormatRun {
664 byte_start: 0,
665 byte_end: inserted_bytes,
666 format: inherited,
667 },
668 );
669 }
670}
671
672pub fn shift_runs_for_delete(runs: &mut Vec<FormatRun>, byte_start: u32, byte_end: u32) {
677 if byte_end <= byte_start {
678 return;
679 }
680 splice_range(runs, byte_start..byte_end, Vec::new());
681 let delta = (byte_end - byte_start) as i32;
682 shift_after(runs, byte_end, -delta);
683 coalesce_in_place(runs);
686}
687
688pub fn shift_runs_for_replace(
706 runs: &mut Vec<FormatRun>,
707 byte_start: u32,
708 byte_end: u32,
709 replacement_bytes: u32,
710 policy: ReplaceFormatPolicy,
711) -> Result<(), FormatRunError> {
712 if byte_end < byte_start {
713 return Err(FormatRunError::ReversedRange {
714 start: byte_start,
715 end: byte_end,
716 });
717 }
718
719 let destroys_formatting = byte_end > byte_start;
731 let override_format: Option<Option<CharacterFormat>> = match policy {
732 ReplaceFormatPolicy::InheritPreceding => None,
733 ReplaceFormatPolicy::PreserveNothing => Some(None),
734 ReplaceFormatPolicy::PreserveIfFullyCovered => {
735 covering_format(runs, byte_start, byte_end).map(Some)
736 }
737 ReplaceFormatPolicy::KeepDominantRun if destroys_formatting => {
738 Some(dominant_format(runs, byte_start, byte_end))
739 }
740 ReplaceFormatPolicy::KeepDominantRun => None,
741 };
742
743 shift_runs_for_delete(runs, byte_start, byte_end);
745 shift_runs_for_insert(runs, byte_start, replacement_bytes);
746
747 if let Some(format) = override_format
749 && replacement_bytes > 0
750 {
751 let span = byte_start..byte_start + replacement_bytes;
752 let replacement = match format {
753 Some(format) => vec![FormatRun {
754 byte_start: span.start,
755 byte_end: span.end,
756 format,
757 }],
758 None => Vec::new(),
759 };
760 try_splice_range(runs, span, replacement)?;
761 }
762 Ok(())
763}
764
765fn covering_format(runs: &[FormatRun], start: u32, end: u32) -> Option<CharacterFormat> {
771 if end <= start {
772 return None;
773 }
774 runs.iter()
775 .find(|r| r.byte_start <= start && r.byte_end >= end)
776 .map(|r| r.format.clone())
777}
778
779fn dominant_format(runs: &[FormatRun], start: u32, end: u32) -> Option<CharacterFormat> {
786 if end <= start {
787 return None;
788 }
789 let span = u64::from(end - start);
790 let mut covered = 0u64;
791 let mut best: Option<(u64, &FormatRun)> = None;
792
793 for r in runs {
794 let lo = r.byte_start.max(start);
795 let hi = r.byte_end.min(end);
796 if hi <= lo {
797 continue;
798 }
799 let overlap = u64::from(hi - lo);
800 covered += overlap;
801 if best.is_none_or(|(best_overlap, _)| overlap > best_overlap) {
804 best = Some((overlap, r));
805 }
806 }
807
808 let plain = span - covered;
809 match best {
810 Some((overlap, run)) if overlap >= plain => Some(run.format.clone()),
811 _ => None,
812 }
813}
814
815pub fn shift_footnote_refs_for_insert(
820 notes: &mut [FootnoteRefAnchor],
821 byte_offset: u32,
822 inserted_bytes: u32,
823) {
824 if inserted_bytes == 0 {
825 return;
826 }
827 for note in notes.iter_mut() {
828 if note.byte_offset >= byte_offset {
829 note.byte_offset += inserted_bytes;
830 }
831 }
832}
833
834pub fn shift_images_for_insert(images: &mut [ImageAnchor], byte_offset: u32, inserted_bytes: u32) {
835 if inserted_bytes == 0 {
836 return;
837 }
838 for img in images.iter_mut() {
839 if img.byte_offset >= byte_offset {
840 img.byte_offset += inserted_bytes;
841 }
842 }
843}
844
845pub fn shift_images_for_delete(
850 images: &mut Vec<ImageAnchor>,
851 byte_start: u32,
852 byte_end: u32,
853) -> usize {
854 if byte_end <= byte_start {
855 return 0;
856 }
857 let before = images.len();
858 images.retain(|i| !(i.byte_offset >= byte_start && i.byte_offset < byte_end));
859 let removed = before - images.len();
860 let delta = (byte_end - byte_start) as i32;
861 shift_images_after(images, byte_end, -delta);
862 removed
863}
864
865pub fn shift_footnote_refs_for_delete(
879 notes: &mut Vec<FootnoteRefAnchor>,
880 byte_start: u32,
881 byte_end: u32,
882) -> usize {
883 if byte_end <= byte_start {
884 return 0;
885 }
886 let before = notes.len();
887 notes.retain(|n| !(n.byte_offset >= byte_start && n.byte_offset < byte_end));
888 let removed = before - notes.len();
889 let delta = byte_end - byte_start;
890 for note in notes.iter_mut() {
891 if note.byte_offset >= byte_end {
892 note.byte_offset -= delta;
893 }
894 }
895 removed
896}
897
898pub fn logical_offset_to_byte(plain_text: &str, _images: &[ImageAnchor], char_offset: i64) -> u32 {
919 if char_offset <= 0 {
920 return 0;
921 }
922 plain_text
923 .char_indices()
924 .nth(char_offset as usize)
925 .map(|(b, _)| b as u32)
926 .unwrap_or(plain_text.len() as u32)
927}
928
929pub fn split_runs_at(runs: &[FormatRun], byte_offset: u32) -> (Vec<FormatRun>, Vec<FormatRun>) {
934 let mut left = Vec::new();
935 let mut right = Vec::new();
936 for run in runs {
937 if run.byte_end <= byte_offset {
938 left.push(run.clone());
939 } else if run.byte_start >= byte_offset {
940 right.push(FormatRun {
941 byte_start: run.byte_start - byte_offset,
942 byte_end: run.byte_end - byte_offset,
943 format: run.format.clone(),
944 });
945 } else {
946 left.push(FormatRun {
947 byte_start: run.byte_start,
948 byte_end: byte_offset,
949 format: run.format.clone(),
950 });
951 right.push(FormatRun {
952 byte_start: 0,
953 byte_end: run.byte_end - byte_offset,
954 format: run.format.clone(),
955 });
956 }
957 }
958 (left, right)
959}
960
961pub fn split_footnote_refs_at(
967 notes: &[FootnoteRefAnchor],
968 byte_offset: u32,
969) -> (Vec<FootnoteRefAnchor>, Vec<FootnoteRefAnchor>) {
970 let mut left = Vec::new();
971 let mut right = Vec::new();
972 for note in notes {
973 if note.byte_offset < byte_offset {
974 left.push(note.clone());
975 } else {
976 let mut new = note.clone();
977 new.byte_offset -= byte_offset;
978 right.push(new);
979 }
980 }
981 (left, right)
982}
983
984pub fn split_images_at(
985 images: &[ImageAnchor],
986 byte_offset: u32,
987) -> (Vec<ImageAnchor>, Vec<ImageAnchor>) {
988 let mut left = Vec::new();
989 let mut right = Vec::new();
990 for img in images {
991 if img.byte_offset < byte_offset {
992 left.push(img.clone());
993 } else {
994 let mut new = img.clone();
995 new.byte_offset -= byte_offset;
996 right.push(new);
997 }
998 }
999 (left, right)
1000}
1001
1002pub fn character_format_from_segment(seg: &InlineSegment) -> CharacterFormat {
1008 CharacterFormat {
1009 font_family: seg.fmt_font_family.clone(),
1010 font_point_size: seg.fmt_font_point_size,
1011 font_weight: seg.fmt_font_weight,
1012 font_bold: seg.fmt_font_bold,
1013 font_italic: seg.fmt_font_italic,
1014 font_underline: seg.fmt_font_underline,
1015 font_overline: seg.fmt_font_overline,
1016 font_strikeout: seg.fmt_font_strikeout,
1017 letter_spacing: seg.fmt_letter_spacing,
1018 word_spacing: seg.fmt_word_spacing,
1019 anchor_href: seg.fmt_anchor_href.clone(),
1020 anchor_names: seg.fmt_anchor_names.clone(),
1021 is_anchor: seg.fmt_is_anchor,
1022 tooltip: seg.fmt_tooltip.clone(),
1023 underline_style: seg.fmt_underline_style.clone(),
1024 vertical_alignment: seg.fmt_vertical_alignment.clone(),
1025 }
1026}
1027
1028pub fn apply_character_format_to_segment(seg: &mut InlineSegment, fmt: &CharacterFormat) {
1030 seg.fmt_font_family = fmt.font_family.clone();
1031 seg.fmt_font_point_size = fmt.font_point_size;
1032 seg.fmt_font_weight = fmt.font_weight;
1033 seg.fmt_font_bold = fmt.font_bold;
1034 seg.fmt_font_italic = fmt.font_italic;
1035 seg.fmt_font_underline = fmt.font_underline;
1036 seg.fmt_font_overline = fmt.font_overline;
1037 seg.fmt_font_strikeout = fmt.font_strikeout;
1038 seg.fmt_letter_spacing = fmt.letter_spacing;
1039 seg.fmt_word_spacing = fmt.word_spacing;
1040 seg.fmt_anchor_href = fmt.anchor_href.clone();
1041 seg.fmt_anchor_names = fmt.anchor_names.clone();
1042 seg.fmt_is_anchor = fmt.is_anchor;
1043 seg.fmt_tooltip = fmt.tooltip.clone();
1044 seg.fmt_underline_style = fmt.underline_style.clone();
1045 seg.fmt_vertical_alignment = fmt.vertical_alignment.clone();
1046}
1047
1048#[derive(Debug, Clone, PartialEq)]
1053pub enum InlinePiece<'a> {
1054 Text {
1057 start: u32,
1058 end: u32,
1059 format: Option<&'a CharacterFormat>,
1060 },
1061 Image(&'a ImageAnchor),
1064 FootnoteRef(&'a FootnoteRefAnchor),
1067}
1068
1069pub fn merge_runs_and_anchors<'a>(
1089 plain_text: &str,
1090 runs: &'a [FormatRun],
1091 anchors: &[BlockAnchor<'a>],
1092) -> Vec<InlinePiece<'a>> {
1093 let text_len = plain_text.len() as u32;
1094 let mut out: Vec<InlinePiece<'a>> = Vec::new();
1095 let mut img_iter = anchors.iter().peekable();
1096 let mut cursor: u32 = 0;
1098
1099 fn sentinel_len(plain_text: &str, byte_offset: u32) -> u32 {
1114 let at = byte_offset as usize;
1115 if plain_text.len() >= at + 3 && plain_text.as_bytes()[at..at + 3] == [0xEF, 0xBF, 0xBC] {
1116 3
1117 } else {
1118 0
1119 }
1120 }
1121
1122 let push_text = |out: &mut Vec<InlinePiece<'a>>,
1123 start: u32,
1124 end: u32,
1125 format: Option<&'a CharacterFormat>| {
1126 if start < end {
1127 out.push(InlinePiece::Text { start, end, format });
1128 }
1129 };
1130
1131 fn piece<'a>(anchor: &BlockAnchor<'a>) -> InlinePiece<'a> {
1133 match *anchor {
1134 BlockAnchor::Image(i) => InlinePiece::Image(i),
1135 BlockAnchor::FootnoteRef(f) => InlinePiece::FootnoteRef(f),
1136 }
1137 }
1138
1139 for run in runs {
1140 while let Some(anchor) = img_iter.peek() {
1142 let at = anchor.byte_offset();
1143 if at >= run.byte_start {
1144 break;
1145 }
1146 push_text(&mut out, cursor, at, None);
1147 out.push(piece(anchor));
1148 cursor = cursor.max(at + sentinel_len(plain_text, at));
1149 img_iter.next();
1150 }
1151
1152 push_text(&mut out, cursor, run.byte_start, None);
1154 cursor = cursor.max(run.byte_start);
1155
1156 while let Some(anchor) = img_iter.peek() {
1161 let at = anchor.byte_offset();
1162 if at > run.byte_end {
1163 break;
1164 }
1165 push_text(&mut out, cursor, at, Some(&run.format));
1166 out.push(piece(anchor));
1167 cursor = cursor.max(at + sentinel_len(plain_text, at));
1168 img_iter.next();
1169 }
1170
1171 push_text(&mut out, cursor, run.byte_end, Some(&run.format));
1172 cursor = cursor.max(run.byte_end);
1173 }
1174
1175 for anchor in img_iter {
1177 let at = anchor.byte_offset();
1178 push_text(&mut out, cursor, at, None);
1179 out.push(piece(anchor));
1180 cursor = cursor.max(at + sentinel_len(plain_text, at));
1181 }
1182
1183 push_text(&mut out, cursor, text_len, None);
1184
1185 out
1186}
1187
1188#[derive(Debug, Clone, PartialEq)]
1210pub struct AddressableInlinePiece {
1211 pub start: u32,
1216 pub end: u32,
1217 pub content: InlineContent,
1218 pub format: CharacterFormat,
1219}
1220
1221pub fn addressable_inline_pieces(
1233 plain_text: &str,
1234 runs: &[FormatRun],
1235 anchors: &[BlockAnchor<'_>],
1236 base_char_offset: u32,
1237) -> Vec<AddressableInlinePiece> {
1238 let pieces = merge_runs_and_anchors(plain_text, runs, anchors);
1239 let mut out = Vec::with_capacity(pieces.len());
1240 let mut cursor = base_char_offset;
1241 for piece in pieces {
1242 match piece {
1243 InlinePiece::Text { start, end, format } => {
1244 let text = &plain_text[start as usize..end as usize];
1245 let len = text.chars().count() as u32;
1246 out.push(AddressableInlinePiece {
1247 start: cursor,
1248 end: cursor + len,
1249 content: InlineContent::Text(text.to_string()),
1250 format: format.cloned().unwrap_or_default(),
1251 });
1252 cursor += len;
1253 }
1254 InlinePiece::Image(anchor) => {
1255 out.push(AddressableInlinePiece {
1256 start: cursor,
1257 end: cursor + 1,
1258 content: InlineContent::Image {
1259 name: anchor.name.clone(),
1260 alt: anchor.alt.clone(),
1261 width: anchor.width,
1262 height: anchor.height,
1263 quality: anchor.quality,
1264 },
1265 format: anchor.format.clone(),
1266 });
1267 cursor += 1;
1268 }
1269 InlinePiece::FootnoteRef(anchor) => {
1270 out.push(AddressableInlinePiece {
1271 start: cursor,
1272 end: cursor + 1,
1273 content: InlineContent::FootnoteRef {
1274 label: anchor.label.clone(),
1275 },
1276 format: anchor.format.clone(),
1277 });
1278 cursor += 1;
1279 }
1280 }
1281 }
1282 out
1283}
1284
1285pub fn inline_segments_view(
1295 plain_text: &str,
1296 runs: &[FormatRun],
1297 images: &[ImageAnchor],
1298 footnote_refs: &[FootnoteRefAnchor],
1299) -> Vec<InlineSegment> {
1300 let bytes = plain_text.as_bytes();
1301 let default_format = CharacterFormat::default();
1302
1303 merge_runs_and_anchors(plain_text, runs, &block_anchors(images, footnote_refs))
1304 .into_iter()
1305 .map(|piece| match piece {
1306 InlinePiece::Text { start, end, format } => {
1307 let slice = &bytes[start as usize..end as usize];
1308 let text = std::str::from_utf8(slice)
1309 .expect("block plain_text must be valid UTF-8")
1310 .to_string();
1311 let mut seg = InlineSegment {
1312 content: InlineContent::Text(text),
1313 ..Default::default()
1314 };
1315 apply_character_format_to_segment(&mut seg, format.unwrap_or(&default_format));
1316 seg
1317 }
1318 InlinePiece::Image(anchor) => {
1319 let mut seg = InlineSegment {
1320 content: InlineContent::Image {
1321 name: anchor.name.clone(),
1322 alt: anchor.alt.clone(),
1323 width: anchor.width,
1324 height: anchor.height,
1325 quality: anchor.quality,
1326 },
1327 ..Default::default()
1328 };
1329 apply_character_format_to_segment(&mut seg, &anchor.format);
1330 seg
1331 }
1332 InlinePiece::FootnoteRef(anchor) => {
1333 let mut seg = InlineSegment {
1334 content: InlineContent::FootnoteRef {
1335 label: anchor.label.clone(),
1336 },
1337 ..Default::default()
1338 };
1339 apply_character_format_to_segment(&mut seg, &anchor.format);
1340 seg
1341 }
1342 })
1343 .collect()
1344}
1345
1346#[cfg(test)]
1347mod tests {
1348 use super::*;
1349
1350 fn run(s: u32, e: u32, bold: bool) -> FormatRun {
1351 FormatRun {
1352 byte_start: s,
1353 byte_end: e,
1354 format: CharacterFormat {
1355 font_bold: Some(bold),
1356 ..Default::default()
1357 },
1358 }
1359 }
1360
1361 #[test]
1362 fn empty_runs_are_well_formed() {
1363 debug_assert_well_formed(&[], 0);
1364 debug_assert_well_formed(&[], 100);
1365 }
1366
1367 fn link(s: u32, e: u32, bold: Option<bool>) -> FormatRun {
1370 FormatRun {
1371 byte_start: s,
1372 byte_end: e,
1373 format: CharacterFormat {
1374 font_bold: bold,
1375 anchor_href: Some("https://example.org".into()),
1376 anchor_names: vec!["target".into()],
1377 is_anchor: Some(true),
1378 tooltip: Some("Example".into()),
1379 ..Default::default()
1380 },
1381 }
1382 }
1383
1384 #[test]
1385 fn typed_at_the_start_of_a_block_extends_its_first_run() {
1386 let mut runs = vec![run(0, 4, true), run(4, 8, false)];
1387 shift_runs_for_typed_insert(&mut runs, 0, 2);
1388 assert_eq!(runs, vec![run(0, 6, true), run(6, 10, false)]);
1389 }
1390
1391 #[test]
1392 fn typed_before_a_link_at_the_start_of_a_block_is_not_part_of_the_link() {
1393 let mut runs = vec![link(0, 4, Some(true)), run(4, 8, false)];
1394 shift_runs_for_typed_insert(&mut runs, 0, 2);
1395 assert_eq!(
1396 runs,
1397 vec![run(0, 2, true), link(2, 6, Some(true)), run(6, 10, false)],
1398 "the typed text keeps the bold and leaves the link out"
1399 );
1400 debug_assert_well_formed(&runs, 10);
1401
1402 let mut runs = vec![link(0, 4, None)];
1403 shift_runs_for_typed_insert(&mut runs, 0, 2);
1404 assert_eq!(runs, vec![link(2, 6, None)], "a bare link leaves it plain");
1405 debug_assert_well_formed(&runs, 6);
1406 }
1407
1408 fn anchor(at: u32, name: &str) -> ImageAnchor {
1411 ImageAnchor {
1412 byte_offset: at,
1413 name: name.into(),
1414 alt: String::new(),
1415 width: 10,
1416 height: 10,
1417 quality: 100,
1418 format: CharacterFormat::default(),
1419 }
1420 }
1421
1422 fn fn_anchor(at: u32, label: &str) -> FootnoteRefAnchor {
1423 FootnoteRefAnchor {
1424 byte_offset: at,
1425 label: label.into(),
1426 format: CharacterFormat::default(),
1427 }
1428 }
1429
1430 fn shape(text: &str, runs: &[FormatRun], images: &[ImageAnchor]) -> String {
1434 shape_with(text, runs, images, &[])
1435 }
1436
1437 fn shape_with(
1438 text: &str,
1439 runs: &[FormatRun],
1440 images: &[ImageAnchor],
1441 notes: &[FootnoteRefAnchor],
1442 ) -> String {
1443 merge_runs_and_anchors(text, runs, &block_anchors(images, notes))
1444 .into_iter()
1445 .map(|p| match p {
1446 InlinePiece::Text { start, end, format } => {
1447 let s = &text[start as usize..end as usize];
1448 if format.is_some() {
1449 format!("*{s}*")
1450 } else {
1451 s.to_string()
1452 }
1453 }
1454 InlinePiece::Image(a) => format!("[{}]", a.name),
1455 InlinePiece::FootnoteRef(a) => format!("^{}^", a.label),
1456 })
1457 .collect::<Vec<_>>()
1458 .join("|")
1459 }
1460
1461 #[test]
1464 fn a_footnote_reference_inside_a_run_splits_it() {
1465 let text = "abcdef";
1466 let runs = [run(0, 6, true)];
1467 assert_eq!(
1468 shape_with(text, &runs, &[], &[fn_anchor(3, "n1")]),
1469 "*abc*|^n1^|*def*"
1470 );
1471 }
1472
1473 #[test]
1479 fn images_and_references_interleave_by_position() {
1480 let text = "abcdefgh";
1481 assert_eq!(
1482 shape_with(
1483 text,
1484 &[],
1485 &[anchor(6, "img")],
1486 &[fn_anchor(2, "early"), fn_anchor(7, "late")]
1487 ),
1488 "ab|^early^|cdef|[img]|g|^late^|h"
1489 );
1490 }
1491
1492 #[test]
1498 fn an_image_inside_a_run_splits_it_instead_of_jumping_to_the_end() {
1499 let text = "abcdef";
1500 let runs = [run(0, 6, true)];
1501 let images = [anchor(3, "img")];
1502 assert_eq!(shape(text, &runs, &images), "*abc*|[img]|*def*");
1503 }
1504
1505 #[test]
1506 fn an_image_on_a_run_start_boundary_stays_in_place() {
1507 let text = "abcdef";
1508 let runs = [run(3, 6, true)];
1509 assert_eq!(shape(text, &runs, &[anchor(3, "i")]), "abc|[i]|*def*");
1510 }
1511
1512 #[test]
1515 fn an_image_on_a_run_end_boundary_stays_in_place() {
1516 let text = "abcdef";
1517 let runs = [run(0, 3, true)];
1518 assert_eq!(shape(text, &runs, &[anchor(3, "i")]), "*abc*|[i]|def");
1519 }
1520
1521 #[test]
1522 fn an_image_between_two_runs_lands_between_them() {
1523 let text = "abcdef";
1524 let runs = [run(0, 3, true), run(3, 6, false)];
1525 let out = shape(text, &runs, &[anchor(3, "i")]);
1526 assert_eq!(out, "*abc*|[i]|*def*");
1527 }
1528
1529 #[test]
1530 fn several_images_inside_one_run_keep_their_order() {
1531 let text = "abcdefgh";
1532 let runs = [run(0, 8, true)];
1533 let images = [anchor(2, "a"), anchor(5, "b")];
1534 assert_eq!(shape(text, &runs, &images), "*ab*|[a]|*cde*|[b]|*fgh*");
1535 }
1536
1537 #[test]
1538 fn two_images_at_the_same_offset_both_survive_in_order() {
1539 let text = "abcd";
1540 let runs = [run(0, 4, true)];
1541 let images = [anchor(2, "a"), anchor(2, "b")];
1542 assert_eq!(shape(text, &runs, &images), "*ab*|[a]|[b]|*cd*");
1543 }
1544
1545 #[test]
1546 fn images_with_no_runs_at_all_are_ordered_with_their_gaps() {
1547 let text = "abcdef";
1548 let images = [anchor(0, "a"), anchor(3, "b"), anchor(6, "c")];
1549 assert_eq!(shape(text, &[], &images), "[a]|abc|[b]|def|[c]");
1550 }
1551
1552 #[test]
1553 fn text_uncovered_by_any_run_stays_unformatted() {
1554 let text = "abcdef";
1555 let runs = [run(2, 4, true)];
1556 assert_eq!(shape(text, &runs, &[]), "ab|*cd*|ef");
1557 }
1558
1559 #[test]
1560 fn a_block_with_neither_runs_nor_images_is_one_plain_piece() {
1561 assert_eq!(shape("abc", &[], &[]), "abc");
1562 assert_eq!(shape("", &[], &[]), "");
1563 }
1564
1565 #[test]
1569 fn every_byte_is_emitted_exactly_once_and_in_order() {
1570 let text = "abcdefghij";
1571 let arrangements: [(&[FormatRun], &[ImageAnchor]); 6] = [
1572 (&[], &[]),
1573 (&[run(0, 10, true)], &[anchor(5, "m")]),
1574 (&[run(2, 5, true), run(5, 8, false)], &[anchor(5, "m")]),
1575 (&[run(2, 5, true)], &[anchor(0, "a"), anchor(10, "z")]),
1576 (&[run(0, 3, true), run(7, 10, true)], &[anchor(3, "m")]),
1577 (
1578 &[run(1, 4, true), run(4, 9, false)],
1579 &[anchor(1, "a"), anchor(4, "b"), anchor(9, "c")],
1580 ),
1581 ];
1582 for (i, (runs, images)) in arrangements.iter().enumerate() {
1583 let pieces = merge_runs_and_anchors(text, runs, &block_anchors(images, &[]));
1584 let mut cursor = 0u32;
1585 let mut rebuilt = String::new();
1586 for piece in &pieces {
1587 if let InlinePiece::Text { start, end, .. } = piece {
1588 assert_eq!(*start, cursor, "arrangement {i}: gap or overlap");
1589 assert!(start < end, "arrangement {i}: empty piece emitted");
1590 rebuilt.push_str(&text[*start as usize..*end as usize]);
1591 cursor = *end;
1592 }
1593 }
1594 assert_eq!(cursor, text.len() as u32, "arrangement {i}: truncated");
1595 assert_eq!(rebuilt, text, "arrangement {i}");
1596 let img_count = pieces
1597 .iter()
1598 .filter(|p| matches!(p, InlinePiece::Image(_)))
1599 .count();
1600 assert_eq!(img_count, images.len(), "arrangement {i}: lost an image");
1601 }
1602 }
1603
1604 #[test]
1606 fn inline_segments_view_places_a_mid_run_image_correctly() {
1607 let segs = inline_segments_view("abcdef", &[run(0, 6, true)], &[anchor(3, "img")], &[]);
1608 assert_eq!(segs.len(), 3);
1609 assert!(matches!(&segs[0].content, InlineContent::Text(t) if t == "abc"));
1610 assert!(matches!(&segs[1].content, InlineContent::Image { name, .. } if name == "img"));
1611 assert!(matches!(&segs[2].content, InlineContent::Text(t) if t == "def"));
1612 assert_eq!(segs[0].fmt_font_bold, Some(true));
1614 assert_eq!(segs[2].fmt_font_bold, Some(true));
1615 }
1616
1617 #[test]
1618 fn inline_segments_view_carries_alt_text_through() {
1619 let mut a = anchor(1, "img");
1620 a.alt = "a black cat".into();
1621 let segs = inline_segments_view("ab", &[], &[a], &[]);
1622 let alt = segs.iter().find_map(|s| match &s.content {
1623 InlineContent::Image { alt, .. } => Some(alt.clone()),
1624 _ => None,
1625 });
1626 assert_eq!(alt.as_deref(), Some("a black cat"));
1627 }
1628
1629 fn pieces_shape(out: &[AddressableInlinePiece]) -> Vec<(u32, u32, String)> {
1634 out.iter()
1635 .map(|p| {
1636 let label = match &p.content {
1637 InlineContent::Text(t) => t.clone(),
1638 InlineContent::Image { name, .. } => format!("[{name}]"),
1639 InlineContent::FootnoteRef { label } => format!("^{label}^"),
1640 InlineContent::Empty => String::new(),
1641 };
1642 (p.start, p.end, label)
1643 })
1644 .collect()
1645 }
1646
1647 #[test]
1648 fn a_lone_text_piece_spans_its_char_length() {
1649 let out = addressable_inline_pieces("hello", &[], &[], 0);
1650 assert_eq!(pieces_shape(&out), vec![(0, 5, "hello".to_string())]);
1651 }
1652
1653 #[test]
1654 fn base_char_offset_shifts_every_piece_by_the_same_amount() {
1655 let out = addressable_inline_pieces("hello", &[], &[], 100);
1656 assert_eq!(pieces_shape(&out), vec![(100, 105, "hello".to_string())]);
1657 }
1658
1659 #[test]
1665 fn a_multibyte_character_before_an_image_does_not_leak_its_extra_byte_into_the_char_position() {
1666 let text = "café";
1667 assert_eq!(text.len(), 5, "test assumes café is 5 bytes");
1668 assert_eq!(text.chars().count(), 4, "test assumes café is 4 chars");
1669 let images = [anchor(5, "pic")]; let anchors = block_anchors(&images, &[]);
1671 let out = addressable_inline_pieces(text, &[], &anchors, 0);
1672 assert_eq!(
1673 pieces_shape(&out),
1674 vec![(0, 4, "café".to_string()), (4, 5, "[pic]".to_string())]
1675 );
1676 }
1677
1678 #[test]
1683 fn an_image_mid_run_gets_a_one_char_span_and_the_trailing_text_resumes_right_after_it() {
1684 let text = "abcdef";
1685 let runs = [run(0, 6, true)];
1686 let images = [anchor(3, "img")];
1687 let anchors = block_anchors(&images, &[]);
1688 let out = addressable_inline_pieces(text, &runs, &anchors, 0);
1689 assert_eq!(
1690 pieces_shape(&out),
1691 vec![
1692 (0, 3, "abc".to_string()),
1693 (3, 4, "[img]".to_string()),
1694 (4, 7, "def".to_string()),
1695 ]
1696 );
1697 }
1698
1699 #[test]
1702 fn a_footnote_reference_gets_a_one_char_span_too() {
1703 let text = "abcdef";
1704 let notes = [fn_anchor(3, "n1")];
1705 let anchors = block_anchors(&[], ¬es);
1706 let out = addressable_inline_pieces(text, &[], &anchors, 0);
1707 assert_eq!(
1708 pieces_shape(&out),
1709 vec![
1710 (0, 3, "abc".to_string()),
1711 (3, 4, "^n1^".to_string()),
1712 (4, 7, "def".to_string()),
1713 ]
1714 );
1715 }
1716
1717 #[test]
1721 fn pieces_are_contiguous_in_char_space_with_no_gaps_or_overlaps() {
1722 let text = "abcdefghij";
1723 let arrangements: [(&[FormatRun], &[ImageAnchor]); 4] = [
1724 (&[], &[]),
1725 (&[run(0, 10, true)], &[anchor(5, "m")]),
1726 (&[run(2, 5, true), run(5, 8, false)], &[anchor(5, "m")]),
1727 (&[run(1, 4, true), run(4, 9, false)], &[anchor(9, "c")]),
1728 ];
1729 for (i, (runs, images)) in arrangements.iter().enumerate() {
1730 let anchors = block_anchors(images, &[]);
1731 let out = addressable_inline_pieces(text, runs, &anchors, 7);
1732 let mut cursor = 7u32;
1733 for piece in &out {
1734 assert_eq!(piece.start, cursor, "arrangement {i}: gap or overlap");
1735 assert!(piece.start < piece.end, "arrangement {i}: empty piece");
1736 cursor = piece.end;
1737 }
1738 assert_eq!(
1742 cursor,
1743 7 + text.chars().count() as u32 + images.len() as u32,
1744 "arrangement {i}: did not tile the whole block"
1745 );
1746 }
1747 }
1748
1749 #[test]
1750 fn coalesce_merges_adjacent_equal_runs() {
1751 let mut rs = vec![run(0, 5, true), run(5, 10, true), run(10, 15, false)];
1752 coalesce_in_place(&mut rs);
1753 assert_eq!(rs.len(), 2);
1754 assert_eq!(rs[0].byte_end, 10);
1755 }
1756
1757 #[test]
1758 fn coalesce_leaves_disjoint_runs_alone() {
1759 let mut rs = vec![run(0, 5, true), run(7, 10, true)];
1760 coalesce_in_place(&mut rs);
1761 assert_eq!(rs.len(), 2);
1762 }
1763
1764 #[test]
1765 fn splice_range_clips_straddling_runs() {
1766 let mut rs = vec![run(0, 20, true)];
1767 splice_range(&mut rs, 5..15, vec![run(5, 15, false)]);
1768 assert_eq!(rs.len(), 3);
1769 assert_eq!(rs[0].byte_end, 5);
1770 assert_eq!(rs[1].format.font_bold, Some(false));
1771 assert_eq!(rs[2].byte_start, 15);
1772 }
1773
1774 #[test]
1775 fn splice_range_empty_replacement_removes_inner_runs() {
1776 let mut rs = vec![run(0, 5, true), run(5, 10, false), run(10, 15, true)];
1777 splice_range(&mut rs, 5..10, vec![]);
1778 assert_eq!(rs.len(), 2);
1781 assert_eq!(rs[0].byte_end, 5);
1782 assert_eq!(rs[1].byte_start, 10);
1783 }
1784
1785 #[test]
1786 fn shift_after_moves_downstream() {
1787 let mut rs = vec![run(0, 5, true), run(10, 15, false)];
1788 shift_after(&mut rs, 5, 3);
1789 assert_eq!(rs[0].byte_start, 0); assert_eq!(rs[1].byte_start, 13);
1791 assert_eq!(rs[1].byte_end, 18);
1792 }
1793}
1794
1795#[cfg(test)]
1802mod replace_policy_tests {
1803 use super::*;
1804
1805 fn fmt(tag: &str) -> CharacterFormat {
1806 CharacterFormat {
1807 font_bold: Some(tag == "B"),
1808 font_italic: Some(tag == "I"),
1809 ..Default::default()
1810 }
1811 }
1812 fn r(start: u32, end: u32, tag: &str) -> FormatRun {
1813 FormatRun {
1814 byte_start: start,
1815 byte_end: end,
1816 format: fmt(tag),
1817 }
1818 }
1819 fn show(runs: &[FormatRun]) -> String {
1821 if runs.is_empty() {
1822 return "[]".to_string();
1823 }
1824 runs.iter()
1825 .map(|x| {
1826 let tag = if x.format.font_bold == Some(true) {
1827 "B"
1828 } else if x.format.font_italic == Some(true) {
1829 "I"
1830 } else {
1831 "p"
1832 };
1833 format!("{}..{}={tag}", x.byte_start, x.byte_end)
1834 })
1835 .collect::<Vec<_>>()
1836 .join(" ")
1837 }
1838 fn replace(
1839 runs: &[FormatRun],
1840 start: u32,
1841 end: u32,
1842 n: u32,
1843 policy: ReplaceFormatPolicy,
1844 ) -> Vec<FormatRun> {
1845 let mut runs = runs.to_vec();
1846 shift_runs_for_replace(&mut runs, start, end, n, policy).expect("valid replace");
1847 runs
1848 }
1849
1850 #[test]
1857 fn inherit_preceding_matches_the_historical_delete_then_insert() {
1858 let corpus: Vec<(&str, Vec<FormatRun>, u32, u32, u32)> = vec![
1859 ("run ends exactly at start", vec![r(0, 5, "B")], 5, 10, 3),
1860 ("run begins exactly at start", vec![r(5, 8, "B")], 5, 10, 3),
1861 (
1862 "run begins at start, outlives end",
1863 vec![r(5, 20, "B")],
1864 5,
1865 10,
1866 3,
1867 ),
1868 (
1869 "run straddles the whole range",
1870 vec![r(0, 20, "B")],
1871 5,
1872 10,
1873 3,
1874 ),
1875 ("no run touches the start", vec![r(12, 20, "B")], 5, 10, 3),
1876 ("bold tail inside the range", vec![r(9, 13, "B")], 5, 13, 4),
1877 ("pure delete", vec![r(0, 20, "B")], 5, 10, 0),
1878 ("pure insert", vec![r(0, 20, "B")], 5, 5, 3),
1879 (
1880 "same format either side coalesces",
1881 vec![r(0, 5, "B"), r(10, 15, "B")],
1882 5,
1883 10,
1884 3,
1885 ),
1886 (
1887 "different formats either side",
1888 vec![r(0, 5, "B"), r(10, 15, "I")],
1889 5,
1890 10,
1891 3,
1892 ),
1893 ("empty run list", vec![], 5, 10, 3),
1894 ("the only run is consumed", vec![r(5, 10, "B")], 5, 10, 3),
1895 (
1896 "replacement longer than the range",
1897 vec![r(0, 5, "B")],
1898 5,
1899 10,
1900 20,
1901 ),
1902 (
1903 "three runs straddled",
1904 vec![r(0, 3, "B"), r(3, 6, "I"), r(6, 9, "B")],
1905 2,
1906 7,
1907 4,
1908 ),
1909 (
1910 "gap between two same-format runs is deleted",
1911 vec![r(0, 5, "B"), r(8, 13, "B")],
1912 5,
1913 8,
1914 0,
1915 ),
1916 ];
1917
1918 for (name, runs, start, end, n) in corpus {
1919 let mut expected = runs.clone();
1921 shift_runs_for_delete(&mut expected, start, end);
1922 shift_runs_for_insert(&mut expected, start, n);
1923
1924 let got = replace(&runs, start, end, n, ReplaceFormatPolicy::InheritPreceding);
1925
1926 assert_eq!(
1927 show(&got),
1928 show(&expected),
1929 "InheritPreceding diverged from delete+insert for {name:?} \
1930 (replace {start}..{end}, n={n})\n before: {}\n historical: {}\n got: {}",
1931 show(&runs),
1932 show(&expected),
1933 show(&got),
1934 );
1935 }
1936 }
1937
1938 #[test]
1942 fn the_four_policies_diverge_on_a_partly_bold_name() {
1943 let runs = vec![r(5, 9, "B")];
1945 let (start, end, n) = (0, 9, 9); use ReplaceFormatPolicy::*;
1948 assert_eq!(
1949 show(&replace(&runs, start, end, n, InheritPreceding)),
1950 "[]",
1951 "the historical default destroys the bold — pinned, not endorsed"
1952 );
1953 assert_eq!(
1954 show(&replace(&runs, start, end, n, PreserveNothing)),
1955 "[]",
1956 "explicitly unformatted"
1957 );
1958 assert_eq!(
1959 show(&replace(&runs, start, end, n, PreserveIfFullyCovered)),
1960 "[]",
1961 "no SINGLE run covers 0..9 — it must fall back to inheritance, not guess"
1962 );
1963 assert_eq!(
1965 show(&replace(&runs, start, end, n, KeepDominantRun)),
1966 "[]",
1967 "plain covers more of the name than the bold does"
1968 );
1969
1970 let mostly_bold = vec![r(1, 9, "B")];
1972 assert_eq!(
1973 show(&replace(&mostly_bold, 0, 9, 9, KeepDominantRun)),
1974 "0..9=B",
1975 "bold covers 8 of 9 bytes — the rename must keep it"
1976 );
1977 }
1978
1979 #[test]
1983 fn fully_covered_means_a_single_run_not_a_gapless_union() {
1984 let two = vec![r(0, 3, "I"), r(3, 10, "B")];
1985 assert_eq!(
1986 show(&replace(
1987 &two,
1988 0,
1989 10,
1990 4,
1991 ReplaceFormatPolicy::PreserveIfFullyCovered
1992 )),
1993 "[]",
1994 "two different-format runs jointly spanning the range are not 'covered'; \
1995 with no run preceding the start, the fallback is unformatted"
1996 );
1997
1998 let one = vec![r(5, 20, "B")];
2001 assert_eq!(
2002 show(&replace(
2003 &one,
2004 5,
2005 10,
2006 3,
2007 ReplaceFormatPolicy::PreserveIfFullyCovered
2008 )),
2009 "5..18=B",
2010 "a single covering run keeps its format across the rename"
2011 );
2012 assert_eq!(
2013 show(&replace(
2014 &one,
2015 5,
2016 10,
2017 3,
2018 ReplaceFormatPolicy::InheritPreceding
2019 )),
2020 "8..18=B",
2021 "…which the default would have lost: the replacement lands unformatted"
2022 );
2023 }
2024
2025 #[test]
2028 fn a_partially_overlapping_run_does_not_count_as_covering() {
2029 let runs = vec![r(0, 8, "B")]; assert_eq!(
2031 show(&replace(
2032 &runs,
2033 5,
2034 12,
2035 4,
2036 ReplaceFormatPolicy::PreserveIfFullyCovered
2037 )),
2038 "0..9=B",
2039 "not covered → falls back to inheritance, which extends the preceding bold; \
2040 it must NOT format the whole replacement as though bold had covered it"
2041 );
2042 }
2043
2044 #[test]
2049 fn a_dominance_tie_between_two_runs_goes_to_the_earlier() {
2050 let runs = vec![r(0, 3, "B"), r(3, 6, "I")]; assert_eq!(
2052 show(&replace(
2053 &runs,
2054 0,
2055 6,
2056 4,
2057 ReplaceFormatPolicy::KeepDominantRun
2058 )),
2059 "0..4=B",
2060 "a true tie must resolve to the earlier run, not to whichever the iterator \
2061 happened to visit last"
2062 );
2063 }
2064
2065 #[test]
2068 fn a_dominance_tie_against_plain_text_keeps_the_formatting() {
2069 let runs = vec![r(4, 8, "B")]; assert_eq!(
2071 show(&replace(
2072 &runs,
2073 0,
2074 8,
2075 5,
2076 ReplaceFormatPolicy::KeepDominantRun
2077 )),
2078 "0..5=B",
2079 "an even split must keep the formatting rather than silently drop it"
2080 );
2081 }
2082
2083 #[test]
2087 fn an_empty_range_is_an_insert_and_no_coverage_policy_overrides_it() {
2088 let runs = vec![r(0, 5, "B"), r(5, 10, "I")];
2089 use ReplaceFormatPolicy::*;
2090 for policy in [InheritPreceding, PreserveIfFullyCovered, KeepDominantRun] {
2091 assert_eq!(
2092 show(&replace(&runs, 5, 5, 2, policy)),
2093 "0..7=B 7..12=I",
2094 "{policy:?}: typing at a boundary must inherit the run to the LEFT (Qt \
2095 convention) — an empty range destroyed no formatting, so there is \
2096 nothing for a coverage policy to override"
2097 );
2098 }
2099 assert_eq!(
2101 show(&replace(&runs, 5, 5, 2, PreserveNothing)),
2102 "0..5=B 7..12=I",
2103 "PreserveNothing asks for unformatted text, and means it even on an insert"
2104 );
2105 }
2106
2107 #[test]
2109 fn a_zero_width_zero_length_replace_is_the_identity() {
2110 let runs = vec![r(0, 5, "B"), r(7, 12, "I")];
2111 for policy in [
2112 ReplaceFormatPolicy::InheritPreceding,
2113 ReplaceFormatPolicy::PreserveIfFullyCovered,
2114 ReplaceFormatPolicy::KeepDominantRun,
2115 ReplaceFormatPolicy::PreserveNothing,
2116 ] {
2117 assert_eq!(
2118 show(&replace(&runs, 6, 6, 0, policy)),
2119 "0..5=B 7..12=I",
2120 "{policy:?} changed a no-op edit"
2121 );
2122 }
2123 }
2124
2125 #[test]
2129 fn preserve_nothing_fabricates_no_default_run() {
2130 let runs = vec![r(0, 5, "B")];
2131 let got = replace(&runs, 7, 9, 2, ReplaceFormatPolicy::PreserveNothing);
2132 assert_eq!(show(&got), "0..5=B", "no run may be invented for the gap");
2133 assert!(
2134 got.iter().all(|x| x.byte_start < 7 || x.byte_end > 9),
2135 "the replaced span must carry no run at all"
2136 );
2137 }
2138
2139 #[test]
2142 fn offsets_are_bytes_not_characters() {
2143 let runs = vec![r(0, 4, "B"), r(5, 9, "I")];
2145 let got = replace(&runs, 0, 4, 2, ReplaceFormatPolicy::KeepDominantRun);
2146 assert_eq!(
2147 show(&got),
2148 "0..2=B 3..7=I",
2149 "the trailing italic must shift back by the BYTE delta (4 -> 2 = -2)"
2150 );
2151 }
2152
2153 #[test]
2157 fn every_policy_leaves_the_runs_well_formed() {
2158 let setups: Vec<(Vec<FormatRun>, u32, u32, u32, usize)> = vec![
2159 (vec![r(0, 3, "B"), r(3, 6, "I"), r(6, 9, "B")], 2, 7, 4, 8),
2160 (vec![r(0, 5, "B"), r(8, 13, "B")], 5, 8, 0, 10),
2161 (vec![r(0, 5, "B"), r(7, 12, "B")], 8, 10, 2, 12),
2162 (vec![r(3, 7, "B")], 3, 7, 0, 6),
2163 (vec![], 2, 6, 3, 9),
2164 ];
2165 for (runs, start, end, n, text_len) in setups {
2166 for policy in [
2167 ReplaceFormatPolicy::InheritPreceding,
2168 ReplaceFormatPolicy::PreserveIfFullyCovered,
2169 ReplaceFormatPolicy::KeepDominantRun,
2170 ReplaceFormatPolicy::PreserveNothing,
2171 ] {
2172 let got = replace(&runs, start, end, n, policy);
2173 check_well_formed(&got, text_len).unwrap_or_else(|e| {
2174 panic!(
2175 "{policy:?} produced malformed runs from {} (replace {start}..{end}, \
2176 n={n}): {} — {e}",
2177 show(&runs),
2178 show(&got)
2179 )
2180 });
2181 }
2182 }
2183 }
2184
2185 #[test]
2189 fn an_untouched_gap_between_equal_runs_survives() {
2190 let runs = vec![r(0, 5, "B"), r(7, 12, "B")];
2191 assert_eq!(
2192 show(&replace(
2193 &runs,
2194 8,
2195 10,
2196 2,
2197 ReplaceFormatPolicy::InheritPreceding
2198 )),
2199 "0..5=B 7..12=B",
2200 "the plain gap at 5..7 must not be swallowed"
2201 );
2202 }
2203
2204 #[test]
2206 fn an_inverted_range_is_an_error_not_a_panic() {
2207 let mut runs = vec![r(0, 5, "B")];
2208 let err =
2209 shift_runs_for_replace(&mut runs, 10, 5, 3, ReplaceFormatPolicy::InheritPreceding)
2210 .expect_err("an inverted range must be rejected");
2211 assert!(matches!(
2212 err,
2213 FormatRunError::ReversedRange { start: 10, end: 5 }
2214 ));
2215 assert_eq!(show(&runs), "0..5=B", "a refused edit must change nothing");
2216 }
2217}
2218
2219#[cfg(test)]
2221mod invariant_check_tests {
2222 use super::*;
2223
2224 fn run(start: u32, end: u32, bold: bool) -> FormatRun {
2225 FormatRun {
2226 byte_start: start,
2227 byte_end: end,
2228 format: CharacterFormat {
2229 font_bold: Some(bold),
2230 ..Default::default()
2231 },
2232 }
2233 }
2234
2235 #[test]
2239 fn a_replacement_outside_the_range_is_rejected_without_mutating() {
2240 let mut runs = vec![run(0, 20, true)];
2241 let before = runs.clone();
2242
2243 let err = try_splice_range(&mut runs, 5..10, vec![run(5, 15, false)])
2244 .expect_err("a replacement run reaching past range.end must be rejected");
2245
2246 assert!(matches!(
2247 err,
2248 FormatRunError::ReplacementOutsideRange {
2249 run_end: 15,
2250 range_end: 10,
2251 ..
2252 }
2253 ));
2254 assert_eq!(
2255 runs, before,
2256 "a rejected splice must not half-apply — validation happens before mutation"
2257 );
2258 }
2259
2260 #[test]
2261 #[allow(clippy::reversed_empty_ranges)]
2264 fn a_reversed_range_is_rejected() {
2265 let mut runs = vec![run(0, 20, true)];
2266 assert!(matches!(
2267 try_splice_range(&mut runs, 10..5, vec![]),
2268 Err(FormatRunError::ReversedRange { start: 10, end: 5 })
2269 ));
2270 }
2271
2272 #[test]
2273 fn a_legal_splice_still_works_through_the_checked_path() {
2274 let mut runs = vec![run(0, 20, true)];
2275 try_splice_range(&mut runs, 5..15, vec![run(5, 15, false)]).expect("legal");
2276 assert_eq!(runs.len(), 3);
2277 assert_eq!(runs[1].format.font_bold, Some(false));
2278 }
2279
2280 #[test]
2281 fn check_well_formed_catches_what_debug_assert_used_to() {
2282 assert!(check_well_formed(&[], 0).is_ok());
2283 assert!(check_well_formed(&[run(0, 5, true)], 5).is_ok());
2284
2285 assert!(matches!(
2286 check_well_formed(&[run(5, 5, true)], 10),
2287 Err(FormatRunError::EmptyRun { .. })
2288 ));
2289 assert!(matches!(
2290 check_well_formed(&[run(0, 8, true), run(5, 10, false)], 10),
2291 Err(FormatRunError::RunsOverlap { .. })
2292 ));
2293 assert!(matches!(
2294 check_well_formed(&[run(0, 5, true), run(5, 10, true)], 10),
2295 Err(FormatRunError::RunsNotCoalesced { .. })
2296 ));
2297 assert!(matches!(
2298 check_well_formed(&[run(0, 20, true)], 10),
2299 Err(FormatRunError::RunPastEndOfBlock { text_len: 10, .. })
2300 ));
2301 }
2302}