use core::fmt;
use core::marker::PhantomData;
use crate::fields::{Field, FieldValue, TryFromValue};
use crate::{RegisterLongName, UIntLike};
#[derive(Copy, Clone)]
pub struct LocalRegisterCopy<T: UIntLike, R: RegisterLongName = ()> {
value: T,
associated_register: PhantomData<R>,
}
impl<T: UIntLike, R: RegisterLongName> LocalRegisterCopy<T, R> {
pub const fn new(value: T) -> Self {
LocalRegisterCopy {
value: value,
associated_register: PhantomData,
}
}
#[inline]
pub fn get(&self) -> T {
self.value
}
#[inline]
pub fn set(&mut self, value: T) {
self.value = value;
}
#[inline]
pub fn read(&self, field: Field<T, R>) -> T {
field.read(self.get())
}
#[inline]
pub fn read_as_enum<E: TryFromValue<T, EnumType = E>>(&self, field: Field<T, R>) -> Option<E> {
field.read_as_enum(self.get())
}
#[inline]
pub fn write(&mut self, field: FieldValue<T, R>) {
self.set(field.value);
}
#[inline]
pub fn modify(&mut self, field: FieldValue<T, R>) {
self.set(field.modify(self.get()));
}
#[inline]
pub fn is_set(&self, field: Field<T, R>) -> bool {
field.is_set(self.get())
}
#[inline]
pub fn matches_any(&self, field: FieldValue<T, R>) -> bool {
field.matches_any(self.get())
}
#[inline]
pub fn matches_all(&self, field: FieldValue<T, R>) -> bool {
field.matches_all(self.get())
}
#[inline]
pub fn bitand(&self, rhs: T) -> LocalRegisterCopy<T, R> {
LocalRegisterCopy::new(self.value & rhs)
}
}
impl<T: UIntLike + fmt::Debug, R: RegisterLongName> fmt::Debug for LocalRegisterCopy<T, R> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.value)
}
}
macro_rules! From_impl_for {
($type:ty) => {
impl<R: RegisterLongName> From<LocalRegisterCopy<$type, R>> for $type {
fn from(r: LocalRegisterCopy<$type, R>) -> $type {
r.value
}
}
};
}
From_impl_for!(u8);
From_impl_for!(u16);
From_impl_for!(u32);
From_impl_for!(u64);
From_impl_for!(u128);
From_impl_for!(usize);