Skip to main content

twig/
error.rs

1use std::fmt;
2
3use crate::ffi;
4
5#[derive(Debug, Clone, Copy, Eq, PartialEq)]
6pub enum Error {
7    InvalidArgument,
8    ParseError,
9    OutOfMemory,
10    UnsupportedFormat,
11    /// A locator resolved to no node (editor).
12    NotFound,
13    /// A selector locator matched more than one node (editor).
14    Ambiguous,
15    /// The target node has no editable span/interior (editor).
16    NotEditable,
17    /// The edit produced a document that no longer parses; it was rolled back
18    /// (editor).
19    EditConflict,
20    /// A metadata block's body contains `</script`, so it can't be emitted into
21    /// a raw-text `<script>` HTML data island without an injection risk; the
22    /// HTML printer refused (render/serialize-to-HTML).
23    UnsafeMetadata,
24    Internal,
25}
26
27impl Error {
28    pub(crate) fn from_status(status: ffi::TwigStatus) -> Result<(), Self> {
29        match status.0 {
30            ffi::TwigStatus::OK => Ok(()),
31            ffi::TwigStatus::INVALID_ARGUMENT => Err(Self::InvalidArgument),
32            ffi::TwigStatus::PARSE_ERROR => Err(Self::ParseError),
33            ffi::TwigStatus::OUT_OF_MEMORY => Err(Self::OutOfMemory),
34            ffi::TwigStatus::UNSUPPORTED_FORMAT => Err(Self::UnsupportedFormat),
35            ffi::TwigStatus::NOT_FOUND => Err(Self::NotFound),
36            ffi::TwigStatus::AMBIGUOUS => Err(Self::Ambiguous),
37            ffi::TwigStatus::NOT_EDITABLE => Err(Self::NotEditable),
38            ffi::TwigStatus::EDIT_CONFLICT => Err(Self::EditConflict),
39            ffi::TwigStatus::UNSAFE_METADATA => Err(Self::UnsafeMetadata),
40            _ => Err(Self::Internal),
41        }
42    }
43}
44
45impl fmt::Display for Error {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        match self {
48            Error::InvalidArgument => f.write_str("invalid argument"),
49            Error::ParseError => f.write_str("parse error"),
50            Error::OutOfMemory => f.write_str("out of memory"),
51            Error::UnsupportedFormat => f.write_str("unsupported format"),
52            Error::NotFound => f.write_str("locator matched no node"),
53            Error::Ambiguous => f.write_str("selector matched more than one node"),
54            Error::NotEditable => f.write_str("node has no editable span"),
55            Error::EditConflict => f.write_str("edit produced an unparseable document"),
56            Error::UnsafeMetadata => f.write_str("metadata contains </script; unsafe to embed in HTML"),
57            Error::Internal => f.write_str("internal error"),
58        }
59    }
60}
61
62impl std::error::Error for Error {}