From c8b1b92e08b79a5133b0418facdbe9cacc98f935 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sat, 23 Jul 2022 12:10:13 -0700 Subject: [PATCH] Line::as_str() -> Cow Previously this would create a new String because it had to, but with the clustered storage we may be able to simply reference the existing string as a str reference, so allow for that. --- mux/src/pane.rs | 5 +++-- termwiz/src/surface/line.rs | 18 ++++++++++++------ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/mux/src/pane.rs b/mux/src/pane.rs index 904c2b359..11818e778 100644 --- a/mux/src/pane.rs +++ b/mux/src/pane.rs @@ -447,6 +447,7 @@ impl_downcast!(Pane); mod test { use super::*; use k9::snapshot; + use std::borrow::Cow; use termwiz::surface::SEQ_ZERO; struct FakePane { @@ -577,7 +578,7 @@ mod test { let width = 20; let physical_lines = physical_lines_from_text(text, width); - fn text_from_lines(lines: &[Line]) -> Vec { + fn text_from_lines(lines: &[Line]) -> Vec> { lines.iter().map(|l| l.as_str()).collect::>() } @@ -603,7 +604,7 @@ mod test { lines: physical_lines, }; - fn summarize_logical_lines(lines: &[LogicalLine]) -> Vec<(StableRowIndex, String)> { + fn summarize_logical_lines(lines: &[LogicalLine]) -> Vec<(StableRowIndex, Cow)> { lines .iter() .map(|l| (l.first_row, l.logical.as_str())) diff --git a/termwiz/src/surface/line.rs b/termwiz/src/surface/line.rs index 779efe5eb..265e5524f 100644 --- a/termwiz/src/surface/line.rs +++ b/termwiz/src/surface/line.rs @@ -7,6 +7,7 @@ use bitflags::bitflags; use fixedbitset::FixedBitSet; #[cfg(feature = "use_serde")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::borrow::Cow; use std::ops::Range; use std::sync::Arc; use unicode_segmentation::UnicodeSegmentation; @@ -497,7 +498,7 @@ impl Line { // use this as an opportunity to rebuild HAS_HYPERLINK, skip matching // cells with existing non-implicit hyperlinks, and avoid matching // text with zero-width cells. - let line = self.as_str(); + let line = self.as_str().into_owned(); self.bits |= LineBits::SCANNED_IMPLICIT_HYPERLINKS; self.bits &= !LineBits::HAS_IMPLICIT_HYPERLINKS; @@ -541,12 +542,17 @@ impl Line { } /// Recompose line into the corresponding utf8 string. - pub fn as_str(&self) -> String { - let mut s = String::new(); - for cell in self.visible_cells() { - s.push_str(cell.str()); + pub fn as_str(&self) -> Cow { + match &self.cells { + CellStorage::V(_) => { + let mut s = String::new(); + for cell in self.visible_cells() { + s.push_str(cell.str()); + } + Cow::Owned(s) + } + CellStorage::C(cl) => Cow::Borrowed(&cl.text), } - s } pub fn split_off(&mut self, idx: usize, seqno: SequenceNo) -> Self {