1#![doc = include_str!("../README.md")]
2#![no_std]
3#![deny(unsafe_code, missing_docs)]
4#![allow(async_fn_in_trait)]
56pub use device_register;
7use device_register::{EditableRegister, ReadableRegister, Register, WritableRegister};
89/// Traits that define how to read and write the registers.
10/// Note that those functions should mostly just be implemented and not used since they are not bound by Read/Write/Edit permission.
11pub trait RegisterInterface<R, A>
12where
13R: Register<Address = A>,
14{
15/// The error type returned by the interface
16type Error;
1718/// Reads a register and returns it
19async fn read_register(&mut self) -> Result<R, Self::Error>;
2021/// Writes a register to the device
22async fn write_register(&mut self, register: &R) -> Result<(), Self::Error>;
23}
2425/// Trait to safely read a register. Only a readable register can be read.
26pub trait ReadRegister<R, A>
27where
28R: ReadableRegister<Address = A>,
29{
30/// The error type returned by reading a register
31type Error;
3233/// Read a register
34async fn read(&mut self) -> Result<R, Self::Error>;
35}
3637/// Trait to safely write a register. Only a writable register can be written to.
38pub trait WriteRegister<R, A>
39where
40R: WritableRegister<Address = A>,
41{
42/// The error type returned by writing a register
43type Error;
4445/// Write a register
46async fn write(&mut self, register: R) -> Result<(), Self::Error>;
47}
4849/// Trait to safely read-edit-write a register.
50/// Usefull when a register has reserved values for internal uses.
51/// Avoids writing garbage to the reserved bits.
52pub trait EditRegister<R, A>
53where
54 for<'a> R: EditableRegister<Address = A> + 'a,
55{
56/// The error type returned by editing a register
57type Error;
5859/// Edit a register. The closure takes a reference to the register,
60 /// the same register must be edited, then returned.
61async fn edit<F>(&mut self, f: F) -> Result<(), Self::Error>
62where
63 for<'w> F: FnOnce(&'w mut R);
64}
6566impl<I, R, A> ReadRegister<R, A> for I
67where
68 for<'a> R: ReadableRegister<Address = A> + 'a,
69 I: RegisterInterface<R, A>,
70for<'a> A: 'a,
71{
72type Error = I::Error;
7374async fn read(&mut self) -> Result<R, Self::Error> {
75self.read_register().await
76}
77}
7879impl<I, R, A> WriteRegister<R, A> for I
80where
81 for<'a> R: WritableRegister<Address = A> + 'a,
82 I: RegisterInterface<R, A>,
83for<'a> A: 'a,
84{
85type Error = I::Error;
8687async fn write(&mut self, register: R) -> Result<(), Self::Error> {
88self.write_register(®ister).await
89}
90}
9192impl<I, R, A> EditRegister<R, A> for I
93where
94 for<'a> R: EditableRegister<Address = A> + 'a,
95 I: RegisterInterface<R, A>,
96for<'a> A: 'a,
97{
98type Error = I::Error;
99100async fn edit<F>(&mut self, f: F) -> Result<(), Self::Error>
101where
102 for<'w> F: FnOnce(&'w mut R),
103 {
104let mut val = self.read_register().await?;
105 f(&mut val);
106self.write_register(&val).await
107}
108}