use crate::lib_bitfield;
use crate::result::{Error, Result};
const IO_OCR_LEN: usize = 3;
lib_bitfield! {
pub IoOcr(MSB0 [u8; IO_OCR_LEN]): bool {
pub vdd_3536: 23;
pub vdd_3435: 22;
pub vdd_3334: 21;
pub vdd_3233: 20;
pub vdd_3132: 19;
pub vdd_3031: 18;
pub vdd_2930: 17;
pub vdd_2829: 16;
pub vdd_2728: 15;
pub vdd_2627: 14;
pub vdd_2526: 13;
pub vdd_2425: 12;
pub vdd_2324: 11;
pub vdd_2223: 10;
pub vdd_2122: 9;
pub vdd_2021: 8;
}
}
impl IoOcr {
pub const LEN: usize = IO_OCR_LEN;
pub const fn new() -> Self {
Self([0; Self::LEN])
}
pub const fn bits(&self) -> u32 {
u32::from_be_bytes([0, self.0[0], self.0[1], self.0[2]])
}
pub const fn from_bits(val: u32) -> Self {
let [_, io0, io1, io2] = val.to_be_bytes();
Self([io0, io1, io2])
}
pub const fn into_bytes(self) -> [u8; Self::LEN] {
self.0
}
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([val[0], val[1], val[2]])),
}
}
}
impl Default for IoOcr {
fn default() -> Self {
Self::new()
}
}
impl From<u32> for IoOcr {
fn from(val: u32) -> Self {
Self::from_bits(val)
}
}
impl From<IoOcr> for u32 {
fn from(val: IoOcr) -> Self {
val.bits()
}
}
impl TryFrom<&[u8]> for IoOcr {
type Error = Error;
fn try_from(val: &[u8]) -> Result<Self> {
Self::try_from_bytes(val)
}
}
impl<const N: usize> TryFrom<&[u8; N]> for IoOcr {
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 IoOcr {
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 ocr = IoOcr::new();
test_field!(ocr, vdd_2021: 8);
test_field!(ocr, vdd_2122: 9);
test_field!(ocr, vdd_2223: 10);
test_field!(ocr, vdd_2324: 11);
test_field!(ocr, vdd_2425: 12);
test_field!(ocr, vdd_2526: 13);
test_field!(ocr, vdd_2627: 14);
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);
}
}