styled_str/types/
mod.rs

1//! Basic types.
2
3use 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/// Text difference between two strings. ANSI-styled when printed.
26///
27/// # [`Display`](fmt::Display) representation
28///
29/// You can specify additional padding at the start of compared lines
30/// via alignment specifiers. For example, `{:>4}` will insert 4 spaces at the start of each line.
31///
32/// # Examples
33///
34/// ```
35/// use styled_str::{StyledString, TextDiff};
36///
37/// let diff = TextDiff::new("Hello, world", "Hello world!");
38/// let diff_str = StyledString::from_ansi(&format!("{diff:>4}"))?;
39/// assert_eq!(
40///     diff_str.text().trim(),
41///     "Diff < left / right > :\n\
42///      <   Hello, world\n\
43///      >   Hello world!"
44/// );
45/// assert!(!diff_str.as_str().is_plain());
46/// # anyhow::Ok(())
47/// ```
48#[derive(Debug)]
49pub struct TextDiff<'a> {
50    lhs: &'a str,
51    rhs: &'a str,
52}
53
54impl<'a> TextDiff<'a> {
55    /// Computes difference between two strings.
56    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
73/// Generic difference between two [`StyledStr`]s: either a difference in text, or in styling.
74///
75/// Produced by the [`StyledStr::diff()`] method.
76pub enum Diff<'a> {
77    /// There is a difference in text between the compared strings.
78    Text(TextDiff<'a>),
79    /// String texts match, but there is a difference in ANSI styles.
80    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
95// Delegates to `Display` to get better panic messages on `.diff(_).unwrap()`.
96impl 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/// Stack-allocated version of [`Styled`] for use in compile-time parsing of rich styling strings.
105#[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    /// Instantiates a new instance from a `rich`-flavored string.
114    ///
115    /// # Panics
116    ///
117    /// Panics if the rich syntax is invalid.
118    #[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}