kumoko/
event.rs

1//! Definitions for Connection Events
2
3use std::{sync::Arc, io};
4use bincode::error::DecodeError;
5use crate::Message;
6
7/// Describes which client an `Event` originated from. `.into()`
8/// can be used to transform into a `Target` to reply to.
9#[derive(Debug, Clone, Copy)]
10pub enum Origin{
11    /// The Id of the Client.
12    Id(usize),
13    /// A Client can ignore this entirely.
14    OnClient,
15}
16
17/// The Connection did something!
18#[derive(Debug, Clone)]
19pub enum Event<Msg: Message>{
20    /// It connected!
21    Connect,
22    /// It sent a Message!
23    Message(Msg),
24    /// It sent Illegal data!
25    IllegalData(Illegal),
26    /// It disconnected!
27    Disconnect(DisconnectEvent),
28    /// An Error which didnt break the connection occured.
29    RealError(Arc<io::Error>),
30}
31
32/// The connection was broken by:
33#[derive(Debug, Clone, Eq, PartialEq)]
34pub enum DisconnectEvent{
35    /// a call to close it.
36    Clean,
37    /// an error.
38    Dirty,
39}
40
41/// The sent Message couldnt be decoded. Includes the raw bytes and the `DecodeError`.
42#[derive(Debug, Clone)]
43pub struct Illegal{
44    pub err: Arc<DecodeError>,
45    pub vec: Vec<u8>,
46}
47
48impl<Msg: Message> Event<Msg> {
49    pub(crate) fn clean() -> Self{
50        Self::Disconnect(DisconnectEvent::Clean)
51    }
52
53    pub(crate) fn dirty() -> Self{
54        Self::Disconnect(DisconnectEvent::Dirty)
55    }
56
57    pub(crate) fn from_err(err: io::Error) -> Self{
58        Self::RealError(Arc::new(err))
59    }
60}
61
62impl<Msg: Message> From<Msg> for Event<Msg> {
63    fn from(msg: Msg) -> Self {
64        Self::Message(msg)
65    }
66}
67
68impl<Msg: Message> From<Illegal> for Event<Msg> {
69    fn from(i: Illegal) -> Self {
70        Self::IllegalData(i)
71    }
72}
73
74impl From<(Vec<u8>, bincode::error::DecodeError)> for Illegal {
75    fn from((vec, err): (Vec<u8>, bincode::error::DecodeError)) -> Self {
76        Self{ vec, err: Arc::new(err) }
77    }
78}
79
80impl<U: Into<usize>> From<U> for Origin{
81    fn from(id: U) -> Self {
82        Self::Id(id.into())
83    }
84}