chore(home-assistant): streamline Python conversion for UnexpectedState
This commit is contained in:
@@ -1,35 +1,14 @@
|
|||||||
use std::sync::Arc;
|
use std::{convert::Infallible, str::FromStr, sync::Arc};
|
||||||
|
|
||||||
use pyo3::{exceptions::PyException, prelude::*};
|
use python_utils::{FromPyFromStr, ToStrToPy};
|
||||||
use snafu::{ResultExt, Snafu};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, derive_more::Display)]
|
#[derive(Debug, Clone, derive_more::Display, FromPyFromStr, ToStrToPy)]
|
||||||
pub struct UnexpectedState(pub Arc<str>);
|
pub struct UnexpectedState(pub Arc<str>);
|
||||||
|
|
||||||
#[derive(Debug, Snafu)]
|
impl FromStr for UnexpectedState {
|
||||||
pub enum ExtractUnexpectedStateError {
|
type Err = Infallible;
|
||||||
/// couldn't extract the object as a string
|
|
||||||
ExtractStringError { source: PyErr },
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<ExtractUnexpectedStateError> for PyErr {
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
fn from(error: ExtractUnexpectedStateError) -> Self {
|
Ok(Self(s.into()))
|
||||||
match &error {
|
|
||||||
ExtractUnexpectedStateError::ExtractStringError { .. } => {
|
|
||||||
PyException::new_err(error.to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: replace with a derive(PyFromStr) (analogous to serde_with::DeserializeFromStr) once I make one
|
|
||||||
impl<'a, 'py> FromPyObject<'a, 'py> for UnexpectedState {
|
|
||||||
type Error = ExtractUnexpectedStateError;
|
|
||||||
|
|
||||||
fn extract(ob: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
|
|
||||||
let s = ob.extract::<String>().context(ExtractStringSnafu)?;
|
|
||||||
let s = s.into();
|
|
||||||
|
|
||||||
Ok(UnexpectedState(s))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user