forked from davidhewitt/pythonize
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.rs
More file actions
190 lines (170 loc) · 5.79 KB
/
error.rs
File metadata and controls
190 lines (170 loc) · 5.79 KB
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use pyo3::{exceptions::*, DowncastError, DowncastIntoError};
use pyo3::{PyDowncastError, PyErr};
use serde::{de, ser};
use std::error;
use std::fmt::{self, Debug, Display};
use std::result;
/// Alias for `std::result::Result` with error type `PythonizeError`
pub type Result<T> = result::Result<T, PythonizeError>;
/// Errors that can occur when serializing/deserializing Python objects
pub struct PythonizeError {
pub(crate) inner: Box<ErrorImpl>,
}
impl PythonizeError {
pub(crate) fn msg<T>(text: T) -> Self
where
T: ToString,
{
Self {
inner: Box::new(ErrorImpl::Message(text.to_string())),
}
}
pub(crate) fn unsupported_type<T>(t: T) -> Self
where
T: ToString,
{
Self {
inner: Box::new(ErrorImpl::UnsupportedType(t.to_string())),
}
}
pub(crate) fn dict_key_not_string() -> Self {
Self {
inner: Box::new(ErrorImpl::DictKeyNotString),
}
}
pub(crate) fn incorrect_sequence_length(expected: usize, got: usize) -> Self {
Self {
inner: Box::new(ErrorImpl::IncorrectSequenceLength { expected, got }),
}
}
pub(crate) fn invalid_enum_type() -> Self {
Self {
inner: Box::new(ErrorImpl::InvalidEnumType),
}
}
pub(crate) fn invalid_length_enum() -> Self {
Self {
inner: Box::new(ErrorImpl::InvalidLengthEnum),
}
}
pub(crate) fn invalid_length_char() -> Self {
Self {
inner: Box::new(ErrorImpl::InvalidLengthChar),
}
}
}
/// Error codes for problems that can occur when serializing/deserializing Python objects
#[derive(Debug)]
pub enum ErrorImpl {
/// An error originating from the Python runtime
PyErr(PyErr),
/// Generic error message
Message(String),
/// A Python type not supported by the deserializer
UnsupportedType(String),
/// A `PyAny` object that failed to downcast to an expected Python type
UnexpectedType(String),
/// Dict keys should be strings to deserialize to struct fields
DictKeyNotString,
/// Sequence length did not match expected tuple or tuple struct length.
IncorrectSequenceLength { expected: usize, got: usize },
/// Enum variants should either be dict (tagged) or str (variant)
InvalidEnumType,
/// Tagged enum variants should be a dict with exactly 1 key
InvalidLengthEnum,
/// Expected a `char`, but got a Python str that was not length 1
InvalidLengthChar,
}
impl error::Error for PythonizeError {}
impl Display for PythonizeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.inner.as_ref() {
ErrorImpl::PyErr(e) => Display::fmt(e, f),
ErrorImpl::Message(s) => Display::fmt(s, f),
ErrorImpl::UnsupportedType(s) => write!(f, "unsupported type {}", s),
ErrorImpl::UnexpectedType(s) => write!(f, "unexpected type: {}", s),
ErrorImpl::DictKeyNotString => f.write_str("dict keys must have type str"),
ErrorImpl::IncorrectSequenceLength { expected, got } => {
write!(f, "expected sequence of length {}, got {}", expected, got)
}
ErrorImpl::InvalidEnumType => f.write_str("expected either a str or dict for enum"),
ErrorImpl::InvalidLengthEnum => {
f.write_str("expected tagged enum dict to have exactly 1 key")
}
ErrorImpl::InvalidLengthChar => f.write_str("expected a str of length 1 for char"),
}
}
}
impl Debug for PythonizeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.inner.as_ref().fmt(f)
}
}
impl ser::Error for PythonizeError {
fn custom<T>(msg: T) -> Self
where
T: Display,
{
Self {
inner: Box::new(ErrorImpl::Message(msg.to_string())),
}
}
}
impl de::Error for PythonizeError {
fn custom<T>(msg: T) -> Self
where
T: Display,
{
Self {
inner: Box::new(ErrorImpl::Message(msg.to_string())),
}
}
}
/// Convert an exception raised in Python to a `PythonizeError`
impl From<PyErr> for PythonizeError {
fn from(other: PyErr) -> Self {
Self {
inner: Box::new(ErrorImpl::PyErr(other)),
}
}
}
/// Handle errors that occur when attempting to use `PyAny::cast_as`
impl<'a> From<PyDowncastError<'a>> for PythonizeError {
fn from(other: PyDowncastError) -> Self {
Self {
inner: Box::new(ErrorImpl::UnexpectedType(other.to_string())),
}
}
}
/// Handle errors that occur when attempting to use `PyAny::cast_as`
impl<'a, 'py> From<DowncastError<'a, 'py>> for PythonizeError {
fn from(other: DowncastError<'a, 'py>) -> Self {
Self {
inner: Box::new(ErrorImpl::UnexpectedType(other.to_string())),
}
}
}
/// Handle errors that occur when attempting to use `PyAny::cast_as`
impl<'py> From<DowncastIntoError<'py>> for PythonizeError {
fn from(other: DowncastIntoError<'py>) -> Self {
Self {
inner: Box::new(ErrorImpl::UnexpectedType(other.to_string())),
}
}
}
/// Convert a `PythonizeError` to a Python exception
impl From<PythonizeError> for PyErr {
fn from(other: PythonizeError) -> Self {
match *other.inner {
ErrorImpl::PyErr(e) => e,
ErrorImpl::Message(e) => PyException::new_err(e),
ErrorImpl::UnsupportedType(_)
| ErrorImpl::UnexpectedType(_)
| ErrorImpl::DictKeyNotString
| ErrorImpl::InvalidEnumType => PyTypeError::new_err(other.to_string()),
ErrorImpl::IncorrectSequenceLength { .. }
| ErrorImpl::InvalidLengthEnum
| ErrorImpl::InvalidLengthChar => PyValueError::new_err(other.to_string()),
}
}
}