on master help sign in
Minimize allocation when converting table rows to string
b2837ffGokul Soumya
helix-term/src/ui/picker.rs+5−1
@@ -733,7 +733,11 @@ impl<T: Item + 'static> Component for Picker<T> {
733 .map(|mut row| {
733 .map(|mut row| {
734 const TEMP_CELL_SEP: &str = " ";
734 const TEMP_CELL_SEP: &str = " ";
735
735
736− let line = row.cell_text().join(TEMP_CELL_SEP);
736+ let line = row.cell_text().fold(String::new(), |mut s, frag| {
737+ s.push_str(&frag);
738+ s.push_str(TEMP_CELL_SEP);
739+ s
740+ });
737
741
738 // Items are filtered by using the text returned by menu::Item::filter_text
742 // Items are filtered by using the text returned by menu::Item::filter_text
739 // but we do highlighting here using the text in Row and therefore there
743 // but we do highlighting here using the text in Row and therefore there
helix-tui/src/text.rs+17−4
@@ -438,17 +438,30 @@ impl<'a> From<Vec<Spans<'a>>> for Text<'a> {
438
438
439impl<'a> From<Text<'a>> for String {
439impl<'a> From<Text<'a>> for String {
440 fn from(text: Text<'a>) -> String {
440 fn from(text: Text<'a>) -> String {
441− let lines: Vec<String> = text.lines.iter().map(String::from).collect();
441+ String::from(&text)
442− lines.join("\n")
443 }
442 }
444}
443}
445
444
446impl<'a> From<&Text<'a>> for String {
445impl<'a> From<&Text<'a>> for String {
447 fn from(text: &Text<'a>) -> String {
446 fn from(text: &Text<'a>) -> String {
448− let lines: Vec<String> = text.lines.iter().map(String::from).collect();
447+ let size = text
449− lines.join("\n")
448+ .lines
449+ .iter()
450+ .flat_map(|spans| spans.0.iter().map(|span| span.content.len()))
451+ .sum::<usize>()
452+ + text.lines.len().saturating_sub(1); // for newline after each line
453+ let mut output = String::with_capacity(size);
454+
455+ for spans in &text.lines {
456+ for span in &spans.0 {
457+ output.push_str(&span.content);
458+ }
459+ output.push('\n');
460+ }
461+ output
450 }
462 }
451}
463}
464+
452impl<'a> IntoIterator for Text<'a> {
465impl<'a> IntoIterator for Text<'a> {
453 type Item = Spans<'a>;
466 type Item = Spans<'a>;
454 type IntoIter = std::vec::IntoIter<Self::Item>;
467 type IntoIter = std::vec::IntoIter<Self::Item>;
helix-tui/src/widgets/table.rs+2−5
@@ -122,11 +122,8 @@ impl<'a> Row<'a> {
122 }
122 }
123
123
124 /// Returns the contents of cells as plain text, without styles and colors.
124 /// Returns the contents of cells as plain text, without styles and colors.
125− pub fn cell_text(&self) -> Vec<String> {
125+ pub fn cell_text(&self) -> impl Iterator<Item = String> + '_ {
126− self.cells
127− .iter()
128− .map(|cell| String::from(&cell.content))
126+ self.cells.iter().map(|cell| String::from(&cell.content))
129− .collect()
130 }
127 }
131}
128}
132
129