Skip to main content

ph_haptics/
error.rs

1use crate::motor::MotorKind;
2use core::fmt;
3
4/// Compiled-runner construction errors.
5#[derive(Copy, Clone, Debug, Eq, PartialEq)]
6pub enum Error {
7    /// Program has no instructions.
8    EmptyProgram,
9    /// Program motor type and runtime motor config do not match.
10    MotorKindMismatch {
11        /// Motor type declared by the program.
12        expected: MotorKind,
13        /// Motor type provided to the runner.
14        got: MotorKind,
15    },
16}
17
18impl fmt::Display for Error {
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        match self {
21            Self::EmptyProgram => f.write_str("program has no instructions"),
22            Self::MotorKindMismatch { expected, got } => {
23                write!(
24                    f,
25                    "motor kind mismatch: program is {expected}, runner is {got}"
26                )
27            }
28        }
29    }
30}
31
32impl core::error::Error for Error {}
33
34impl fmt::Display for MotorKind {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        f.write_str(match self {
37            Self::Erm => "ERM",
38            Self::Lra => "LRA",
39        })
40    }
41}
42
43#[cfg(test)]
44// This crate is no_alloc and has no `extern crate alloc`, so the lint's advice
45// to import from `alloc` does not apply. Tests pull in `std` deliberately.
46#[allow(clippy::std_instead_of_alloc)]
47mod tests {
48    use super::*;
49    use std::string::ToString;
50
51    #[test]
52    fn errors_render_readable_messages() {
53        assert_eq!(
54            Error::EmptyProgram.to_string(),
55            "program has no instructions"
56        );
57        assert_eq!(
58            Error::MotorKindMismatch {
59                expected: MotorKind::Erm,
60                got: MotorKind::Lra,
61            }
62            .to_string(),
63            "motor kind mismatch: program is ERM, runner is LRA"
64        );
65    }
66}