use crate::limits::ChargeError;
#[derive(Debug, thiserror::Error)]
pub enum ViewError {
#[error("'UnknownObject' object has no attribute '{0}'")]
NoAttribute(&'static str),
#[error("malformed object: {0}")]
Malformed(String),
#[error("bytes must be in range(0, 256)")]
ByteRange,
#[error(transparent)]
Charge(#[from] ChargeError),
}
const _: () = crate::send_sync::<ViewError>();
impl ViewError {
pub fn malformed(detail: std::fmt::Arguments<'_>, meter: &crate::limits::Meter) -> Self {
let mut bytes = Vec::new();
if let Err(error) =
crate::limits::reserve_exact(&mut bytes, CAPACITY, CAPACITY as u64, meter)
{
return Self::Charge(ChargeError::Budget(error));
}
let mut text = String::from_utf8(bytes).unwrap_or_default();
let _ = std::fmt::write(&mut Bounded(&mut text), detail);
Self::Malformed(text)
}
}
const CAPACITY: usize = 512;
struct Bounded<'a>(&'a mut String);
impl std::fmt::Write for Bounded<'_> {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
if self.0.len().saturating_add(s.len()) > CAPACITY {
return Err(std::fmt::Error);
}
self.0.push_str(s);
Ok(())
}
}