From: Simon Tatham Date: Thu, 11 Jan 2024 17:55:20 +0000 (+0000) Subject: Add a trait TextFragmentOneLine. X-Git-Url: http://www.chiark.greenend.org.uk/ucgi/~ian/git?a=commitdiff_plain;h=9b22210139d8fe96c71ce005eccfbe3c8b4e4267;p=mastodonochrome.git Add a trait TextFragmentOneLine. This is a slight refinement of ordinary TextFragment, to be implemented by types that render to exactly one line of text always, as opposed to being able to render to 0 or to more than one. The idea is that if a type implements this trait, then the compiler can _know_ there's one line of text coming out of its render method, instead of having to call .iter().exactly_one().unwrap() and think hard about whether I'm risking a runtime failure. I could implement this trait for a lot more things in text.rs, but for the moment, I'm only bothering to put it on the one that I need it for right now. --- diff --git a/src/text.rs b/src/text.rs index 6833f45..1599b5e 100644 --- a/src/text.rs +++ b/src/text.rs @@ -119,6 +119,12 @@ pub trait TextFragment { } } +pub trait TextFragmentOneLine { + // A more specific trait for fragments always producing exactly one line + fn render_oneline(&self, width: usize, _highlight: Option, + _style: &dyn DisplayStyleGetter) -> ColouredString; +} + impl TextFragment for Option { fn can_highlight(htype: HighlightType) -> bool where Self : Sized { T::can_highlight(htype) @@ -1735,10 +1741,9 @@ impl MenuKeypressLine { } } -impl TextFragment for MenuKeypressLine { - fn render_highlighted(&self, width: usize, _highlight: Option, - _style: &dyn DisplayStyleGetter) - -> Vec +impl TextFragmentOneLine for MenuKeypressLine { + fn render_oneline(&self, width: usize, _highlight: Option, + _style: &dyn DisplayStyleGetter) -> ColouredString { let ourwidth = self.lmaxwid + self.rmaxwid + 3; // " = " in the middle let space = width - min(width, ourwidth + 1); @@ -1758,8 +1763,17 @@ impl TextFragment for MenuKeypressLine { ColouredString::plain(" = ") + &self.keypress.description; + line.truncate(width).into() + } +} + +impl TextFragment for MenuKeypressLine { + fn render_highlighted(&self, width: usize, highlight: Option, + style: &dyn DisplayStyleGetter) + -> Vec + { vec! { - line.truncate(width).into() + self.render_oneline(width, highlight, style) } } }