1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
use crate::{dyn_styles::StyleFlags, Style, Styled};
use core::{
    fmt::{self, Display},
    marker::PhantomData,
};

#[cfg(feature = "alloc")]
extern crate alloc;

// Hidden trait for use in `StyledList` bounds
mod sealed {
    pub trait IsStyled {
        type Inner: core::fmt::Display;

        fn style(&self) -> &crate::Style;
        fn inner(&self) -> &Self::Inner;
    }
}

use sealed::IsStyled;

impl<T: IsStyled> IsStyled for &T {
    type Inner = T::Inner;

    fn style(&self) -> &Style {
        <T as IsStyled>::style(*self)
    }

    fn inner(&self) -> &Self::Inner {
        <T as IsStyled>::inner(*self)
    }
}

impl<T: Display> IsStyled for Styled<T> {
    type Inner = T;

    fn style(&self) -> &Style {
        &self.style
    }

    fn inner(&self) -> &T {
        &self.target
    }
}

/// A collection of [`Styled`] items that are displayed in such a way as to minimize the amount of characters
/// that are written when displayed.
///
/// ```rust
/// use owo_colors::{Style, Styled, StyledList};
///
/// let styled_items = [
///     Style::new().red().style("Hello "),
///     Style::new().green().style("World"),
///  ];
///
/// // 29 characters
/// let normal_length = styled_items.iter().map(|item| format!("{}", item).len()).sum::<usize>();
/// // 25 characters
/// let styled_length = format!("{}", StyledList::from(styled_items)).len();
///
/// assert!(styled_length < normal_length);
/// ```
pub struct StyledList<T, U>(pub T, PhantomData<fn(U)>)
where
    T: AsRef<[U]>,
    U: IsStyled;

impl<T, U> From<T> for StyledList<T, U>
where
    T: AsRef<[U]>,
    U: IsStyled,
{
    fn from(list: T) -> Self {
        Self(list, PhantomData)
    }
}

impl<T, U> Display for StyledList<T, U>
where
    T: AsRef<[U]>,
    U: IsStyled,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Handle first item manually
        let first_item = match self.0.as_ref().first() {
            Some(s) => s,
            None => return Ok(()),
        };

        first_item.style().fmt_prefix(f)?;
        write!(f, "{}", first_item.inner())?;

        // Handle the rest
        for window in self.0.as_ref().windows(2) {
            let prev = &window[0];
            let current = &window[1];

            write!(
                f,
                "{}{}",
                current.style().transition_from(prev.style()),
                current.inner()
            )?;
        }

        // Print final reset
        // SAFETY: We know that the first item exists, thus a last item exists
        self.0.as_ref().last().unwrap().style().fmt_suffix(f)
    }
}

impl<'a> Style {
    /// Returns an enum that indicates how the transition from one style to this style should be printed
    fn transition_from(&'a self, from: &Style) -> Transition<'a> {
        if self == from {
            return Transition::Noop;
        }

        // Use full reset if transitioning from colored to non-colored
        // or if previous style contains properties that are not in this style
        if (from.fg.is_some() && self.fg.is_none())
            || (from.bg.is_some() && self.bg.is_none())
            || (from.bold && !self.bold)
            || (!self.style_flags.0 & from.style_flags.0) != 0
        {
            return Transition::FullReset(self);
        }

        // Build up a transition style, that does not require a full reset
        // Contains all properties from `self` that are not in `from`
        let fg = match (self.fg, from.fg) {
            (Some(fg), Some(from_fg)) if fg != from_fg => Some(fg),
            (Some(fg), None) => Some(fg),
            _ => None,
        };

        let bg = match (self.bg, from.bg) {
            (Some(bg), Some(from_bg)) if bg != from_bg => Some(bg),
            (Some(bg), None) => Some(bg),
            _ => None,
        };

        let new_style = Style {
            fg,
            bg,
            bold: from.bold ^ self.bold,
            style_flags: StyleFlags(self.style_flags.0 ^ from.style_flags.0),
        };

        Transition::Style(new_style)
    }
}

/// How the transition between two styles should be printed
#[cfg_attr(test, derive(Debug, PartialEq))]
enum Transition<'a> {
    Noop,
    FullReset(&'a Style),
    Style(Style),
}

impl fmt::Display for Transition<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            // Styles are equal
            Transition::Noop => Ok(()),
            // Reset the style & print full prefix
            Transition::FullReset(style) => {
                write!(f, "\x1B[0m")?;
                style.fmt_prefix(f)
            }
            // Print transition style without resetting the style
            Transition::Style(style) => style.fmt_prefix(f),
        }
    }
}

/// A helper alias for [`StyledList`] for easier usage with [`alloc::vec::Vec`].
#[cfg(feature = "alloc")]
pub type StyledVec<T> = StyledList<alloc::vec::Vec<Styled<T>>, Styled<T>>;

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_styled_list() {
        let list = &[
            Style::new().red().style("red"),
            Style::new().green().italic().style("green italic"),
            Style::new().red().bold().style("red bold"),
        ];

        let list = StyledList::from(list);

        assert_eq!(
            format!("{}", list),
            "\x1b[31mred\x1b[32;3mgreen italic\x1b[0m\x1b[31;1mred bold\x1b[0m"
        );
    }

    #[test]
    fn test_styled_final_plain() {
        let list = &[
            Style::new().red().style("red"),
            Style::new().green().italic().style("green italic"),
            Style::new().style("plain"),
        ];

        let list = StyledList::from(list);

        assert_eq!(
            format!("{}", list),
            "\x1b[31mred\x1b[32;3mgreen italic\x1b[0mplain"
        );
    }

    #[test]
    fn test_transition_from_noop() {
        let style_current = Style::new().italic().red();
        let style_prev = Style::new().italic().red();

        assert_eq!(style_current.transition_from(&style_prev), Transition::Noop);
    }

    #[test]
    fn test_transition_from_full_reset() {
        let style_current = Style::new().italic().red();
        let style_prev = Style::new().italic().dimmed().red();

        assert_eq!(
            style_current.transition_from(&style_prev),
            Transition::FullReset(&style_current)
        );

        let style_current = Style::new();
        let style_prev = Style::new().red();
        assert_eq!(
            style_current.transition_from(&style_prev),
            Transition::FullReset(&style_current)
        );

        let style_current = Style::new();
        let style_prev = Style::new().bold();
        assert_eq!(
            style_current.transition_from(&style_prev),
            Transition::FullReset(&style_current)
        );
    }

    #[test]
    fn test_transition_from_style() {
        let style_current = Style::new().italic().dimmed().red();
        let style_prev = Style::new().italic().red();

        assert_eq!(
            style_current.transition_from(&style_prev),
            Transition::Style(Style::new().dimmed())
        );

        let style_current = Style::new().red().on_green();
        let style_prev = Style::new().red().on_bright_cyan();
        assert_eq!(
            style_current.transition_from(&style_prev),
            Transition::Style(Style::new().on_green())
        );

        let style_current = Style::new().bold().blue();
        let style_prev = Style::new().bold();
        assert_eq!(
            style_current.transition_from(&style_prev),
            Transition::Style(Style::new().blue())
        );
    }
}