Minimize allocation when converting table rows to string

This commit is contained in:
Gokul Soumya 2022-12-24 16:51:38 +05:30 committed by Blaž Hrastnik
parent 7a76c6cbba
commit b2837ff3be
3 changed files with 24 additions and 10 deletions

View file

@ -733,7 +733,11 @@ fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
.map(|mut row| { .map(|mut row| {
const TEMP_CELL_SEP: &str = " "; const TEMP_CELL_SEP: &str = " ";
let line = row.cell_text().join(TEMP_CELL_SEP); let line = row.cell_text().fold(String::new(), |mut s, frag| {
s.push_str(&frag);
s.push_str(TEMP_CELL_SEP);
s
});
// Items are filtered by using the text returned by menu::Item::filter_text // Items are filtered by using the text returned by menu::Item::filter_text
// but we do highlighting here using the text in Row and therefore there // but we do highlighting here using the text in Row and therefore there

View file

@ -438,17 +438,30 @@ fn from(lines: Vec<Spans<'a>>) -> Text<'a> {
impl<'a> From<Text<'a>> for String { impl<'a> From<Text<'a>> for String {
fn from(text: Text<'a>) -> String { fn from(text: Text<'a>) -> String {
let lines: Vec<String> = text.lines.iter().map(String::from).collect(); String::from(&text)
lines.join("\n")
} }
} }
impl<'a> From<&Text<'a>> for String { impl<'a> From<&Text<'a>> for String {
fn from(text: &Text<'a>) -> String { fn from(text: &Text<'a>) -> String {
let lines: Vec<String> = text.lines.iter().map(String::from).collect(); let size = text
lines.join("\n") .lines
.iter()
.flat_map(|spans| spans.0.iter().map(|span| span.content.len()))
.sum::<usize>()
+ text.lines.len().saturating_sub(1); // for newline after each line
let mut output = String::with_capacity(size);
for spans in &text.lines {
for span in &spans.0 {
output.push_str(&span.content);
}
output.push('\n');
}
output
} }
} }
impl<'a> IntoIterator for Text<'a> { impl<'a> IntoIterator for Text<'a> {
type Item = Spans<'a>; type Item = Spans<'a>;
type IntoIter = std::vec::IntoIter<Self::Item>; type IntoIter = std::vec::IntoIter<Self::Item>;

View file

@ -122,11 +122,8 @@ fn total_height(&self) -> u16 {
} }
/// Returns the contents of cells as plain text, without styles and colors. /// Returns the contents of cells as plain text, without styles and colors.
pub fn cell_text(&self) -> Vec<String> { pub fn cell_text(&self) -> impl Iterator<Item = String> + '_ {
self.cells self.cells.iter().map(|cell| String::from(&cell.content))
.iter()
.map(|cell| String::from(&cell.content))
.collect()
} }
} }