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
93
94
95
96
97
98
99
100
101
102
103
104
105
use crate::core;
use crate::core::futures::sync::mpsc;
use std::sync::Arc;
use crate::subscription::Session;
pub type TransportSender = mpsc::Sender<String>;
pub type TransportError = mpsc::SendError<String>;
pub type SinkResult = core::futures::sink::Send<TransportSender>;
pub trait PubSubMetadata: core::Metadata {
fn session(&self) -> Option<Arc<Session>>;
}
impl PubSubMetadata for Arc<Session> {
fn session(&self) -> Option<Arc<Session>> {
Some(self.clone())
}
}
impl<T: PubSubMetadata> PubSubMetadata for Option<T> {
fn session(&self) -> Option<Arc<Session>> {
self.as_ref().and_then(|s| s.session())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SubscriptionId {
Number(u64),
String(String),
}
impl SubscriptionId {
pub fn parse_value(val: &core::Value) -> Option<SubscriptionId> {
match *val {
core::Value::String(ref val) => Some(SubscriptionId::String(val.clone())),
core::Value::Number(ref val) => val.as_u64().map(SubscriptionId::Number),
_ => None,
}
}
}
impl From<String> for SubscriptionId {
fn from(other: String) -> Self {
SubscriptionId::String(other)
}
}
impl From<u64> for SubscriptionId {
fn from(other: u64) -> Self {
SubscriptionId::Number(other)
}
}
impl From<SubscriptionId> for core::Value {
fn from(sub: SubscriptionId) -> Self {
match sub {
SubscriptionId::Number(val) => core::Value::Number(val.into()),
SubscriptionId::String(val) => core::Value::String(val),
}
}
}
#[cfg(test)]
mod tests {
use super::SubscriptionId;
use crate::core::Value;
#[test]
fn should_convert_between_value_and_subscription_id() {
let val1 = Value::Number(5.into());
let val2 = Value::String("asdf".into());
let val3 = Value::Null;
let res1 = SubscriptionId::parse_value(&val1);
let res2 = SubscriptionId::parse_value(&val2);
let res3 = SubscriptionId::parse_value(&val3);
assert_eq!(res1, Some(SubscriptionId::Number(5)));
assert_eq!(res2, Some(SubscriptionId::String("asdf".into())));
assert_eq!(res3, None);
assert_eq!(Value::from(res1.unwrap()), val1);
assert_eq!(Value::from(res2.unwrap()), val2);
}
}