1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
use pyo3::{exceptions::PyRuntimeError, PyErr, Python};
use serde::{de, ser};
use std::fmt::{self, Display};

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug)]
pub struct Error {
    pyerr: PyErr,
    hints: Vec<String>,
}

#[macro_export]
macro_rules! err {
    ($($t:tt)*) => {
        $crate::error::Error::new(format!($($t)*))
    }
}

#[macro_export]
macro_rules! bail {
    ($($t:tt)*) => {
        return Err($crate::err!($($t)*));
    }
}

impl Error {
    pub fn new<T>(t: T) -> Self
    where
        T: ToString,
    {
        let py = unsafe { Python::assume_gil_acquired() };

        let pyerr = if PyErr::occurred(py) {
            PyErr::fetch(py)
        } else {
            PyErr::new::<PyRuntimeError, _>(t.to_string())
        };

        Self {
            pyerr,
            hints: vec![t.to_string()],
        }
    }
}

impl<T> From<T> for Error
where
    T: std::error::Error,
{
    fn from(e: T) -> Self {
        Self::new(e)
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.pyerr)
    }
}

pub trait Convert<T> {
    fn de<E>(self) -> std::result::Result<T, E>
    where
        E: de::Error,
        Self: Sized;

    fn ser<E>(self) -> std::result::Result<T, E>
    where
        E: ser::Error,
        Self: Sized;

    fn restore(self) -> Option<T>
    where
        Self: Sized;

    fn context<C>(self, context: C) -> Result<T>
    where
        C: Display + Send + Sync + 'static;

    fn with_context<C, F>(self, f: F) -> Result<T>
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C;
}

impl<T> Convert<T> for Result<T> {
    fn de<E>(self) -> std::result::Result<T, E>
    where
        E: de::Error,
        Self: Sized,
    {
        self.map_err(|e| de::Error::custom(e.to_string()))
    }

    fn ser<E>(self) -> std::result::Result<T, E>
    where
        E: ser::Error,
        Self: Sized,
    {
        self.map_err(|e| ser::Error::custom(e.to_string()))
    }

    fn restore(self) -> Option<T> {
        match self {
            Ok(t) => Some(t),
            Err(e) => {
                let py = unsafe { Python::assume_gil_acquired() };
                e.pyerr.restore(py);
                None
            }
        }
    }

    fn context<C>(mut self, context: C) -> Result<T>
    where
        C: Display + Send + Sync + 'static,
    {
        if let Err(e) = self.as_mut() {
            e.hints.push(context.to_string());
        }
        self
    }

    fn with_context<C, F>(mut self, f: F) -> Result<T>
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C,
    {
        if let Err(e) = self.as_mut() {
            e.hints.push(f().to_string());
        }
        self
    }
}