From 39f073611246c955096e4561b107fcdaa78858d1 Mon Sep 17 00:00:00 2001 From: Property404 Date: Tue, 6 Feb 2024 11:55:11 -0600 Subject: [PATCH] Make Style methods const Now we can do things like: ``` const ERROR_STYLE: Style = Style::new().red(); ``` --- src/dyn_styles.rs | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/src/dyn_styles.rs b/src/dyn_styles.rs index a65fc28..5a5ad12 100644 --- a/src/dyn_styles.rs +++ b/src/dyn_styles.rs @@ -26,14 +26,14 @@ macro_rules! color_methods { $( #[$fg_meta] #[must_use] - pub fn $fg_method(mut self) -> Self { + pub const fn $fg_method(mut self) -> Self { self.fg = Some(DynColors::Ansi(AnsiColors::$color)); self } #[$fg_meta] #[must_use] - pub fn $bg_method(mut self) -> Self { + pub const fn $bg_method(mut self) -> Self { self.bg = Some(DynColors::Ansi(AnsiColors::$color)); self } @@ -78,7 +78,7 @@ pub struct Styled { /// /// println!("{}", "red text, white background, struck through".style(my_style)); /// ``` -#[derive(Debug, Default, Copy, Clone, PartialEq)] +#[derive(Debug, Copy, Clone, PartialEq)] pub struct Style { pub(crate) fg: Option, pub(crate) bg: Option, @@ -87,7 +87,7 @@ pub struct Style { } #[repr(transparent)] -#[derive(Debug, Default, Copy, Clone, PartialEq)] +#[derive(Debug, Copy, Clone, PartialEq)] pub(crate) struct StyleFlags(pub(crate) u8); const DIMMED_SHIFT: u8 = 0; @@ -114,6 +114,10 @@ macro_rules! style_flags_methods { } impl StyleFlags { + const fn new() -> Self { + Self(0) + } + style_flags_methods! { (DIMMED_SHIFT, dimmed, set_dimmed), (ITALIC_SHIFT, italic, set_italic), @@ -126,11 +130,22 @@ impl StyleFlags { } } +impl Default for StyleFlags { + fn default() -> Self { + Self::new() + } +} + impl Style { /// Create a new style to be applied later #[must_use] - pub fn new() -> Self { - Self::default() + pub const fn new() -> Self { + Self { + fg: None, + bg: None, + bold: false, + style_flags: StyleFlags::new(), + } } /// Apply the style to a given struct to output @@ -486,8 +501,14 @@ impl Style { } } +impl Default for Style { + fn default() -> Self { + Self::new() + } +} + /// Helper to create [`Style`]s more ergonomically -pub fn style() -> Style { +pub const fn style() -> Style { Style::new() }