Skip to main content

libghostty_vt/
error.rs

1//! Error handling.
2use crate::ffi;
3
4/// Convenient alias for fallible return values from libghostty-vt.
5pub type Result<T> = std::result::Result<T, Error>;
6
7/// Possible errors libghostty-vt may return.
8#[derive(Debug, Clone, Copy)]
9pub enum Error {
10    /// Out of memory.
11    OutOfMemory,
12    /// Invalid value was specified or returned.
13    InvalidValue,
14    /// Ran out of space when writing to a buffer.
15    OutOfSpace {
16        /// Required minimum size of the buffer.
17        required: usize,
18    },
19}
20
21impl std::fmt::Display for Error {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        match self {
24            Self::OutOfMemory => write!(f, "out of memory"),
25            Self::InvalidValue => write!(f, "invalid value"),
26            Self::OutOfSpace { required } => {
27                write!(f, "out of space, {required} bytes required")
28            }
29        }
30    }
31}
32
33impl std::error::Error for Error {}
34
35pub(crate) fn from_result(code: ffi::GhosttyResult) -> Result<()> {
36    match code {
37        ffi::GhosttyResult_GHOSTTY_SUCCESS => Ok(()),
38        ffi::GhosttyResult_GHOSTTY_OUT_OF_MEMORY => Err(Error::OutOfMemory),
39        ffi::GhosttyResult_GHOSTTY_OUT_OF_SPACE => Err(Error::OutOfSpace { required: 0 }),
40        _ => Err(Error::InvalidValue),
41    }
42}
43
44pub(crate) fn from_result_with_len(code: ffi::GhosttyResult, len: usize) -> Result<usize> {
45    match code {
46        ffi::GhosttyResult_GHOSTTY_SUCCESS => Ok(len),
47        ffi::GhosttyResult_GHOSTTY_OUT_OF_MEMORY => Err(Error::OutOfMemory),
48        ffi::GhosttyResult_GHOSTTY_OUT_OF_SPACE => Err(Error::OutOfSpace { required: len }),
49        _ => Err(Error::InvalidValue),
50    }
51}