styled_str/types/string.rs
1//! `StyledString` and its builder.
2
3use alloc::{string::String, vec::Vec};
4use core::{fmt, mem, num::NonZeroUsize, ops};
5
6use anstyle::Style;
7
8use super::{StyledStr, slice::SpansSlice, spans::StyledSpan};
9use crate::{AnsiError, ansi_parser::AnsiParser, utils::normalize_style};
10
11/// Builder for [`StyledString`]s.
12///
13/// A builder can be initialized from scratch via [`StyledString::builder()`] or [`Default`].
14/// Alternatively, it can be initialized from an existing [`StyledString`].
15/// A builder can be extended by pushing [text](Self::push_text()), [styles](Self::push_style())
16/// or [`StyledStr`]ings into it.
17///
18/// # Examples
19///
20/// ```
21/// # use styled_str::{styled, StyledString};
22/// # use anstyle::{AnsiColor, Style};
23/// let mut builder = StyledString::builder();
24/// builder.push_style(AnsiColor::BrightGreen.on(AnsiColor::White).bold());
25/// builder.push_text("Hello");
26/// builder.push_text(",");
27/// // It's possible to use `+=` as syntactic sugar for `push_str()` / `push_style()`.
28/// builder += Style::new();
29/// builder.push_text(" world");
30/// builder += styled!("[[it, dim]]!");
31///
32/// let s = builder.build();
33/// assert_eq!(
34/// s.to_string(),
35/// "[[bold green! on white]]Hello,[[/]] world[[italic dim]]!"
36/// );
37/// ```
38#[derive(Debug, Clone, Default)]
39pub struct StyledStringBuilder {
40 inner: StyledString,
41 current_style: Style,
42}
43
44impl StyledStringBuilder {
45 /// Returns the current string text.
46 pub fn text(&self) -> &str {
47 self.inner.text()
48 }
49
50 /// Pushes unstyled text at the end of the string.
51 ///
52 /// # Panics
53 ///
54 /// Panics if `text` contains an ANSI escape char (`\x1b`).
55 pub fn push_text(&mut self, text: &str) {
56 assert!(
57 text.bytes().all(|ch| ch != 0x1b),
58 "Text contains 0x1b escape char"
59 );
60 self.inner.text.push_str(text);
61 }
62
63 pub(crate) fn current_style(&self) -> &Style {
64 &self.current_style
65 }
66
67 /// Pushes a style at the end of this string.
68 pub fn push_style(&mut self, style: Style) {
69 let style = normalize_style(style);
70 let spanned_text_len = self.inner.spans.last().map_or(0, StyledSpan::end);
71 let prev_style = mem::replace(&mut self.current_style, style);
72 if let Some(len) = NonZeroUsize::new(self.inner.text.len() - spanned_text_len) {
73 self.push_span(StyledSpan {
74 style: prev_style,
75 start: spanned_text_len,
76 len,
77 });
78 }
79 }
80
81 fn push_span(&mut self, span: StyledSpan) {
82 if let Some(last_span) = self.inner.spans.last_mut() {
83 if last_span.style == span.style {
84 last_span.extend_len(span.len.get());
85 return;
86 }
87 }
88 self.inner.spans.push(span);
89 }
90
91 /// Pushes a styled string at the end of this string.
92 pub fn push_str(&mut self, s: StyledStr<'_>) {
93 // Flush the current style so that `self.inner` is well-formed, which `StyledString::push_str()` relies upon.
94 self.push_style(self.current_style);
95 self.inner.push_str(s);
96
97 if let Some(last_span) = self.inner.spans.last() {
98 self.current_style = last_span.style;
99 }
100 }
101
102 /// Finalizes the [`StyledString`].
103 pub fn build(mut self) -> StyledString {
104 // Push the last style span covering the non-spanned text
105 self.push_style(Style::new());
106 self.inner
107 }
108}
109
110impl From<StyledString> for StyledStringBuilder {
111 fn from(string: StyledString) -> Self {
112 let current_style = string
113 .spans
114 .last()
115 .map_or_else(Style::new, |span| span.style);
116 Self {
117 inner: string,
118 current_style,
119 }
120 }
121}
122
123impl ops::AddAssign<Style> for StyledStringBuilder {
124 fn add_assign(&mut self, rhs: Style) {
125 self.push_style(rhs);
126 }
127}
128
129impl ops::AddAssign<StyledStr<'_>> for StyledStringBuilder {
130 fn add_assign(&mut self, rhs: StyledStr<'_>) {
131 self.push_str(rhs);
132 }
133}
134
135// We don't implement `AddAssign<&str>` for `StyledStringBuilder` to avoid ambiguity what the string represents.
136
137/// Heap-allocated styled string.
138///
139/// `StyledString` represents the owned string variant in contrast to [`StyledStr`], which is borrowed.
140/// Since [conversion](Self::as_str()) to a `StyledStr` is cheap, some immutable methods are accessible via [`StyledStr`]
141/// only (e.g., [iterating over style spans](StyledStr::spans()) or [splitting a string](StyledStr::split_at())).
142/// This allows to define these methods as `const fn`s and/or to propagate the borrowed data lifetime correctly.
143///
144/// A `StyledString` can be parsed from [rich syntax](crate#rich-syntax) via the [`FromStr`](core::str::FromStr) trait,
145/// from a string with ANSI escapes via [`StyledString::from_ansi()`], or manually constructed via [`StyledStringBuilder`].
146#[derive(Clone, Default, PartialEq)]
147pub struct StyledString<T = String> {
148 pub(crate) text: T,
149 pub(crate) spans: Vec<StyledSpan>,
150}
151
152impl<T> StyledString<T>
153where
154 T: ops::Deref<Target = str>,
155{
156 /// Returns the unstyled text behind this string.
157 pub fn into_text(self) -> T {
158 self.text
159 }
160
161 /// Borrows a [`StyledStr`] from this string. This can be used to call more complex methods.
162 pub fn as_str(&self) -> StyledStr<'_> {
163 StyledStr {
164 text: &self.text,
165 spans: SpansSlice::new(&self.spans),
166 }
167 }
168
169 /// Returns the unstyled text.
170 pub fn text(&self) -> &str {
171 &self.text
172 }
173}
174
175impl StyledString {
176 /// Creates a builder for styled strings.
177 pub fn builder() -> StyledStringBuilder {
178 StyledStringBuilder::default()
179 }
180
181 /// Parses a string from a string with embedded ANSI escape sequences.
182 ///
183 /// # Errors
184 ///
185 /// Returns an error if the input is not a valid ANSI escaped string.
186 ///
187 /// # Examples
188 ///
189 /// ```
190 /// # use styled_str::{styled, StyledString};
191 /// let str = StyledString::from_ansi(
192 /// "\u{1b}[1;32mHello,\u{1b}[m world\u{1b}[3m!\u{1b}[m",
193 /// )?;
194 /// assert_eq!(str, styled!("[[bold green]]Hello,[[/]] world[[it]]!"));
195 /// # anyhow::Ok(())
196 /// ```
197 pub fn from_ansi(ansi_str: &str) -> Result<Self, AnsiError> {
198 AnsiParser::parse(ansi_str.as_bytes())
199 }
200
201 /// Parses a string from bytes with embedded ANSI escape sequences. This is similar to
202 /// [`Self::from_ansi()`], just using bytes as an input.
203 ///
204 /// # Errors
205 ///
206 /// Returns an error if the input is not a valid ANSI escaped string.
207 pub fn from_ansi_bytes(ansi_bytes: &[u8]) -> Result<Self, AnsiError> {
208 AnsiParser::parse(ansi_bytes)
209 }
210
211 /// Pushes another styled string at the end of this one.
212 ///
213 /// Use [`StyledStringBuilder`] for more complex string manipulations.
214 ///
215 /// # Examples
216 ///
217 /// ```
218 /// # use styled_str::{styled, StyledString};
219 /// let mut styled = styled!("[[bold green!]]Hello").to_owned();
220 /// styled.push_str(styled!("[[it]]!"));
221 /// // `push_str()` is also available via `+=` operator:
222 /// styled += styled!("[[it]]❤");
223 ///
224 /// assert_eq!(
225 /// styled,
226 /// styled!("[[bold green!]]Hello[[it]]!❤")
227 /// );
228 /// ```
229 pub fn push_str(&mut self, other: StyledStr<'_>) {
230 let mut copied_spans = other.spans.iter();
231 if let (Some(last), Some(next)) = (self.spans.last_mut(), other.spans.get(0)) {
232 if last.style == next.style {
233 last.extend_len(next.len.get());
234 copied_spans.next(); // skip copying the first span
235 }
236 }
237
238 // We need to offset the newly added spans, so that their start positions are correct.
239 let offset = self.text.len();
240 self.spans.extend(copied_spans.map(|mut span| {
241 span.start += offset;
242 span
243 }));
244
245 self.text.push_str(other.text);
246 }
247
248 /// Pops a single char from the end of the string.
249 ///
250 /// # Examples
251 ///
252 /// ```
253 /// # use styled_str::{styled, StyledString};
254 /// # use anstyle::Style;
255 /// let mut styled = styled!("[[bold green!]]Hello[[it]]!❤").to_owned();
256 /// let (ch, style) = styled.pop().unwrap();
257 /// assert_eq!(ch, '❤');
258 /// assert_eq!(style, Style::new().italic());
259 /// assert_eq!(styled, styled!("[[bold green!]]Hello[[it]]!"));
260 ///
261 /// styled.pop().unwrap();
262 /// assert_eq!(styled, styled!("[[bold green!]]Hello"));
263 /// ```
264 #[allow(clippy::missing_panics_doc)] // internal checks; should never be triggered
265 pub fn pop(&mut self) -> Option<(char, Style)> {
266 let ch = self.text.pop()?;
267 let char_len = ch.len_utf8();
268
269 let last_span = self.spans.last_mut().unwrap();
270 assert!(last_span.len.get() >= char_len, "style span divides char");
271
272 let style = last_span.style;
273 if let Some(new_len) = NonZeroUsize::new(last_span.len.get() - char_len) {
274 last_span.len = new_len;
275 } else {
276 self.spans.pop();
277 }
278 Some((ch, style))
279 }
280}
281
282impl ops::AddAssign<StyledStr<'_>> for StyledString {
283 fn add_assign(&mut self, rhs: StyledStr<'_>) {
284 self.push_str(rhs);
285 }
286}
287
288impl<T> fmt::Debug for StyledString<T>
289where
290 T: ops::Deref<Target = str>,
291{
292 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
293 fmt::Debug::fmt(&self.as_str(), formatter)
294 }
295}
296
297impl<T> fmt::Display for StyledString<T>
298where
299 T: ops::Deref<Target = str>,
300{
301 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
302 fmt::Display::fmt(&self.as_str(), formatter)
303 }
304}
305
306impl<'a> FromIterator<StyledStr<'a>> for StyledString {
307 fn from_iter<I: IntoIterator<Item = StyledStr<'a>>>(iter: I) -> Self {
308 iter.into_iter()
309 .fold(StyledString::default(), |mut acc, str| {
310 acc.push_str(str);
311 acc
312 })
313 }
314}
315
316impl<'a> Extend<StyledStr<'a>> for StyledString {
317 fn extend<I: IntoIterator<Item = StyledStr<'a>>>(&mut self, iter: I) {
318 for str in iter {
319 self.push_str(str);
320 }
321 }
322}