Skip to main content

twig/
error.rs

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