Skip to main content

alux_cli_direct/
render.rs

1use std::{ffi::OsString, path::PathBuf};
2
3/// Renders a command's successful value as the text it writes to standard output.
4///
5/// A domain type renders itself by implementing this. A value that renders nothing writes nothing.
6pub trait DirectRender {
7    /// Appends this value's text to `out`, without a trailing newline.
8    fn render(&self, out: &mut String);
9}
10
11impl DirectRender for () {
12    fn render(&self, _: &mut String) {}
13}
14
15macro_rules! displayed {
16    ($($value:ty),* $(,)?) => {
17        $(impl DirectRender for $value {
18            fn render(&self, out: &mut String) {
19                out.push_str(&self.to_string());
20            }
21        })*
22    };
23}
24
25displayed!(String, &str, char, bool, f32, f64, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);
26
27impl DirectRender for PathBuf {
28    fn render(&self, out: &mut String) {
29        out.push_str(&self.display().to_string());
30    }
31}
32
33impl DirectRender for OsString {
34    fn render(&self, out: &mut String) {
35        out.push_str(&self.to_string_lossy());
36    }
37}
38
39/// Renders nothing when absent.
40impl<Value: DirectRender> DirectRender for Option<Value> {
41    fn render(&self, out: &mut String) {
42        if let Some(value) = self {
43            value.render(out);
44        }
45    }
46}
47
48/// Renders one value per line.
49impl<Value: DirectRender> DirectRender for Vec<Value> {
50    fn render(&self, out: &mut String) {
51        for (index, value) in self.iter().enumerate() {
52            if index > 0 {
53                out.push('\n');
54            }
55            value.render(out);
56        }
57    }
58}