Crate bit_collection [−] [src]
#[bit]
Attribute
The #[bit]
attribute is composed of three parts, two of which are optional
in some cases. The components can be provided in any order.
Type:
The type used to represent individual bits. This part is required.
#[bit(Type, ...)]
Mask:
A mask indicating the valid bits of the collection. This should be a constant expression.
If not provided, the mask is assumed to have all bits set (i.e. !0
).
BitCollection::full()
returns this value.
#[bit(..., mask = "0b11", ...)]
Retriever:
The suffix for retrieving the inner integer value of the bit type. It
expands to $value.$retr
. Because of this, the provided retriever must be
visible where the derive is located.
If not provided, the bit type is assumed to be an enum
that can be
casted to an integer.
#[bit(..., retr = "inner", ...)]
Examples
In computer chess, one popular way of representing the occupants of a board
is through a Bitboard
type. In this type, each individual bit
is a square on a chess board.
#[macro_use] extern crate bit_collection; use bit_collection::BitCollection; #[derive(Copy, Clone)] pub struct Square(u8); /// A set of sixty-four `Square`s. #[bit(Square, mask = "!0", retr = "0")] #[derive(BitCollection)] pub struct Bitboard(u64);
We can also represent castle rights this way.
#[derive(Copy, Clone)] pub enum CastleRight { WhiteKingside, BlackKingside, WhiteQueenside, BlackQueenside, } /// A set of `CastleRight`s. #[bit(CastleRight, mask = "0b1111")] #[derive(BitCollection)] pub struct CastleRights { bits: u8 } fn iterate_over(rights: CastleRights) { for right in rights { match right { CastleRight::WhiteKingside => { /* ... */ }, CastleRight::BlackKingside => { /* ... */ }, CastleRight::WhiteQueenside => { /* ... */ }, CastleRight::BlackQueenside => { /* ... */ }, } } }
Traits
BitCollection |
A type that represents a collection of bits that can be iterated over. |