1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use std::sync::Arc;
use workflow_core::channel::*;
use super::error::Error;

#[derive(Debug,Clone,PartialEq,Eq,Hash)]
pub enum Ctl {
	/// Connection is opened
	Open,
	/// Connection is closed
	Closed,
	/// Dispatched when user invokes WebSocket::disconnect()
	Shutdown,
	/// Ctl reserved for RPC channels
	RpcCtl(u32),
	/// For use by external clients that need to send
	/// themselves a custom shutdown signal
	Custom(u32),
}

#[derive(Debug,Clone,PartialEq,Eq,Hash)]
pub enum Message {
	Text(String),
	Binary(Vec<u8>),
	Ctl(Ctl)
}

impl Message {
	pub fn is_ctl(&self) -> bool {
		match self {
			Message::Ctl(_) => true,
			_ => false
		}
	}
}

impl From<Message> for Vec<u8> {
	fn from( msg: Message ) -> Self {
		match msg {
			Message::Text(string) => string.into(),
			Message::Binary(vec) => vec,
			Message::Ctl(ctl) => {
				panic!( "WebSocket - From<Message> for Vec<u8>: unsupported 'Ctl' message type: {:?}", ctl );
			}
		}
	}
}

impl From<Vec<u8>> for Message {
	fn from(vec: Vec<u8>) -> Self {
		Message::Binary(vec)
	}
}

impl From<String> for Message {
	fn from(s: String) -> Self {
		Message::Text(s)
	}
}

impl From<&str> for Message {
	fn from(s: &str) -> Self {
		Message::Text(s.to_string())
	}
}

impl AsRef<[u8]> for Message {
	fn as_ref( &self ) -> &[u8] {
		match self {
			Message::Text(string) => string.as_ref(),
			Message::Binary(vec) => vec.as_ref(),
			Message::Ctl(ctl) => {
				panic!( "WebSocket - AsRef<[u8]> for Message: unsupported 'Ctl' message type: {:?}", ctl );
			}
		}
	}
}

#[derive(Clone)]
pub enum DispatchMessage {
	Post(Message),
	WithAck(Message, Sender<Result<Arc<()>,Arc<Error>>>),
	DispatcherShutdown,
}

impl DispatchMessage {
	pub fn is_ctl(&self) -> bool {
		match self {
			DispatchMessage::DispatcherShutdown => true,
			_ => false
		}
	}
}