use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReasonCode {
UnsupportedOperation,
UnsupportedComponentKind,
UnsupportedNativeSurface,
UnsupportedBundleFormat,
UnsupportedProtocolVersion,
ProjectionProfileMismatch,
UnsupportedPermissionProfile,
UnsupportedPlatform,
UnsupportedArchitecture,
RecoveryRequired,
Stale,
InvalidTarget,
LockUnavailable,
StateUnavailable,
IntegrityMismatch,
}
impl ReasonCode {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::UnsupportedOperation => "unsupported_operation",
Self::UnsupportedComponentKind => "unsupported_component_kind",
Self::UnsupportedNativeSurface => "unsupported_native_surface",
Self::UnsupportedBundleFormat => "unsupported_bundle_format",
Self::UnsupportedProtocolVersion => "unsupported_protocol_version",
Self::ProjectionProfileMismatch => "projection_profile_mismatch",
Self::UnsupportedPermissionProfile => "unsupported_permission_profile",
Self::UnsupportedPlatform => "unsupported_platform",
Self::UnsupportedArchitecture => "unsupported_architecture",
Self::RecoveryRequired => "recovery_required",
Self::Stale => "stale",
Self::InvalidTarget => "invalid_target",
Self::LockUnavailable => "lock_unavailable",
Self::StateUnavailable => "state_unavailable",
Self::IntegrityMismatch => "integrity_mismatch",
}
}
}
impl fmt::Display for ReasonCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug)]
pub struct Error {
reason: ReasonCode,
detail: String,
source: Option<Box<dyn std::error::Error + Send + Sync>>,
}
impl Error {
pub fn new(reason: ReasonCode, detail: impl Into<String>) -> Self {
Self {
reason,
detail: detail.into(),
source: None,
}
}
#[must_use]
pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
self.source = Some(Box::new(source));
self
}
#[must_use]
pub fn is_missing_path(&self) -> bool {
self.source
.as_ref()
.and_then(|source| source.downcast_ref::<std::io::Error>())
.is_some_and(|source| source.kind() == std::io::ErrorKind::NotFound)
}
#[must_use]
pub const fn reason(&self) -> ReasonCode {
self.reason
}
#[must_use]
pub fn detail(&self) -> &str {
&self.detail
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.reason, self.detail)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source
.as_ref()
.map(|boxed| &**boxed as &(dyn std::error::Error + 'static))
}
}
pub type Result<T> = std::result::Result<T, Error>;