add static assertion

This commit is contained in:
Robert 2022-12-17 23:03:36 +01:00
parent b284e2ebab
commit 62825d5d28
5 changed files with 17 additions and 9 deletions

View file

@ -11,5 +11,4 @@ path = "src/lib.rs"
[dependencies] [dependencies]
serialport = "4.2.0" serialport = "4.2.0"
rand = "0.8.5" rand = "0.8.5"

View file

@ -16,6 +16,6 @@ fn main() {
direction *= -1; direction *= -1;
} }
sleep(Duration::from_millis(50)); sleep(Duration::from_millis(40));
} }
} }

9
src/assert.rs Normal file
View file

@ -0,0 +1,9 @@
struct AssertInRange<const VALUE: usize, const MIN: usize, const MAX: usize>;
impl<const VALUE: usize, const MIN: usize, const MAX: usize> AssertInRange<VALUE, MIN, MAX> {
const OK: () = assert!(MIN <= VALUE && VALUE <= MAX);
}
pub fn assert_in_range<const VALUE: usize, const MIN: usize, const MAX: usize> () {
let () = AssertInRange::<VALUE, MIN, MAX>::OK;
}

View file

@ -5,9 +5,8 @@
use std::{process::Command, time::Duration, fmt::Debug, thread::sleep}; use std::{process::Command, time::Duration, fmt::Debug, thread::sleep};
use rand::Rng; use rand::Rng;
use serialport::SerialPort; use serialport::SerialPort;
use crate::error::Error;
use crate::{request::Request, build_request}; use crate::{assert::assert_in_range, error::Error, request::Request, build_request};
macro_rules! log { macro_rules! log {
($text: literal, $($arg:tt)*) => (println!(concat!("[B15F] ", $text), $($arg)*)); ($text: literal, $($arg:tt)*) => (println!(concat!("[B15F] ", $text), $($arg)*));
@ -125,11 +124,11 @@ impl B15F {
/// ///
/// # Examples /// # Examples
/// ///
pub fn digital_write<const port: u8> (&mut self, value: u8) -> Result<(), Error> { pub fn digital_write<const PORT: usize> (&mut self, value: u8) -> Result<(), Error> {
assert!(port == 0 || port == 1); assert_in_range::<PORT, 0, 1>();
let reversed = value.reverse_bits(); let reversed = value.reverse_bits();
let request = if port == 0 { Request::DigitalWrite0 } else { Request::DigitalWrite1 }; let request = if PORT == 0 { Request::DigitalWrite0 } else { Request::DigitalWrite1 };
self.usart.write(build_request![request, reversed])?; self.usart.write(build_request![request, reversed])?;
@ -137,7 +136,7 @@ impl B15F {
self.usart.read(&mut aw)?; self.usart.read(&mut aw)?;
if aw[0] != B15F::MSG_OK { if aw[0] != B15F::MSG_OK {
return Err(format!("Setting Port {} failed", port).into()); return Err(format!("Setting Port {} failed", PORT).into());
} }
Ok(()) Ok(())

View file

@ -16,5 +16,6 @@
pub mod b15f; pub mod b15f;
mod request; mod request;
mod error; mod error;
mod assert;
pub use crate::b15f::B15F; pub use crate::b15f::B15F;