use crate::lib_bitfield;
use crate::result::{Error, Result};
const OCR_MASK: u32 = 0xe9ff_8000;
lib_bitfield! {
pub Ocr(u32): bool {
pub vdd_2728: 15;
pub vdd_2829: 16;
pub vdd_2930: 17;
pub vdd_3031: 18;
pub vdd_3132: 19;
pub vdd_3233: 20;
pub vdd_3334: 21;
pub vdd_3435: 22;
pub vdd_3536: 23;
pub s18a: 24;
pub co2t: 27;
pub uhs2: 29;
pub ccs: 30;
pub busy: 31;
}
}
impl Ocr {
pub const LEN: usize = 4;
pub const fn new() -> Self {
Self(0)
}
pub const fn from_bits(val: u32) -> Self {
Self(val & OCR_MASK)
}
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(
u32::from_be_bytes([val[0], val[1], val[2], val[3]]) & OCR_MASK,
)),
}
}
pub const fn bytes(&self) -> [u8; Self::LEN] {
self.0.to_be_bytes()
}
}
impl From<u32> for Ocr {
fn from(val: u32) -> Self {
Self::from_bits(val)
}
}
impl From<Ocr> for u32 {
fn from(val: Ocr) -> Self {
val.bits()
}
}
impl TryFrom<&[u8]> for Ocr {
type Error = Error;
fn try_from(val: &[u8]) -> Result<Self> {
Self::try_from_bytes(val)
}
}
impl<const N: usize> TryFrom<&[u8; N]> for Ocr {
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 Ocr {
type Error = Error;
fn try_from(val: [u8; N]) -> Result<Self> {
Self::try_from_bytes(val.as_ref())
}
}
impl From<Ocr> for [u8; Ocr::LEN] {
fn from(val: Ocr) -> Self {
val.bytes()
}
}
impl Default for Ocr {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_field;
#[test]
fn test_fields() {
let mut ocr = Ocr::new();
test_field!(ocr, vdd_2728: 15);
test_field!(ocr, vdd_2829: 16);
test_field!(ocr, vdd_2930: 17);
test_field!(ocr, vdd_3031: 18);
test_field!(ocr, vdd_3132: 19);
test_field!(ocr, vdd_3233: 20);
test_field!(ocr, vdd_3334: 21);
test_field!(ocr, vdd_3435: 22);
test_field!(ocr, vdd_3536: 23);
test_field!(ocr, s18a: 24);
test_field!(ocr, co2t: 27);
test_field!(ocr, uhs2: 29);
test_field!(ocr, ccs: 30);
test_field!(ocr, busy: 31);
}
}