Skip to main content

unityrs_core/objmode/
error.rs

1//! Errors of the borrowed object-mode view.
2use crate::limits::ChargeError;
3
4/// A failure reading an object-mode attribute.
5#[derive(Debug, thiserror::Error)]
6pub enum ViewError {
7    /// A required attribute missing on an `UnknownObject`.
8    #[error("'UnknownObject' object has no attribute '{0}'")]
9    NoAttribute(&'static str),
10    /// A type or range no characterised typetree writes.
11    #[error("malformed object: {0}")]
12    Malformed(String),
13    /// An integer that Python's bytes constructor refuses.
14    #[error("bytes must be in range(0, 256)")]
15    ByteRange,
16    /// Work refused by the caller's meter.
17    #[error(transparent)]
18    Charge(#[from] ChargeError),
19}
20const _: () = crate::send_sync::<ViewError>();
21impl ViewError {
22    /// Formats a malformed-input diagnostic into a fixed 512-byte buffer.
23    /// An allocator refusal returns `Charge` instead, tagged with `meter`'s
24    /// reservation. A longer diagnostic stops at the last complete write.
25    pub fn malformed(detail: std::fmt::Arguments<'_>, meter: &crate::limits::Meter) -> Self {
26        // Diagnostics are a fixed-size constant, as in meshdecode's existing
27        // memory contract. Even this allocation can be refused by the host.
28        let mut bytes = Vec::new();
29        if let Err(error) =
30            crate::limits::reserve_exact(&mut bytes, CAPACITY, CAPACITY as u64, meter)
31        {
32            return Self::Charge(ChargeError::Budget(error));
33        }
34        let mut text = String::from_utf8(bytes).unwrap_or_default();
35        let _ = std::fmt::write(&mut Bounded(&mut text), detail);
36        Self::Malformed(text)
37    }
38}
39
40const CAPACITY: usize = 512;
41struct Bounded<'a>(&'a mut String);
42impl std::fmt::Write for Bounded<'_> {
43    fn write_str(&mut self, s: &str) -> std::fmt::Result {
44        if self.0.len().saturating_add(s.len()) > CAPACITY {
45            return Err(std::fmt::Error);
46        }
47        self.0.push_str(s);
48        Ok(())
49    }
50}