1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
use std::ops::{BitAnd, BitOr, BitXor};
use crate::style::Attribute;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Attributes(u32);
impl From<Attribute> for Attributes {
fn from(attribute: Attribute) -> Self {
Self(attribute.bytes())
}
}
impl From<&[Attribute]> for Attributes {
fn from(arr: &[Attribute]) -> Self {
let mut attributes = Attributes::default();
for &attr in arr {
attributes.set(attr);
}
attributes
}
}
impl BitAnd<Attribute> for Attributes {
type Output = Self;
fn bitand(self, rhs: Attribute) -> Self {
Self(self.0 & rhs.bytes())
}
}
impl BitAnd for Attributes {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl BitOr<Attribute> for Attributes {
type Output = Self;
fn bitor(self, rhs: Attribute) -> Self {
Self(self.0 | rhs.bytes())
}
}
impl BitOr for Attributes {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl BitXor<Attribute> for Attributes {
type Output = Self;
fn bitxor(self, rhs: Attribute) -> Self {
Self(self.0 ^ rhs.bytes())
}
}
impl BitXor for Attributes {
type Output = Self;
fn bitxor(self, rhs: Self) -> Self {
Self(self.0 ^ rhs.0)
}
}
impl Attributes {
#[inline(always)]
pub fn set(&mut self, attribute: Attribute) {
self.0 |= attribute.bytes();
}
#[inline(always)]
pub fn unset(&mut self, attribute: Attribute) {
self.0 &= !attribute.bytes();
}
#[inline(always)]
pub fn toggle(&mut self, attribute: Attribute) {
self.0 ^= attribute.bytes();
}
#[inline(always)]
pub const fn has(self, attribute: Attribute) -> bool {
self.0 & attribute.bytes() != 0
}
#[inline(always)]
pub fn extend(&mut self, attributes: Attributes) {
self.0 |= attributes.0;
}
#[inline(always)]
pub const fn is_empty(self) -> bool {
self.0 == 0
}
}
#[cfg(test)]
mod tests {
use super::{Attribute, Attributes};
#[test]
fn test_attributes() {
let mut attributes: Attributes = Attribute::Bold.into();
assert!(attributes.has(Attribute::Bold));
attributes.set(Attribute::Italic);
assert!(attributes.has(Attribute::Italic));
attributes.unset(Attribute::Italic);
assert!(!attributes.has(Attribute::Italic));
attributes.toggle(Attribute::Bold);
assert!(attributes.is_empty());
}
}