use core::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigError {
SampleRateOutOfRange {
got: u32,
min: u32,
max: u32,
},
BaudRateInvalid {
got: u32,
min: u32,
max: u32,
},
ToneOutOfRange {
got: u32,
nyquist: u32,
},
BaudExceedsSampleRate {
baud: u32,
sample_rate: u32,
},
SweepLenInvalid {
got: usize,
max: usize,
},
SweepGainZero {
index: usize,
},
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
ConfigError::SampleRateOutOfRange { got, min, max } => write!(
f,
"sample rate {got} Hz is out of range: must be within {min}..={max} Hz"
),
ConfigError::BaudRateInvalid { got, min, max } => write!(
f,
"baud rate {got} is invalid: must be within {min}..={max} bit/s"
),
ConfigError::ToneOutOfRange { got, nyquist } => write!(
f,
"tone {got} Hz is out of range: must be nonzero and below the Nyquist frequency {nyquist} Hz"
),
ConfigError::BaudExceedsSampleRate { baud, sample_rate } => write!(
f,
"baud rate {baud} exceeds sample rate {sample_rate} Hz: each bit needs at least one sample"
),
ConfigError::SweepLenInvalid { got, max } => write!(
f,
"space-gain sweep length {got} is invalid: must be within 1..={max}"
),
ConfigError::SweepGainZero { index } => write!(
f,
"space-gain sweep entry {index} is zero: gains must be positive Q8 values"
),
}
}
}
impl core::error::Error for ConfigError {}
#[cfg(test)]
mod tests {
extern crate std;
use super::*;
use std::string::ToString;
#[test]
fn display_sample_rate_out_of_range() {
let e = ConfigError::SampleRateOutOfRange {
got: 7_000,
min: 8_000,
max: 48_000,
};
assert_eq!(
e.to_string(),
"sample rate 7000 Hz is out of range: must be within 8000..=48000 Hz"
);
}
#[test]
fn display_baud_rate_invalid() {
let e = ConfigError::BaudRateInvalid {
got: 0,
min: 1,
max: 9_600,
};
assert_eq!(
e.to_string(),
"baud rate 0 is invalid: must be within 1..=9600 bit/s"
);
}
#[test]
fn display_tone_out_of_range() {
let e = ConfigError::ToneOutOfRange {
got: 5_000,
nyquist: 4_000,
};
assert_eq!(
e.to_string(),
"tone 5000 Hz is out of range: must be nonzero and below the Nyquist frequency 4000 Hz"
);
}
#[test]
fn display_baud_exceeds_sample_rate() {
let e = ConfigError::BaudExceedsSampleRate {
baud: 9_600,
sample_rate: 8_000,
};
assert_eq!(
e.to_string(),
"baud rate 9600 exceeds sample rate 8000 Hz: each bit needs at least one sample"
);
}
#[test]
fn error_trait_object() {
let e: &dyn core::error::Error = &ConfigError::BaudRateInvalid {
got: 0,
min: 1,
max: 9_600,
};
assert!(e.source().is_none());
}
#[test]
fn error_is_copy_and_eq() {
let e = ConfigError::ToneOutOfRange { got: 1, nyquist: 2 };
let e2 = e;
assert_eq!(e, e2);
}
}