chiark / gitweb /
Add a trait TextFragmentOneLine.
authorSimon Tatham <anakin@pobox.com>
Thu, 11 Jan 2024 17:55:20 +0000 (17:55 +0000)
committerSimon Tatham <anakin@pobox.com>
Fri, 12 Jan 2024 12:52:04 +0000 (12:52 +0000)
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.

src/text.rs

index 6833f452694e12d74d35d4569c38f1bf44a0e1a6..1599b5e0a496bb411e0d3db62c14499589e4f2cd 100644 (file)
@@ -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<Highlight>,
+                      _style: &dyn DisplayStyleGetter) -> ColouredString;
+}
+
 impl<T: TextFragment> TextFragment for Option<T> {
     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<Highlight>,
-                          _style: &dyn DisplayStyleGetter)
-                          -> Vec<ColouredString>
+impl TextFragmentOneLine for MenuKeypressLine {
+    fn render_oneline(&self, width: usize, _highlight: Option<Highlight>,
+                      _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<Highlight>,
+                          style: &dyn DisplayStyleGetter)
+                          -> Vec<ColouredString>
+    {
         vec! {
-            line.truncate(width).into()
+            self.render_oneline(width, highlight, style)
         }
     }
 }