From 84c19ffdc6d12a9146761beb2de45617135dbb4d Mon Sep 17 00:00:00 2001 From: Kier Davis Date: Wed, 30 Aug 2023 14:07:30 +0100 Subject: [PATCH] add functions to allow constructing `Attributes` in a const context 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. --- src/style/attributes.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/style/attributes.rs b/src/style/attributes.rs index 7acd02e5f..f0113843d 100644 --- a/src/style/attributes.rs +++ b/src/style/attributes.rs @@ -62,6 +62,24 @@ 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. + 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. + 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)] @@ -117,4 +135,11 @@ mod tests { attributes.toggle(Attribute::Bold); assert!(attributes.is_empty()); } + + #[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)); + } }