Skip to main content

miden_note_schema/
error.rs

1//! Error types for note storage schemas.
2
3use core::fmt;
4
5/// Why a bundled codec did not return a value.
6///
7/// The class covers the whole life of a codec call: the structural load policy, the compilation
8/// of the component, the instantiation that precedes the call, the call itself, and the host
9/// caps applied to what the call returned.
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11pub enum CodecFailure {
12    /// The call used its whole fuel budget.
13    OutOfFuel,
14    /// The structural load policy rejected the component, or a host limit was exceeded in the
15    /// guest or in the returned value.
16    LimitExceeded,
17    /// The component trapped, or the engine rejected the component or the call.
18    Trapped,
19    /// The codec returned its own rejection message.
20    Rejected,
21}
22
23/// An error reported while reading, encoding, or decoding a note storage schema.
24#[derive(Clone, Debug, Eq, PartialEq)]
25pub struct Error {
26    message: String,
27    codec_failure: Option<CodecFailure>,
28}
29
30impl Error {
31    /// Creates an error with an actionable message.
32    pub fn new(message: impl Into<String>) -> Self {
33        Self {
34            message: message.into(),
35            codec_failure: None,
36        }
37    }
38
39    /// Creates an error that reports how a bundled codec failed.
40    ///
41    /// The structural load policy and the bundled codec adapter report a failure class.
42    pub(crate) fn codec(kind: CodecFailure, message: impl Into<String>) -> Self {
43        Self {
44            message: message.into(),
45            codec_failure: Some(kind),
46        }
47    }
48
49    /// Returns the failure class of a bundled codec failure.
50    ///
51    /// The structural load policy classifies every rejection it reports, and the bundled codec
52    /// adapter classifies every compilation, instantiation, call, and host cap failure. Errors
53    /// from other sources, such as a schema that does not parse, return `None`.
54    pub fn codec_failure(&self) -> Option<CodecFailure> {
55        self.codec_failure
56    }
57
58    /// Adds context before the current error message.
59    pub(crate) fn context(self, context: impl fmt::Display) -> Self {
60        Self {
61            message: format!("{context}: {}", self.message),
62            codec_failure: self.codec_failure,
63        }
64    }
65}
66
67impl fmt::Display for Error {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        f.write_str(&self.message)
70    }
71}
72
73impl std::error::Error for Error {}
74
75/// A result returned by note storage schema operations.
76pub type Result<T> = core::result::Result<T, Error>;