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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
use core::fmt::{self, Debug, Display, Formatter};
use core::marker::PhantomData;

extern crate alloc;
use alloc::borrow::Cow;

use serde::{Deserialize, Serialize};

use crate::errors::Errors;

/// Quality of service
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Serialize, Deserialize)]
pub enum QoS {
    AtMostOnce = 0,
    AtLeastOnce = 1,
    ExactlyOnce = 2,
}

pub type MessageId = u32;

#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum Event<M> {
    BeforeConnect,
    Connected(bool),
    Disconnected,
    Subscribed(MessageId),
    Unsubscribed(MessageId),
    Published(MessageId),
    Received(M),
    Deleted(MessageId),
}

impl<M> Display for Event<M>
where
    M: Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::BeforeConnect => write!(f, "BeforeConnect"),
            Self::Connected(connected) => write!(f, "Connected(session: {})", connected),
            Self::Disconnected => write!(f, "Disconnected"),
            Self::Subscribed(message_id) => write!(f, "Subscribed({})", message_id),
            Self::Unsubscribed(message_id) => write!(f, "Unsubscribed({})", message_id),
            Self::Published(message_id) => write!(f, "Published({})", message_id),
            Self::Received(message) => write!(f, "Received({})", message),
            Self::Deleted(message_id) => write!(f, "Deleted({})", message_id),
        }
    }
}

pub trait Message {
    fn id(&self) -> MessageId;

    fn topic(&self, topic_token: &TopicToken) -> Cow<'_, str>;

    fn data(&self) -> Cow<'_, [u8]>;

    fn details(&self) -> &Details;

    fn retrieve_topic(&self) -> Option<Cow<'_, str>> {
        let topic_token = match self.details() {
            Details::Complete(topic_token) => Some(topic_token),
            Details::InitialChunk(chunk) => Some(&chunk.topic_token),
            _ => None,
        };

        topic_token.map(|topic_token| self.topic(topic_token))
    }
}

#[derive(Debug)]
pub enum Details {
    Complete(TopicToken),
    InitialChunk(InitialChunkData),
    SubsequentChunk(SubsequentChunkData),
}

#[derive(Debug)]
pub struct InitialChunkData {
    pub topic_token: TopicToken,
    pub total_data_size: usize,
}

#[derive(Debug)]
pub struct SubsequentChunkData {
    pub current_data_offset: usize,
    pub total_data_size: usize,
}

#[derive(Debug)]
pub struct TopicToken(PhantomData<*const ()>);

impl TopicToken {
    /// # Safety
    /// This function is marked as unsafe because it is an internal API and is NOT supposed to be called by the user
    pub unsafe fn new() -> Self {
        Self(PhantomData)
    }
}

pub trait Client: Errors {
    fn subscribe<'a, S>(&'a mut self, topic: S, qos: QoS) -> Result<MessageId, Self::Error>
    where
        S: Into<Cow<'a, str>>;

    fn unsubscribe<'a, S>(&'a mut self, topic: S) -> Result<MessageId, Self::Error>
    where
        S: Into<Cow<'a, str>>;
}

impl<'b, C> Client for &'b mut C
where
    C: Client,
{
    fn subscribe<'a, S>(&'a mut self, topic: S, qos: QoS) -> Result<MessageId, Self::Error>
    where
        S: Into<Cow<'a, str>>,
    {
        (*self).subscribe(topic, qos)
    }

    fn unsubscribe<'a, S>(&'a mut self, topic: S) -> Result<MessageId, Self::Error>
    where
        S: Into<Cow<'a, str>>,
    {
        (*self).unsubscribe(topic)
    }
}

pub trait Publish: Errors {
    fn publish<'a, S, V>(
        &'a mut self,
        topic: S,
        qos: QoS,
        retain: bool,
        payload: V,
    ) -> Result<MessageId, Self::Error>
    where
        S: Into<Cow<'a, str>>,
        V: Into<Cow<'a, [u8]>>;
}

impl<'b, P> Publish for &'b mut P
where
    P: Publish,
{
    fn publish<'a, S, V>(
        &'a mut self,
        topic: S,
        qos: QoS,
        retain: bool,
        payload: V,
    ) -> Result<MessageId, Self::Error>
    where
        S: Into<Cow<'a, str>>,
        V: Into<Cow<'a, [u8]>>,
    {
        (*self).publish(topic, qos, retain, payload)
    }
}

pub trait Enqueue: Errors {
    fn enqueue<'a, S, V>(
        &'a mut self,
        topic: S,
        qos: QoS,
        retain: bool,
        payload: V,
    ) -> Result<MessageId, Self::Error>
    where
        S: Into<Cow<'a, str>>,
        V: Into<Cow<'a, [u8]>>;
}

impl<'b, E> Enqueue for &'b mut E
where
    E: Enqueue,
{
    fn enqueue<'a, S, V>(
        &'a mut self,
        topic: S,
        qos: QoS,
        retain: bool,
        payload: V,
    ) -> Result<MessageId, Self::Error>
    where
        S: Into<Cow<'a, str>>,
        V: Into<Cow<'a, [u8]>>,
    {
        (*self).enqueue(topic, qos, retain, payload)
    }
}

pub trait Connection: Errors {
    type Message<'a>: Message
    where
        Self: 'a;

    /// GATs do not (yet) define a standard streaming iterator,
    /// so we have to put the next() method directly in the Connection trait
    fn next(&mut self) -> Option<Result<Event<Self::Message<'_>>, Self::Error>>;
}

impl<'b, C> Connection for &'b mut C
where
    C: Connection,
{
    type Message<'a>
    where
        Self: 'a,
    = C::Message<'a>;

    fn next(&mut self) -> Option<Result<Event<Self::Message<'_>>, Self::Error>> {
        (*self).next()
    }
}

#[cfg(feature = "experimental")]
pub mod nonblocking {
    use core::future::Future;

    extern crate alloc;
    use alloc::borrow::Cow;

    pub use super::{Details, Event, Message, MessageId, QoS};

    use crate::errors::Errors;

    pub trait Client: Errors {
        type SubscribeFuture<'a>: Future<Output = Result<MessageId, Self::Error>>
        where
            Self: 'a;
        type UnsubscribeFuture<'a>: Future<Output = Result<MessageId, Self::Error>>
        where
            Self: 'a;

        fn subscribe<'a, S>(&'a mut self, topic: S, qos: QoS) -> Self::SubscribeFuture<'a>
        where
            S: Into<Cow<'a, str>>;

        fn unsubscribe<'a, S>(&'a mut self, topic: S) -> Self::UnsubscribeFuture<'a>
        where
            S: Into<Cow<'a, str>>;
    }

    pub trait Publish: Errors {
        type PublishFuture<'a>: Future<Output = Result<MessageId, Self::Error>>
        where
            Self: 'a;

        fn publish<'a, S, V>(
            &'a mut self,
            topic: S,
            qos: QoS,
            retain: bool,
            payload: V,
        ) -> Self::PublishFuture<'a>
        where
            S: Into<Cow<'a, str>>,
            V: Into<Cow<'a, [u8]>>;
    }

    /// core.stream.Stream is not stable yet and on top of that it has an Item which is not
    /// parameterizable by lifetime (GATs). Therefore, we have to use a Future instead
    pub trait Connection: Errors {
        type Message<'a>: Message
        where
            Self: 'a;

        type NextFuture<'a, FM, OM, FE, OE>: Future<Output = Option<Result<Event<OM>, OE>>>
        where
            Self: 'a,
            FM: FnMut(&'a Self::Message<'a>) -> OM + Unpin,
            FE: FnMut(&'a Self::Error) -> OE + Unpin;

        fn next<'a, FM, OM, FE, OE>(
            &'a mut self,
            fm: FM,
            fe: FE,
        ) -> Self::NextFuture<'a, FM, OM, FE, OE>
        where
            FM: FnMut(&'a Self::Message<'a>) -> OM + Unpin,
            FE: FnMut(&'a Self::Error) -> OE + Unpin;
    }
}