use std::{
error::Error,
fmt::{self, Debug, Display, Formatter},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrivateContext {
key: String,
value: String,
}
impl PrivateContext {
pub fn key(&self) -> &str {
&self.key
}
pub fn value(&self) -> &str {
&self.value
}
}
pub struct PrivateReport {
source: Box<dyn Error + Send + Sync>,
context: Vec<PrivateContext>,
}
impl PrivateReport {
pub fn new<E>(source: E) -> Self
where
E: Error + Send + Sync + 'static,
{
Self {
source: Box::new(source),
context: Vec::new(),
}
}
#[must_use]
pub fn context(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.context.push(PrivateContext {
key: key.into(),
value: value.into(),
});
self
}
pub fn source_error(&self) -> &(dyn Error + Send + Sync + 'static) {
self.source.as_ref()
}
pub fn contexts(&self) -> &[PrivateContext] {
&self.context
}
}
impl Debug for PrivateReport {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PrivateReport")
.field("source", &self.source)
.field("context", &self.context)
.finish()
}
}
impl Display for PrivateReport {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
Display::fmt(&self.source, formatter)?;
for entry in &self.context {
write!(formatter, " [{}={}]", entry.key, entry.value)?;
}
Ok(())
}
}
impl Error for PrivateReport {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(self.source.as_ref())
}
}