Struct bitfield_layout::BitField[][src]

pub struct BitField<M, T> {
    pub value: T,
    // some fields omitted
}
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

impl<M, T> BitField<M, T>[src]

pub fn new(value: T) -> Self[src]

Trait Implementations

impl<M: Layout, T: Copy + IntoBits> BitFieldLayout for BitField<M, T>[src]

type Value = T

fn get(&self) -> Self::Value[src]

Returns a copy of the contained value.

fn set(&mut self, new: Self::Value)[src]

Sets the contained value.

fn replace(&mut self, new: Self::Value) -> Self::Value[src]

Replaces the contained value with val, and returns the old contained value.

fn swap(&mut self, other: &mut Self)[src]

Swaps the values of two bitfields.

fn update<F>(&mut self, f: F) -> Self::Value where
    F: FnOnce(Self::Value) -> Self::Value
[src]

Updates the contained value using a function and returns the new value.

fn bits(&self) -> Bits<<Self::Value as IntoBits>::Bytes>

Notable traits for Bits<I>

impl<I: Iterator<Item = u8>> Iterator for Bits<I> type Item = bool;
[src]

Return iterator through bitfield value bits. Every bit represents as bool value.

fn flags(&self) -> Flags<Self::Layout, Bits<<Self::Value as IntoBits>::Bytes>>

Notable traits for Flags<L, B>

impl<L, B> Iterator for Flags<L, B> where
    L: Iterator,
    B: Iterator<Item = bool>, 
type Item = Flag<L::Item>;
[src]

Return iterator through bitfield value flags. Every flag contains bit state (set or unset) and item (record) value - string in simple case. Read more

fn diff(
    &self,
    other: Self
) -> Diff<Self::Layout, Bits<<Self::Value as IntoBits>::Bytes>>

Notable traits for Diff<L, B>

impl<L, T, B> Iterator for Diff<L, B> where
    L: Iterator<Item = T>,
    B: Iterator<Item = bool>, 
type Item = Either<(usize, T), (usize, T)>;
where
    Self: Sized
[src]

Helps to find difference between two bitfield values.

impl<M: Clone, T: Clone> Clone for BitField<M, T>[src]

fn clone(&self) -> BitField<M, T>[src]

Returns a copy of the value. Read more

fn clone_from(&mut self, source: &Self)1.0.0[src]

Performs copy-assignment from source. Read more

impl<M: Debug, T: Debug> Debug for BitField<M, T>[src]

fn fmt(&self, f: &mut Formatter<'_>) -> Result[src]

Formats the value using the given formatter. Read more

impl<M: Hash, T: Hash> Hash for BitField<M, T>[src]

fn hash<__H: Hasher>(&self, state: &mut __H)[src]

Feeds this value into the given Hasher. Read more

fn hash_slice<H>(data: &[Self], state: &mut H) where
    H: Hasher
1.3.0[src]

Feeds a slice of this type into the given Hasher. Read more

impl<M: Layout, T> Layout for BitField<M, T>[src]

type Layout = M::Layout

Layout iterator. Typically constant array or slice

fn layout() -> Self::Layout[src]

Return iterator through layout items. Actual layout may be implemented inside this function or be a associated constant of bitfield type Read more

impl<M: Ord, T: Ord> Ord for BitField<M, T>[src]

fn cmp(&self, other: &BitField<M, T>) -> Ordering[src]

This method returns an Ordering between self and other. Read more

#[must_use]
fn max(self, other: Self) -> Self
1.21.0[src]

Compares and returns the maximum of two values. Read more

#[must_use]
fn min(self, other: Self) -> Self
1.21.0[src]

Compares and returns the minimum of two values. Read more

#[must_use]
fn clamp(self, min: Self, max: Self) -> Self
1.50.0[src]

Restrict a value to a certain interval. Read more

impl<M: PartialEq, T: PartialEq> PartialEq<BitField<M, T>> for BitField<M, T>[src]

fn eq(&self, other: &BitField<M, T>) -> bool[src]

This method tests for self and other values to be equal, and is used by ==. Read more

fn ne(&self, other: &BitField<M, T>) -> bool[src]

This method tests for !=.

impl<M: PartialOrd, T: PartialOrd> PartialOrd<BitField<M, T>> for BitField<M, T>[src]

fn partial_cmp(&self, other: &BitField<M, T>) -> Option<Ordering>[src]

This method returns an ordering between self and other values if one exists. Read more

#[must_use]
fn lt(&self, other: &Rhs) -> bool
1.0.0[src]

This method tests less than (for self and other) and is used by the < operator. Read more

#[must_use]
fn le(&self, other: &Rhs) -> bool
1.0.0[src]

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

#[must_use]
fn gt(&self, other: &Rhs) -> bool
1.0.0[src]

This method tests greater than (for self and other) and is used by the > operator. Read more

#[must_use]
fn ge(&self, other: &Rhs) -> bool
1.0.0[src]

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

impl<M: Eq, T: Eq> Eq for BitField<M, T>[src]

impl<M, T> StructuralEq for BitField<M, T>[src]

impl<M, T> StructuralPartialEq for BitField<M, T>[src]

Auto Trait Implementations

impl<M, T> RefUnwindSafe for BitField<M, T> where
    M: RefUnwindSafe,
    T: RefUnwindSafe

impl<M, T> Send for BitField<M, T> where
    M: Send,
    T: Send

impl<M, T> Sync for BitField<M, T> where
    M: Sync,
    T: Sync

impl<M, T> Unpin for BitField<M, T> where
    M: Unpin,
    T: Unpin

impl<M, T> UnwindSafe for BitField<M, T> where
    M: UnwindSafe,
    T: UnwindSafe

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

pub fn type_id(&self) -> TypeId[src]

Gets the TypeId of self. Read more

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

pub fn borrow(&self) -> &T[src]

Immutably borrows from an owned value. Read more

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

pub fn borrow_mut(&mut self) -> &mut T[src]

Mutably borrows from an owned value. Read more

impl<T> From<T> for T[src]

pub fn from(t: T) -> T[src]

Performs the conversion.

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

pub fn into(self) -> U[src]

Performs the conversion.

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

pub fn to_owned(&self) -> T[src]

Creates owned data from borrowed data, usually by cloning. Read more

pub fn clone_into(&self, target: &mut T)[src]

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>[src]

Performs the conversion.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>[src]

Performs the conversion.