ascii_forge/renderer/
cell.rs

1use std::fmt::Display;
2
3use crate::prelude::*;
4use compact_str::{CompactString, ToCompactString};
5
6/// A cell that stores a symbol, and the style that will be applied to it.
7#[derive(Debug, Clone, Eq, PartialEq)]
8pub struct Cell {
9    text: CompactString,
10    style: ContentStyle,
11}
12
13impl Default for Cell {
14    fn default() -> Self {
15        Self::chr(' ')
16    }
17}
18
19impl Cell {
20    pub fn new<S: Into<ContentStyle>>(text: impl Into<CompactString>, style: S) -> Self {
21        Self {
22            text: text.into(),
23            style: style.into(),
24        }
25    }
26
27    pub fn string(string: impl AsRef<str>) -> Self {
28        Self {
29            text: CompactString::new(string),
30            style: ContentStyle::default(),
31        }
32    }
33
34    pub fn chr(chr: char) -> Self {
35        Self {
36            text: chr.to_compact_string(),
37            style: ContentStyle::default(),
38        }
39    }
40
41    pub fn styled<D: Display>(content: StyledContent<D>) -> Self {
42        Self {
43            text: CompactString::new(format!("{}", content.content())),
44            style: *content.style(),
45        }
46    }
47
48    pub fn is_empty(&self) -> bool {
49        self.text.trim().is_empty()
50    }
51
52    pub fn text(&self) -> &str {
53        &self.text
54    }
55
56    pub fn text_mut(&mut self) -> &mut CompactString {
57        &mut self.text
58    }
59
60    pub fn style(&self) -> &ContentStyle {
61        &self.style
62    }
63
64    pub fn style_mut(&mut self) -> &mut ContentStyle {
65        &mut self.style
66    }
67}
68
69impl Render for Cell {
70    fn render(&self, loc: crate::prelude::Vec2, buffer: &mut crate::prelude::Buffer) -> Vec2 {
71        buffer.set(loc, self.clone());
72        loc
73    }
74}
75
76macro_rules! str_impl {
77    ($($ty:ty)*) => {
78        $(
79            impl From<$ty> for Cell {
80                fn from(value: $ty) -> Self {
81                    Self::string(value)
82                }
83            }
84        )*
85    };
86}
87
88str_impl! {&str String}
89
90impl From<char> for Cell {
91    fn from(value: char) -> Self {
92        Self::chr(value)
93    }
94}
95
96impl<D: Display> From<StyledContent<D>> for Cell {
97    fn from(value: StyledContent<D>) -> Self {
98        Self::styled(value)
99    }
100}
101
102impl Display for Cell {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        write!(f, "{}", StyledContent::new(self.style, &self.text))
105    }
106}