use alloc::{
borrow::Cow,
string::{
String,
ToString,
},
sync::Arc,
vec::Vec,
};
use core::{
error::Error,
fmt,
};
use std::path::Path;
use crate::errors::{
BunsenError,
BunsenErrorKind,
};
const MAX_CANDIDATES_SHOWN: usize = 16;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Namespace {
Table(Cow<'static, str>),
Path,
Url,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LookupProblem {
Missing,
Unauthorized,
Denied,
Duplicate,
Undeclared,
Absent,
OutOfRange {
len: usize,
},
KeySet {
unexpected: Vec<String>,
missing: Vec<String>,
},
}
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct LookupError {
pub namespace: Namespace,
pub key: String,
pub problem: LookupProblem,
pub candidates: Vec<String>,
pub source: Option<Arc<dyn Error + Send + Sync + 'static>>,
}
impl LookupError {
pub fn new(
namespace: Namespace,
key: impl Into<String>,
problem: LookupProblem,
) -> Self {
Self {
namespace,
key: key.into(),
problem,
candidates: Vec::new(),
source: None,
}
}
pub fn missing(
table: impl Into<Cow<'static, str>>,
key: impl Into<String>,
) -> Self {
Self::new(Namespace::Table(table.into()), key, LookupProblem::Missing)
}
pub fn duplicate(
table: impl Into<Cow<'static, str>>,
key: impl Into<String>,
) -> Self {
Self::new(
Namespace::Table(table.into()),
key,
LookupProblem::Duplicate,
)
}
pub fn undeclared(
table: impl Into<Cow<'static, str>>,
key: impl Into<String>,
) -> Self {
Self::new(
Namespace::Table(table.into()),
key,
LookupProblem::Undeclared,
)
}
pub fn absent(
table: impl Into<Cow<'static, str>>,
key: impl Into<String>,
) -> Self {
Self::new(Namespace::Table(table.into()), key, LookupProblem::Absent)
}
pub fn out_of_range(
table: impl Into<Cow<'static, str>>,
key: impl fmt::Display,
len: usize,
) -> Self {
Self::new(
Namespace::Table(table.into()),
key.to_string(),
LookupProblem::OutOfRange { len },
)
}
pub fn path(
path: impl AsRef<Path>,
problem: LookupProblem,
) -> Self {
Self::new(
Namespace::Path,
path.as_ref().display().to_string(),
problem,
)
}
pub fn url(
url: impl Into<String>,
problem: LookupProblem,
) -> Self {
Self::new(Namespace::Url, url, problem)
}
pub fn with_candidates<I, S>(
mut self,
candidates: I,
) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.candidates = candidates.into_iter().map(Into::into).collect();
self
}
pub fn with_source<E>(
mut self,
source: E,
) -> Self
where
E: Error + Send + Sync + 'static,
{
self.source = Some(Arc::new(source));
self
}
}
impl fmt::Display for LookupError {
fn fmt(
&self,
f: &mut fmt::Formatter<'_>,
) -> fmt::Result {
let key = &self.key;
match &self.namespace {
Namespace::Table(table) => {
match &self.problem {
LookupProblem::Missing => write!(f, "no {table} {key:?}")?,
LookupProblem::Unauthorized => write!(f, "{table} {key:?}: unauthorized")?,
LookupProblem::Denied => write!(f, "{table} {key:?}: access denied")?,
LookupProblem::Duplicate => write!(f, "duplicate {table} {key:?}")?,
LookupProblem::Undeclared => write!(f, "{table} {key:?} is not declared")?,
LookupProblem::Absent => write!(f, "{table} {key:?} is absent")?,
LookupProblem::OutOfRange { len } => {
write!(f, "{table} {key} is out of range; there are {len}")?
}
LookupProblem::KeySet {
unexpected,
missing,
} => {
write!(f, "{table} {key}: keys do not match")?;
if !unexpected.is_empty() {
write!(f, "; unexpected: {}", unexpected.join(", "))?;
}
if !missing.is_empty() {
write!(f, "; missing: {}", missing.join(", "))?;
}
}
}
if !self.candidates.is_empty() {
let shown = self.candidates.len().min(MAX_CANDIDATES_SHOWN);
write!(f, "; there are: {}", self.candidates[..shown].join(", "))?;
if shown < self.candidates.len() {
write!(f, ", and {} more", self.candidates.len() - shown)?;
}
}
Ok(())
}
Namespace::Path | Namespace::Url => match &self.problem {
LookupProblem::Missing => write!(f, "{key}: not found"),
LookupProblem::Unauthorized => write!(f, "{key}: unauthorized"),
LookupProblem::Denied => write!(f, "{key}: access denied"),
LookupProblem::Duplicate => write!(f, "{key}: already exists"),
LookupProblem::Undeclared => write!(f, "{key}: not declared"),
LookupProblem::Absent => write!(f, "{key}: absent"),
LookupProblem::OutOfRange { len } => {
write!(f, "{key}: out of range; there are {len}")
}
LookupProblem::KeySet { .. } => write!(f, "{key}: keys do not match"),
},
}
}
}
impl Error for LookupError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_deref().map(|s| s as &(dyn Error + 'static))
}
}
impl From<LookupError> for BunsenError {
#[track_caller]
fn from(error: LookupError) -> Self {
BunsenError::from_cause(BunsenErrorKind::Lookup, error)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_table_display() {
assert_eq!(
LookupError::missing("resource", "weights").to_string(),
"no resource \"weights\""
);
assert_eq!(
LookupError::duplicate("provider", "hf").to_string(),
"duplicate provider \"hf\""
);
assert_eq!(
LookupError::out_of_range("shard", 9, 4).to_string(),
"shard 9 is out of range; there are 4"
);
}
#[test]
fn test_many_candidates_are_counted() {
let names: Vec<String> = (0..20).map(|i| alloc::format!("c{i}")).collect();
let text = LookupError::missing("language", "xx")
.with_candidates(names)
.to_string();
assert!(text.ends_with("c15, and 4 more"), "{text}");
}
#[test]
fn test_path_display_and_source() {
let io = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
let e = LookupError::path("/a/b", LookupProblem::Missing).with_source(io);
assert_eq!(e.to_string(), "/a/b: not found");
assert!(e.source().is_some());
}
}