Skip to content

Commit

Permalink
Add functions to allow constructing Attributes in a const context (#…
Browse files Browse the repository at this point in the history
…817)

Previously, the only ways to construct new `Attributes` values were
`Attributes::default()` or `Attributes::from(_)`, neither of can be
made `const fn` due to limitations of these standard library traits.
  • Loading branch information
kierdavis committed Jan 6, 2024
1 parent 94fdd58 commit 0935196
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/style/attributes.rs
Expand Up @@ -62,6 +62,26 @@ impl BitXor for Attributes {
}

impl Attributes {
/// Returns the empty bitset.
#[inline(always)]
pub const fn none() -> Self {
Self(0)
}

/// Returns a copy of the bitset with the given attribute set.
/// If it's already set, this returns the bitset unmodified.
#[inline(always)]
pub const fn with(self, attribute: Attribute) -> Self {
Self(self.0 | attribute.bytes())
}

/// Returns a copy of the bitset with the given attribute unset.
/// If it's not set, this returns the bitset unmodified.
#[inline(always)]
pub const fn without(self, attribute: Attribute) -> Self {
Self(self.0 & !attribute.bytes())
}

/// Sets the attribute.
/// If it's already set, this does nothing.
#[inline(always)]
Expand Down Expand Up @@ -117,4 +137,11 @@ mod tests {
attributes.toggle(Attribute::Bold);
assert!(attributes.is_empty());
}

Check failure on line 140 in src/style/attributes.rs

View workflow job for this annotation

GitHub Actions / stable on ubuntu-latest

Diff in /home/runner/work/crossterm/crossterm/src/style/attributes.rs
#[test]
fn test_attributes_const() {
const ATTRIBUTES: Attributes = Attributes::none().with(Attribute::Bold).with(Attribute::Italic).without(Attribute::Bold);
assert!(!ATTRIBUTES.has(Attribute::Bold));
assert!(ATTRIBUTES.has(Attribute::Italic));
}
}

0 comments on commit 0935196

Please sign in to comment.