on master help sign in
Minimize allocation when converting table rows to string
commitb2837ff3bea286ce7ccfba9b6fbcd861977caf83 authorGokul Soumya <gokulps15@gmail.com> dateSat 24 Dec 2022, 16:51 (4 years ago) parent7a76c6c
3 files changed+24−10
helix-term/src/ui/picker.rs+5−1 helix-tui/src/text.rs+17−4 helix-tui/src/widgets/table.rs+2−5
helix-term/src/ui/picker.rs+5−1
@@ -733,7 +733,11 @@ impl<T: Item + 'static> Component for Picker<T> {
733733 .map(|mut row| {
734734 const TEMP_CELL_SEP: &str = " ";
735735
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+ });
737741
738742 // Items are filtered by using the text returned by menu::Item::filter_text
739743 // 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> {
438438
439439impl<'a> From<Text<'a>> for String {
440440 fn from(text: Text<'a>) -> String {
441− let lines: Vec<String> = text.lines.iter().map(String::from).collect();
442− lines.join("\n")
441+ String::from(&text)
443442 }
444443}
445444
446445impl<'a> From<&Text<'a>> for String {
447446 fn from(text: &Text<'a>) -> String {
448− let lines: Vec<String> = text.lines.iter().map(String::from).collect();
449− lines.join("\n")
447+ let size = text
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
450462 }
451463}
464+
452465impl<'a> IntoIterator for Text<'a> {
453466 type Item = Spans<'a>;
454467 type IntoIter = std::vec::IntoIter<Self::Item>;
helix-tui/src/widgets/table.rs+2−5
@@ -122,11 +122,8 @@ impl<'a> Row<'a> {
122122 }
123123
124124 /// Returns the contents of cells as plain text, without styles and colors.
125− pub fn cell_text(&self) -> Vec<String> {
126− self.cells
127− .iter()
128− .map(|cell| String::from(&cell.content))
129− .collect()
125+ pub fn cell_text(&self) -> impl Iterator<Item = String> + '_ {
126+ self.cells.iter().map(|cell| String::from(&cell.content))
130127 }
131128}
132129