use std::fmt;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
NotFound(String),
Security(String),
InvalidState(String),
Network(String),
NotSupported(String),
InvalidModification(String),
NotAvailable(Availability),
Timeout(String),
Aborted(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Authorization {
NotDetermined,
Restricted,
Denied,
Allowed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Availability {
Unsupported,
PoweredOff,
Unauthorized,
Resetting,
Unknown,
}
impl Error {
pub fn name(&self) -> &'static str {
match self {
Self::NotFound(_) => "NotFoundError",
Self::Security(_) => "SecurityError",
Self::InvalidState(_) => "InvalidStateError",
Self::Network(_) => "NetworkError",
Self::NotSupported(_) => "NotSupportedError",
Self::InvalidModification(_) => "InvalidModificationError",
Self::NotAvailable(_) => "NotFoundError",
Self::Timeout(_) => "TimeoutError",
Self::Aborted(_) => "AbortError",
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let detail = match self {
Self::NotFound(m)
| Self::Security(m)
| Self::InvalidState(m)
| Self::Network(m)
| Self::NotSupported(m)
| Self::InvalidModification(m)
| Self::Timeout(m)
| Self::Aborted(m) => m.clone(),
Self::NotAvailable(a) => a.to_string(),
};
write!(f, "{}: {detail}", self.name())
}
}
impl std::fmt::Display for Availability {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let detail = match self {
Self::Unsupported => "this system has no Bluetooth LE support",
Self::PoweredOff => "Bluetooth is turned off",
Self::Unauthorized => {
"this process is not authorised to use Bluetooth — on Apple \
platforms it needs NSBluetoothAlwaysUsageDescription in its \
Info.plist"
}
Self::Resetting => "the Bluetooth adapter is resetting",
Self::Unknown => "Bluetooth state is not yet known",
};
f.write_str(detail)
}
}
impl std::error::Error for Error {}
impl std::error::Error for Availability {}
impl From<Availability> for Error {
fn from(availability: Availability) -> Self {
Self::NotAvailable(availability)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_availability_explains_itself() {
let mut seen = std::collections::BTreeSet::new();
for a in [
Availability::Unsupported,
Availability::PoweredOff,
Availability::Unauthorized,
Availability::Resetting,
Availability::Unknown,
] {
let said = a.to_string();
assert!(!said.is_empty(), "{a:?} says nothing");
assert!(
!said.ends_with('.'),
"{a:?}: {said:?} ends a sentence it is inside of"
);
assert!(
seen.insert(said.clone()),
"{a:?} says the same as another: {said:?}"
);
}
}
#[test]
fn an_unavailable_error_carries_the_same_explanation() {
let why = Availability::PoweredOff;
let wrapped = Error::NotAvailable(why).to_string();
assert!(
wrapped.contains(&why.to_string()),
"{wrapped:?} does not contain {:?}",
why.to_string()
);
assert!(wrapped.starts_with("NotFoundError"), "got {wrapped:?}");
}
}