use std::convert::Infallible;
use std::sync::Arc;
use crate::handler::{FromConnectParts, FromMessageParts};
use crate::{adapter::Adapter, socket::Socket};
use serde::de::DeserializeOwned;
use socketioxide_core::Value;
use socketioxide_core::parser::{Parse, ParserError};
pub struct Data<T>(pub T);
impl<T, A> FromConnectParts<A> for Data<T>
where
T: DeserializeOwned,
A: Adapter,
{
type Error = ParserError;
fn from_connect_parts(s: &Arc<Socket<A>>, auth: &Option<Value>) -> Result<Self, Self::Error> {
s.parser.decode_default(auth.as_ref()).map(Data)
}
}
impl<T, A> FromMessageParts<A> for Data<T>
where
T: DeserializeOwned,
A: Adapter,
{
type Error = ParserError;
fn from_message_parts(
s: &Arc<Socket<A>>,
v: &mut Value,
_: &Option<i64>,
) -> Result<Self, Self::Error> {
s.parser.decode_value(v, true).map(Data)
}
}
pub struct TryData<T>(pub Result<T, ParserError>);
impl<T, A> FromConnectParts<A> for TryData<T>
where
T: DeserializeOwned,
A: Adapter,
{
type Error = Infallible;
fn from_connect_parts(s: &Arc<Socket<A>>, auth: &Option<Value>) -> Result<Self, Infallible> {
Ok(TryData(s.parser.decode_default(auth.as_ref())))
}
}
impl<T, A> FromMessageParts<A> for TryData<T>
where
T: DeserializeOwned,
A: Adapter,
{
type Error = Infallible;
fn from_message_parts(
s: &Arc<Socket<A>>,
v: &mut Value,
_: &Option<i64>,
) -> Result<Self, Infallible> {
Ok(TryData(s.parser.decode_value(v, true)))
}
}
pub struct Event(pub String);
impl<A> FromMessageParts<A> for Event
where
A: Adapter,
{
type Error = ParserError;
fn from_message_parts(
s: &Arc<Socket<A>>,
v: &mut Value,
_: &Option<i64>,
) -> Result<Self, ParserError> {
Ok(Event(s.parser.read_event(v)?.to_string()))
}
}
super::__impl_deref!(TryData<T>: Result<T, ParserError>);
super::__impl_deref!(Data);
super::__impl_deref!(Event: str);