Make Text accept both borrowed and owned strings

pull/74/head
Antoine Büsch 6 years ago committed by Florian Dehau
parent 6c69160d6b
commit 559c9c75f3

@ -55,15 +55,15 @@ fn draw(t: &mut Terminal<MouseBackend>, size: Rect) -> Result<(), io::Error> {
.split(size);
let text = [
Text::Data("This a line\n"),
Text::StyledData("This a line\n", Style::default().fg(Color::Red)),
Text::StyledData("This a line\n", Style::default().bg(Color::Blue)),
Text::Data("This a line\n".into()),
Text::StyledData("This a line\n".into(), Style::default().fg(Color::Red)),
Text::StyledData("This a line\n".into(), Style::default().bg(Color::Blue)),
Text::StyledData(
"This a longer line\n",
"This a longer line\n".into(),
Style::default().modifier(Modifier::CrossedOut),
),
Text::StyledData(
"This a line\n",
"This a line\n".into(),
Style::default().fg(Color::Green).modifier(Modifier::Italic),
),
];

@ -1,3 +1,5 @@
use std::borrow::Cow;
use either::Either;
use itertools::{multipeek, MultiPeek};
use unicode_segmentation::UnicodeSegmentation;
@ -50,8 +52,8 @@ where
}
pub enum Text<'b> {
Data(&'b str),
StyledData(&'b str, Style),
Data(Cow<'b, str>),
StyledData(Cow<'b, str>, Style),
}
impl<'a, 't, T> Paragraph<'a, 't, T>
@ -122,11 +124,13 @@ where
let style = self.style;
let styled = self.text.by_ref().flat_map(|t| match *t {
Text::Data(d) => {
Either::Left(UnicodeSegmentation::graphemes(d, true).map(|g| (g, style)))
Text::Data(ref d) => {
let data: &'t str = d; // coerce to &str
Either::Left(UnicodeSegmentation::graphemes(data, true).map(|g| (g, style)))
}
Text::StyledData(d, s) => {
Either::Right(UnicodeSegmentation::graphemes(d, true).map(move |g| (g, s)))
Text::StyledData(ref d, s) => {
let data: &'t str = d; // coerce to &str
Either::Right(UnicodeSegmentation::graphemes(data, true).map(move |g| (g, s)))
}
});
let mut styled = multipeek(styled);

Loading…
Cancel
Save