forked from eclipse-paho/paho.mqtt.rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwill_options.rs
365 lines (313 loc) · 11.3 KB
/
will_options.rs
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// will_options.rs
// This file is part of the Eclipse Paho MQTT Rust Client library.
//
/*******************************************************************************
* Copyright (c) 2017-2019 Frank Pagliughi <fpagliughi@mindspring.com>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Frank Pagliughi - initial implementation and documentation
*******************************************************************************/
//! Last Will and Testament (LWT) options for the Paho MQTT Rust client library.
//!
use std::{borrow::Cow, os::raw::c_void, pin::Pin, ptr};
use crate::{
ffi,
message::{Message, MessageData},
properties::Properties,
};
/// The options for the Last Will and Testament (LWT).
/// This defines a message that is registered with the the server at the time
/// of connection. Then if the connection is lost unexpectedly, the message
/// is published by the server.
///
/// The will options are somewhat redundant in that they simply represent a
/// message, albeit a special one, that is included in the connect options.
/// This structure may eventually be phased out, and therefore users are
/// encouraged to just create a `Message` object and use it when building
/// `ConnectOptions`:
/// ```
/// use paho_mqtt as mqtt;
///
/// let lwt = mqtt::Message::new("lwt", "disconnected", 1);
/// let opts = mqtt::ConnectOptionsBuilder::new().will_message(lwt).finalize();
/// ```
///
#[derive(Debug)]
pub struct WillOptions {
/// The underlying C options struct
pub(crate) copts: ffi::MQTTAsync_willOptions,
/// The local data cache for the C options
data: Pin<Box<MessageData>>,
/// The will properties
props: Properties,
}
impl WillOptions {
/// Creates a new WillOptions message.
///
/// # Arguments
///
/// * `topic` The topic on which the LWT message is to be published.
/// * `payload` The binary payload of the LWT message
/// * `qos` The quality of service for message delivery (0, 1, or 2)
pub fn new<S, V>(topic: S, payload: V, qos: i32) -> WillOptions
where
S: Into<String>,
V: Into<Vec<u8>>,
{
let copts = ffi::MQTTAsync_willOptions {
qos,
..ffi::MQTTAsync_willOptions::default()
};
Self::from_data(copts, MessageData::new(topic, payload))
}
/// Creates a new WillOptions message with the 'retain' flag set.
///
/// # Arguments
///
/// * `topic` The topic on which the LWT message is to be published.
/// * `payload` The binary payload of the LWT message
/// * `qos` The quality of service for message delivery (0, 1, or 2)
pub fn new_retained<S, V>(topic: S, payload: V, qos: i32) -> WillOptions
where
S: Into<String>,
V: Into<Vec<u8>>,
{
let mut opts = Self::new(topic, payload, qos);
opts.copts.retained = 1;
opts
}
// Updates the C struct from the cached topic and payload vars
fn from_data(copts: ffi::MQTTAsync_willOptions, data: MessageData) -> Self {
Self::from_pinned_data(copts, Box::pin(data))
}
// Updates the C struct from the cached topic and payload vars
fn from_pinned_data(
mut copts: ffi::MQTTAsync_willOptions,
data: Pin<Box<MessageData>>,
) -> Self {
copts.topicName = if !data.topic.as_bytes().is_empty() {
data.topic.as_ptr()
}
else {
ptr::null()
};
copts.payload.len = data.payload.len() as i32;
copts.payload.data = if copts.payload.len != 0 {
data.payload.as_ptr() as *const c_void
}
else {
ptr::null()
};
// Note: For some reason, properties aren't in the will options
// They're in the connect options
Self {
copts,
data,
props: Properties::default(),
}
}
/// Gets the topic string for the LWT
pub fn topic(&self) -> &str {
self.data.topic.to_str().unwrap()
}
/// Gets the payload of the LWT
pub fn payload(&self) -> &[u8] {
&self.data.payload
}
/// Gets the payload of the message as a string.
/// Note that this clones the payload.
pub fn payload_str(&self) -> Cow<'_, str> {
String::from_utf8_lossy(&self.data.payload)
}
/// Returns the Quality of Service (QOS) for the message.
pub fn qos(&self) -> i32 {
self.copts.qos
}
/// Gets the 'retained' flag for the message.
pub fn retained(&self) -> bool {
self.copts.retained != 0
}
/// Gets the properties for the will message.
pub fn properties(&self) -> &Properties {
&self.props
}
}
impl Default for WillOptions {
/// Creates a WillOptions struct with default options
fn default() -> Self {
Self::from_data(
ffi::MQTTAsync_willOptions::default(),
MessageData::default(),
)
}
}
impl Clone for WillOptions {
/// Creates a clone of the WillOptions struct.
/// This clones the cached values and updates the C struct to refer
/// to them.
fn clone(&self) -> Self {
Self::from_data(self.copts, (&*self.data).clone())
}
}
unsafe impl Send for WillOptions {}
unsafe impl Sync for WillOptions {}
impl From<Message> for WillOptions {
/// Create `WillOptions` from a `Message`
fn from(msg: Message) -> Self {
let copts = ffi::MQTTAsync_willOptions {
qos: msg.cmsg.qos,
retained: msg.cmsg.retained,
..ffi::MQTTAsync_willOptions::default()
};
Self::from_pinned_data(copts, msg.data)
}
}
/////////////////////////////////////////////////////////////////////////////
// Unit Tests
/////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod tests {
use super::*;
use crate::message::MessageBuilder;
use std::os::raw::c_char;
// The C struct identifier for will options and the supported struct version.
const STRUCT_ID: [c_char; 4] = [
b'M' as c_char,
b'Q' as c_char,
b'T' as c_char,
b'W' as c_char,
];
const STRUCT_VERSION: i32 = 1;
// These should differ from defaults.
const TOPIC: &str = "test";
const PAYLOAD: &[u8] = b"Hello world";
const QOS: i32 = 2;
const RETAINED: bool = true;
// By convention our defaults should match the defaults of the C library
#[test]
fn test_default() {
let opts = WillOptions::default();
// Get default C options for comparison
let copts = ffi::MQTTAsync_willOptions::default();
// First, make sure C options valid
assert_eq!(STRUCT_ID, copts.struct_id);
assert_eq!(STRUCT_VERSION, copts.struct_version);
assert_eq!(ptr::null(), copts.message);
assert_eq!(copts.struct_id, opts.copts.struct_id);
assert_eq!(copts.struct_version, opts.copts.struct_version);
assert_eq!(copts.topicName, opts.copts.topicName);
assert_eq!(copts.retained, opts.copts.retained);
assert_eq!(copts.qos, opts.copts.qos);
assert_eq!(copts.payload.len, opts.copts.payload.len);
assert_eq!(copts.payload.data, opts.copts.payload.data);
assert_eq!(&[] as &[u8], opts.data.topic.as_bytes());
assert_eq!(&[] as &[u8], opts.data.payload.as_slice());
}
#[test]
fn test_new() {
let msg = WillOptions::new(TOPIC, PAYLOAD, QOS);
assert_eq!(STRUCT_ID, msg.copts.struct_id);
assert_eq!(STRUCT_VERSION, msg.copts.struct_version);
assert_eq!(TOPIC, msg.data.topic.to_str().unwrap());
assert_eq!(PAYLOAD, msg.data.payload.as_slice());
assert_eq!(msg.data.payload.len() as i32, msg.copts.payload.len);
assert_eq!(
msg.data.payload.as_ptr() as *const c_void,
msg.copts.payload.data
);
assert_eq!(QOS, msg.copts.qos);
assert!(msg.copts.retained == 0);
}
#[test]
fn test_new_retained() {
let msg = WillOptions::new_retained(TOPIC, PAYLOAD, QOS);
assert_eq!(STRUCT_ID, msg.copts.struct_id);
assert_eq!(STRUCT_VERSION, msg.copts.struct_version);
assert_eq!(TOPIC, msg.data.topic.to_str().unwrap());
assert_eq!(PAYLOAD, msg.data.payload.as_slice());
assert_eq!(msg.data.payload.len() as i32, msg.copts.payload.len);
assert_eq!(
msg.data.payload.as_ptr() as *const c_void,
msg.copts.payload.data
);
assert_eq!(QOS, msg.copts.qos);
assert!(msg.copts.retained != 0);
}
// Test creating will options from a message
#[test]
fn test_from_message() {
let msg = MessageBuilder::new()
.topic(TOPIC)
.payload(PAYLOAD)
.qos(QOS)
.retained(RETAINED)
.finalize();
let opts = WillOptions::from(msg);
assert_eq!(TOPIC, opts.data.topic.to_str().unwrap());
assert_eq!(PAYLOAD, opts.data.payload.as_slice());
assert_eq!(opts.data.payload.len() as i32, opts.copts.payload.len);
assert_eq!(
opts.data.payload.as_ptr() as *const c_void,
opts.copts.payload.data
);
assert_eq!(QOS, opts.copts.qos);
assert!(opts.copts.retained != 0);
}
// Make sure assignment works properly
// This primarily ensures that C pointers stay fixed to cached values,
// and/or that the cached buffers don't move due to assignment.
#[test]
fn test_assign() {
let msg = MessageBuilder::new()
.topic(TOPIC)
.payload(PAYLOAD)
.qos(QOS)
.retained(RETAINED)
.finalize();
let org_opts = WillOptions::from(msg);
let opts = org_opts;
assert_eq!(TOPIC, opts.data.topic.to_str().unwrap());
assert_eq!(PAYLOAD, opts.data.payload.as_slice());
assert_eq!(opts.data.payload.len() as i32, opts.copts.payload.len);
assert_eq!(
opts.data.payload.as_ptr() as *const c_void,
opts.copts.payload.data
);
assert_eq!(QOS, opts.copts.qos);
assert!(opts.copts.retained != 0);
}
// Test that a clone works properly.
// This ensures that the cached values are cloned and that the C pointers
// in the new object point to those clones.
#[test]
fn test_clone() {
let opts = {
let msg = MessageBuilder::new()
.topic(TOPIC)
.payload(PAYLOAD)
.qos(QOS)
.retained(RETAINED)
.finalize();
let org_opts = WillOptions::from(msg);
org_opts.clone()
};
assert_eq!(TOPIC, opts.data.topic.to_str().unwrap());
assert_eq!(PAYLOAD, opts.data.payload.as_slice());
assert_eq!(opts.data.payload.len() as i32, opts.copts.payload.len);
assert_eq!(
opts.data.payload.as_ptr() as *const c_void,
opts.copts.payload.data
);
assert_eq!(QOS, opts.copts.qos);
assert!(opts.copts.retained != 0);
}
}