use alloc::string::String;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("invalid wire format: expected at least {expected} bytes, got {got}")]
TooShort {
expected: usize,
got: usize,
},
#[error("invalid wire format: {got} bytes exceeds maximum of 256")]
TooLong {
got: usize,
},
#[error("invalid MType: {0:#05b}")]
InvalidMType(u8),
#[error("invalid major version: {0:#04b}")]
InvalidMajor(u8),
#[error("invalid rejoin type: {0}")]
InvalidRejoinType(u8),
#[error("FOpts and FPort=0 cannot both carry MAC commands")]
ConflictingMacCommands,
#[error("FOpts length {0} exceeds maximum of 15")]
FOptsTooLong(usize),
#[error("expected key length {expected}, got {got}")]
InvalidKeyLength {
expected: usize,
got: usize,
},
#[error("expected identifier length {expected}, got {got}")]
InvalidIdentifierLength {
expected: usize,
got: usize,
},
#[error("MIC mismatch")]
MicMismatch,
#[error("missing key for operation: {0}")]
MissingKey(&'static str),
#[error("operation not supported for this message type in this LoRaWAN version: {0}")]
UnsupportedForVersion(&'static str),
#[error("required builder field not set: {0}")]
MissingField(&'static str),
#[error("payload too large: {0} bytes")]
PayloadTooLarge(usize),
#[error("invalid Join Accept length: {0} bytes (expected 17 or 33)")]
InvalidJoinAcceptLength(usize),
#[error("{0}")]
Other(String),
#[cfg(feature = "hex_base64")]
#[error("hex decode error: {0}")]
Hex(hex::FromHexError),
#[cfg(feature = "hex_base64")]
#[error("base64 decode error: {0}")]
Base64(base64::DecodeError),
}
#[cfg(feature = "hex_base64")]
impl From<hex::FromHexError> for Error {
fn from(e: hex::FromHexError) -> Self {
Self::Hex(e)
}
}
#[cfg(feature = "hex_base64")]
impl From<base64::DecodeError> for Error {
fn from(e: base64::DecodeError) -> Self {
Self::Base64(e)
}
}
pub type Result<T> = core::result::Result<T, Error>;
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
#[test]
fn error_display_includes_context() {
let e = Error::TooShort { expected: 12, got: 7 };
assert_eq!(e.to_string(), "invalid wire format: expected at least 12 bytes, got 7");
}
#[test]
fn invalid_mtype_format() {
let e = Error::InvalidMType(0b111);
assert_eq!(e.to_string(), "invalid MType: 0b111");
}
#[test]
fn result_alias_works() {
#[allow(clippy::unnecessary_wraps)]
fn ok() -> Result<u8> {
Ok(42)
}
fn err() -> Result<u8> {
Err(Error::MicMismatch)
}
assert_eq!(ok().unwrap(), 42);
assert!(err().is_err());
}
}