Skip to main content

ink_rs/
error.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Errors coming back out of Ink.
6
7use core::fmt;
8
9use crate::ffi;
10
11/// The kind of failure Ink reported.
12///
13/// These mirror the `absl::Status` codes Ink actually returns. By far the most
14/// common is [`ErrorKind::InvalidArgument`]: it covers a brush size that is not
15/// finite and positive, stroke inputs that go backwards in time, and inputs
16/// that disagree about which optional fields they carry.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18#[non_exhaustive]
19pub enum ErrorKind {
20    /// An argument was outside the range Ink accepts.
21    InvalidArgument,
22    /// The object was not in a state where the call made sense, such as
23    /// updating the shape of a stroke that was never started.
24    FailedPrecondition,
25    /// An index was past the end.
26    OutOfRange,
27    /// Something Ink knows about but has not implemented.
28    Unimplemented,
29    /// A lookup found nothing.
30    NotFound,
31    /// Ink hit an internal inconsistency.
32    Internal,
33    /// Anything else, including a status code this crate does not know yet.
34    Unknown,
35}
36
37impl ErrorKind {
38    fn from_status(code: i32) -> Self {
39        match code {
40            3 => Self::InvalidArgument,
41            5 => Self::NotFound,
42            9 => Self::FailedPrecondition,
43            11 => Self::OutOfRange,
44            12 => Self::Unimplemented,
45            13 => Self::Internal,
46            _ => Self::Unknown,
47        }
48    }
49
50    fn describe(self) -> &'static str {
51        match self {
52            Self::InvalidArgument => "invalid argument",
53            Self::FailedPrecondition => "failed precondition",
54            Self::OutOfRange => "out of range",
55            Self::Unimplemented => "unimplemented",
56            Self::NotFound => "not found",
57            Self::Internal => "internal error",
58            Self::Unknown => "error",
59        }
60    }
61}
62
63/// A failure reported by Ink, with the message it came with.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct Error {
66    kind: ErrorKind,
67    message: String,
68}
69
70impl Error {
71    pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
72        Self {
73            kind,
74            message: message.into(),
75        }
76    }
77
78    /// What sort of failure this was.
79    pub fn kind(&self) -> ErrorKind {
80        self.kind
81    }
82
83    /// Ink's own description of the failure. May be empty.
84    pub fn message(&self) -> &str {
85        &self.message
86    }
87}
88
89impl fmt::Display for Error {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        if self.message.is_empty() {
92            f.write_str(self.kind.describe())
93        } else {
94            write!(f, "{}: {}", self.kind.describe(), self.message)
95        }
96    }
97}
98
99impl std::error::Error for Error {}
100
101/// Result type used throughout this crate.
102pub type Result<T> = std::result::Result<T, Error>;
103
104/// Converts a status returned by the C++ facade into a `Result`.
105///
106/// Reads the thread-local message the facade recorded, so it has to be called
107/// before anything else crosses the boundary on this thread.
108pub(crate) fn check(status: ffi::StatusCode) -> Result<()> {
109    let code = ffi::status_code_value(status);
110    if code == 0 {
111        return Ok(());
112    }
113    Err(Error::new(
114        ErrorKind::from_status(code),
115        ffi::last_error_message(),
116    ))
117}