pub struct BitField<M, T> {
pub value: T,
/* private fields */
}
Expand description
Accessory struct for convinient type construction
This structure holds value of created bitfield type and may be used for types that doesn’t has own value field: enums and unit-like structs.
§Enum wrapper
Using enumeration as bitfield type has the following advantage - you can bind bit (flag) to one of enum variants.
// Declare new bitfield type
enum EightFlags {
One,
Two,
Three,
Four,
OemReserved(u8), // Reserved field referenced to multiple bits
FutureReserved(u8), // Reserved field referenced to multiple bits
}
// Implement Dispaly trait for basic and alternative views
impl fmt::Display for EightFlags {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (self, f.alternate()) {
// Basic view
(Self::One, false) => write!(f, "one"),
(Self::Two, false) => write!(f, "two"),
(Self::Three, false) => write!(f, "three"),
(Self::Four, false) => write!(f, "four"),
// Alternative view
(Self::One, true) => write!(f, "ONE"),
(Self::Two, true) => write!(f, "TWO"),
(Self::Three, true) => write!(f, "THREE"),
(Self::Four, true) => write!(f, "FOUR"),
// Reserved fields
(Self::OemReserved(v), _) => write!(f, "OEM reserved (#{})", v),
(Self::FutureReserved(v), _) => write!(f, "Reserved for future usage (#{})", v),
}
}
}
// Implement constant bit layout for this type
impl EightFlags {
const LAYOUT: [Self; 8] = [
Self::One,
Self::Two,
Self::Three,
Self::Four,
Self::OemReserved(4),
Self::OemReserved(5),
Self::FutureReserved(6),
Self::FutureReserved(7),
];
}
// Implement Layout for enum created early
impl Layout for EightFlags {
type Layout = std::slice::Iter<'static, EightFlags>;
fn layout() -> Self::Layout { EightFlags::LAYOUT.iter() }
}
// Now we can use wrapped bitfield enum
let bf: BitField<EightFlags, u8> = BitField::new(0b01100101);
// Get only setted flags
let result = bf.flags()
.filter_map(|f| {
if f.is_set {
match f.value {
EightFlags::OemReserved(v) =>
Some(format!("Reserved flag #{}", v)),
EightFlags::FutureReserved(_) =>
Some(format!("{}", f.value)),
v @ _ =>
Some(format!("Name: {}, Description: {:#}", v, v)),
}
} else {
None
}
})
.collect::<Vec<_>>();
let sample = vec![
"Name: one, Description: ONE",
"Name: three, Description: THREE",
"Reserved flag #5",
"Reserved for future usage (#6)",
];
assert_eq!(sample, result, "Wrapped enum");
§Unit-like struct wrapper
We can use bitfield type defined as unit-like struct in the same way as for enum
// Unit-like struct without value
struct Status;
// Bind flags layout to this struct
impl Status {
const LAYOUT: [&'static str; 8] = [
"s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
];
}
// Implement layout trait
impl Layout for Status {
type Layout = core::slice::Iter<'static, &'static str>;
fn layout() -> Self::Layout { Status::LAYOUT.iter() }
}
let bf: BitField<Status, u8> = BitField::new(42);
// Get formatted strings from flags iteartor
let result = bf.flags()
.map(|f| format!("{:#}", f.value))
.collect::<Vec<_>>();
let sample = vec!["s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7"];
assert_eq!(sample, result, "Simple unit-like struct");
§Unit-like struct with associated constants
Also we can use unit-like struct with associated constant flags. This will gave us feauture to has marked bits. This realisation somewhere in beetween enum and simple unit-like struct.
// Unit-like struct without value
struct Status;
// Implement layout. You can leave comments on every item. For example, you can use bit id as
// Status::ONE.
impl Status {
const ONE: &'static str = "One";
const TWO: &'static str = "Two";
const THREE: &'static str = "Three";
const FOUR: &'static str = "Four";
const RESERVED: &'static str = "Reserved";
const UNKNOWN: &'static str = "Unknown";
const LAYOUT: [&'static str; 8] = [
Self::ONE,
Self::TWO,
Self::THREE,
Self::FOUR,
Self::RESERVED,
Self::RESERVED,
Self::RESERVED,
Self::UNKNOWN,
];
}
// Implement layout trait
impl Layout for Status {
type Layout = core::slice::Iter<'static, &'static str>;
fn layout() -> Self::Layout { Status::LAYOUT.iter() }
}
let bf: BitField<Status, u8> = BitField::new(0b00001000);
let result = bf.flags()
.find(|f| f.is_set)
.map(|f| f.value)
.unwrap();
assert_eq!(Status::FOUR, *result, "Enumeration");
Fields§
§value: T
Implementations§
Trait Implementations§
Source§impl<M, T> BitAndAssign for BitField<M, T>
impl<M, T> BitAndAssign for BitField<M, T>
Source§fn bitand_assign(&mut self, rhs: Self)
fn bitand_assign(&mut self, rhs: Self)
Performs the
&=
operation. Read moreSource§impl<M: Layout, T: Copy + IntoBits + FromBits> BitFieldLayout for BitField<M, T>
impl<M: Layout, T: Copy + IntoBits + FromBits> BitFieldLayout for BitField<M, T>
type Value = T
Source§fn replace(&mut self, new: Self::Value) -> Self::Value
fn replace(&mut self, new: Self::Value) -> Self::Value
Replaces the contained value with val, and returns the old contained value. Read more
Source§fn update<F>(&mut self, f: F) -> Self::Value
fn update<F>(&mut self, f: F) -> Self::Value
Updates the contained value using a function and returns the new value. Read more
Source§fn insert_flag(&mut self, position: usize, b: bool) -> bool
fn insert_flag(&mut self, position: usize, b: bool) -> bool
Set the specified bit (flag) in-place. Returns current state Read more
Source§fn toggle_flag(&mut self, position: usize)
fn toggle_flag(&mut self, position: usize)
The specified bit (flag) will be inverted Read more
Source§fn bits(&self) -> Bits<<Self::Value as IntoBits>::Bytes> ⓘ
fn bits(&self) -> Bits<<Self::Value as IntoBits>::Bytes> ⓘ
Return iterator through bitfield value bits. Every bit represents as bool value. Read more
Source§fn flags(&self) -> Flags<Self::Layout, Bits<<Self::Value as IntoBits>::Bytes>> ⓘ
fn flags(&self) -> Flags<Self::Layout, Bits<<Self::Value as IntoBits>::Bytes>> ⓘ
Return iterator through bitfield value flags. Every flag contains bit state (set or unset)
and item (record) value - string in simple case. Read more
Source§impl<M, T> BitOrAssign for BitField<M, T>
impl<M, T> BitOrAssign for BitField<M, T>
Source§fn bitor_assign(&mut self, rhs: Self)
fn bitor_assign(&mut self, rhs: Self)
Performs the
|=
operation. Read moreSource§impl<M, T> BitXorAssign for BitField<M, T>
impl<M, T> BitXorAssign for BitField<M, T>
Source§fn bitxor_assign(&mut self, rhs: Self)
fn bitxor_assign(&mut self, rhs: Self)
Performs the
^=
operation. Read moreSource§impl<M: Ord, T: Ord> Ord for BitField<M, T>
impl<M: Ord, T: Ord> Ord for BitField<M, T>
1.21.0 · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
Compares and returns the maximum of two values. Read more
Source§impl<M: PartialOrd, T: PartialOrd> PartialOrd for BitField<M, T>
impl<M: PartialOrd, T: PartialOrd> PartialOrd for BitField<M, T>
impl<M: Eq, T: Eq> Eq for BitField<M, T>
impl<M, T> StructuralPartialEq for BitField<M, T>
Auto Trait Implementations§
impl<M, T> Freeze for BitField<M, T>where
T: Freeze,
impl<M, T> RefUnwindSafe for BitField<M, T>where
T: RefUnwindSafe,
M: RefUnwindSafe,
impl<M, T> Send for BitField<M, T>
impl<M, T> Sync for BitField<M, T>
impl<M, T> Unpin for BitField<M, T>
impl<M, T> UnwindSafe for BitField<M, T>where
T: UnwindSafe,
M: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
Converts
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
Converts
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more