Skip to content

Commit

Permalink
Merge pull request #122 from Property404/Property404/const-methods
Browse files Browse the repository at this point in the history
Make Style methods const
  • Loading branch information
jam1garner authored May 2, 2024
2 parents 74a37f1 + 39f0736 commit 57c3468
Showing 1 changed file with 28 additions and 7 deletions.
35 changes: 28 additions & 7 deletions src/dyn_styles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -78,7 +78,7 @@ pub struct Styled<T> {
///
/// 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<DynColors>,
pub(crate) bg: Option<DynColors>,
Expand All @@ -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;
Expand All @@ -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),
Expand All @@ -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
Expand Down Expand Up @@ -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()
}

Expand Down

0 comments on commit 57c3468

Please sign in to comment.