use pyo3::{
exceptions::PyTypeError,
prelude::*,
types::{PyDict, PyString},
};
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum MessageType {
Start,
Stop,
Pause,
Resume,
Restart,
Status,
Metrics,
}
impl<'a> FromPyObject<'a> for MessageType {
fn extract(ob: &'a PyAny) -> PyResult<Self> {
if let Ok(message_type) = ob.extract::<&str>() {
match message_type {
"start" => Ok(MessageType::Start),
"stop" => Ok(MessageType::Stop),
"pause" => Ok(MessageType::Pause),
"resume" => Ok(MessageType::Resume),
"restart" => Ok(MessageType::Restart),
"status" => Ok(MessageType::Status),
"metrics" => Ok(MessageType::Metrics),
_ => Err(PyErr::new::<PyTypeError, _>("Invalid message type")),
}
} else {
Err(PyErr::new::<PyTypeError, _>("Invalid message type"))
}
}
}
impl IntoPy<PyObject> for MessageType {
fn into_py(self, py: Python) -> PyObject {
let string = PyString::new(py, &format!("{:?}", self));
string.into()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct MessageState {
pub message_type: MessageType,
pub timestamp: f64,
pub payload: String,
}
impl<'a> FromPyObject<'a> for MessageState {
fn extract(ob: &'a PyAny) -> PyResult<Self> {
let message_type = ob.get_item("message_type")?.extract()?;
let timestamp = ob.get_item("timestamp")?.extract()?;
let payload = ob.get_item("payload")?.extract()?;
Ok(MessageState { message_type, timestamp, payload })
}
}
impl IntoPy<PyObject> for MessageState {
fn into_py(self, py: Python) -> PyObject {
let dict = PyDict::new(py);
dict.set_item("message_type", self.message_type.into_py(py)).unwrap();
dict.set_item("timestamp", self.timestamp).unwrap();
dict.set_item("payload", self.payload).unwrap();
dict.into()
}
}