use crate::lib_bitfield;
use crate::result::{Error, Result};
const CARD_STATUS_MASK: u16 = 0xe000;
lib_bitfield! {
pub CardStatus(u16): bool {
pub crc_error: 15;
pub illegal_command: 14;
pub error: 13;
}
}
impl CardStatus {
pub const LEN: usize = 2;
pub const fn new() -> Self {
Self(0)
}
pub const fn from_bits(val: u16) -> Self {
Self(val & CARD_STATUS_MASK)
}
pub const fn bytes(&self) -> [u8; Self::LEN] {
self.0.to_be_bytes()
}
pub const fn try_from_bytes(val: &[u8]) -> Result<Self> {
match val.len() {
len if len < Self::LEN => Err(Error::invalid_length(len, Self::LEN)),
_ => Ok(Self::from_bits(u16::from_be_bytes([val[0], val[1]]))),
}
}
}
impl Default for CardStatus {
fn default() -> Self {
Self::new()
}
}
impl From<u16> for CardStatus {
fn from(val: u16) -> Self {
Self::from_bits(val)
}
}
impl From<CardStatus> for u16 {
fn from(val: CardStatus) -> Self {
val.bits()
}
}
impl From<CardStatus> for [u8; CardStatus::LEN] {
fn from(val: CardStatus) -> Self {
val.bytes()
}
}
impl TryFrom<&[u8]> for CardStatus {
type Error = Error;
fn try_from(val: &[u8]) -> Result<Self> {
Self::try_from_bytes(val)
}
}
impl<const N: usize> TryFrom<&[u8; N]> for CardStatus {
type Error = Error;
fn try_from(val: &[u8; N]) -> Result<Self> {
Self::try_from_bytes(val.as_ref())
}
}
impl<const N: usize> TryFrom<[u8; N]> for CardStatus {
type Error = Error;
fn try_from(val: [u8; N]) -> Result<Self> {
Self::try_from_bytes(val.as_ref())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_field;
#[test]
fn test_fields() {
let mut cs = CardStatus::new();
test_field!(cs, crc_error: 15);
test_field!(cs, illegal_command: 14);
test_field!(cs, error: 13);
}
}