1use core::fmt;
4
5use self::slice::SpansSlice;
6pub(crate) use self::spans::StyledSpan;
7pub use self::{
8 lines::Lines,
9 spans::SpanStr,
10 str::StyledStr,
11 string::{StyledString, StyledStringBuilder},
12};
13use crate::{
14 StyleDiff,
15 comparison::{highlight_diff, write_diff_header},
16 utils::{Stack, StackStr},
17};
18
19mod lines;
20mod slice;
21mod spans;
22mod str;
23mod string;
24
25#[derive(Debug)]
49pub struct TextDiff<'a> {
50 lhs: &'a str,
51 rhs: &'a str,
52}
53
54impl<'a> TextDiff<'a> {
55 pub const fn new(lhs: &'a str, rhs: &'a str) -> Self {
57 Self { lhs, rhs }
58 }
59}
60
61impl fmt::Display for TextDiff<'_> {
62 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
63 let padding = if matches!(formatter.align(), Some(fmt::Alignment::Right) | None) {
64 formatter.width().map_or(0, |width| width.saturating_sub(1))
65 } else {
66 0
67 };
68 write_diff_header(formatter)?;
69 highlight_diff(formatter, self.lhs, self.rhs, padding)
70 }
71}
72
73pub enum Diff<'a> {
77 Text(TextDiff<'a>),
79 Style(StyleDiff<'a>),
81}
82
83impl fmt::Display for Diff<'_> {
84 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
85 match self {
86 Self::Text(diff) => write!(formatter, "styled strings differ by text\n{diff}"),
87 Self::Style(diff) => write!(
88 formatter,
89 "styled strings differ by style\n{diff}\n{diff:#}"
90 ),
91 }
92 }
93}
94
95impl fmt::Debug for Diff<'_> {
97 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
98 fmt::Display::fmt(self, formatter)
99 }
100}
101
102impl core::error::Error for Diff<'_> {}
103
104#[doc(hidden)]
106#[derive(Debug)]
107pub struct StackStyled<const TEXT_CAP: usize, const SPAN_CAP: usize> {
108 pub(crate) text: StackStr<TEXT_CAP>,
109 pub(crate) spans: Stack<StyledSpan, SPAN_CAP>,
110}
111
112impl<const TEXT_CAP: usize, const SPAN_CAP: usize> StackStyled<TEXT_CAP, SPAN_CAP> {
113 #[track_caller]
119 pub const fn new(raw: &str) -> Self {
120 match Self::parse(raw) {
121 Ok(styled) => styled,
122 Err(err) => err.compile_panic(raw),
123 }
124 }
125
126 pub const fn as_ref(&'static self) -> StyledStr<'static> {
127 StyledStr {
128 text: self.text.as_str(),
129 spans: SpansSlice::new(self.spans.as_slice()),
130 }
131 }
132}