Skip to main content

tf_rust_socketio/
event.rs

1use std::fmt::{Display, Formatter, Result as FmtResult};
2
3/// An `Event` in `socket.io` could either (`Message`, `Error`) or custom.
4#[derive(Debug, PartialEq, PartialOrd, Clone, Eq, Hash)]
5pub enum Event {
6    Message,
7    Error,
8    Custom(String),
9    Connect,
10    Close,
11}
12
13impl Event {
14    pub fn as_str(&self) -> &str {
15        match self {
16            Event::Message => "message",
17            Event::Error => "error",
18            Event::Connect => "connect",
19            Event::Close => "close",
20            Event::Custom(string) => string,
21        }
22    }
23}
24
25impl From<String> for Event {
26    fn from(string: String) -> Self {
27        match &string.to_lowercase()[..] {
28            "message" => Event::Message,
29            "error" => Event::Error,
30            "open" => Event::Connect,
31            "close" => Event::Close,
32            _ => Event::Custom(string),
33        }
34    }
35}
36
37impl From<&str> for Event {
38    fn from(string: &str) -> Self {
39        Event::from(String::from(string))
40    }
41}
42
43impl From<Event> for String {
44    fn from(event: Event) -> Self {
45        match event {
46            Event::Message => Self::from("message"),
47            Event::Connect => Self::from("open"),
48            Event::Close => Self::from("close"),
49            Event::Error => Self::from("error"),
50            Event::Custom(string) => string,
51        }
52    }
53}
54
55impl Display for Event {
56    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
57        f.write_str(self.as_str())
58    }
59}
60
61/// A `CloseReason` is the payload of the [`Event::Close`] and specifies the reason for
62/// why it was fired.
63/// These are aligned with the official Socket.IO disconnect reasons, see
64/// https://socket.io/docs/v4/client-socket-instance/#disconnect
65#[derive(Debug, PartialEq, PartialOrd, Clone, Eq, Hash)]
66pub enum CloseReason {
67    IOServerDisconnect,
68    IOClientDisconnect,
69    TransportClose,
70}
71
72impl CloseReason {
73    pub fn as_str(&self) -> &str {
74        match self {
75            // Inspired by https://github.com/socketio/socket.io/blob/d0fc72042068e7eaef448941add617f05e1ec236/packages/socket.io-client/lib/socket.ts#L865
76            CloseReason::IOServerDisconnect => "io server disconnect",
77            // Inspired by https://github.com/socketio/socket.io/blob/d0fc72042068e7eaef448941add617f05e1ec236/packages/socket.io-client/lib/socket.ts#L911
78            CloseReason::IOClientDisconnect => "io client disconnect",
79            CloseReason::TransportClose => "transport close",
80        }
81    }
82}
83
84impl From<CloseReason> for String {
85    fn from(event: CloseReason) -> Self {
86        Self::from(event.as_str())
87    }
88}
89
90impl Display for CloseReason {
91    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
92        f.write_str(self.as_str())
93    }
94}