forked from eclipse-paho/paho.mqtt.rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproperties.rs
1626 lines (1409 loc) · 53.9 KB
/
properties.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// properties.rs
//
// The set of properties in an MQTT v5 packet.
//
// This file is part of the Eclipse Paho MQTT Rust Client library.
//
/*******************************************************************************
* Copyright (c) 2019-2020 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
*******************************************************************************/
//! MQTT v5 properties.
use std::{
any::{Any, TypeId},
ffi::CString,
mem,
os::raw::{c_char, c_int},
ptr,
};
use crate::{errors::Result, ffi};
/// Error code for property mismatches
const INVALID_PROPERTY_ID: i32 = ffi::MQTT_INVALID_PROPERTY_ID;
/// The type for properties that take binary data.
pub type Binary = Vec<u8>;
/// The Property `value` union type.
pub type Value = ffi::MQTTProperty__bindgen_ty_1;
/// The struct to encapsulate property string values.
type LenString = ffi::MQTTLenString;
#[repr(u32)]
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum PropertyType {
Byte = 0,
TwoByteInteger = 1,
FourByteInteger = 2,
VariableByteInteger = 3,
BinaryData = 4,
Utf8EncodedString = 5,
Utf8StringPair = 6,
}
// Local alias for the C property type
type Type = ffi::MQTTPropertyTypes;
impl PropertyType {
/// Tries to create a property type from a C integer value
pub fn new(typ: ffi::MQTTPropertyTypes) -> Option<Self> {
match typ {
0 => Some(Self::Byte),
1 => Some(Self::TwoByteInteger),
2 => Some(Self::FourByteInteger),
3 => Some(Self::VariableByteInteger),
4 => Some(Self::BinaryData),
5 => Some(Self::Utf8EncodedString),
6 => Some(Self::Utf8StringPair),
_ => None,
}
}
/// Gets the any::TypeId that corresponds to the property type.
pub fn type_of(&self) -> TypeId {
match *self {
Self::Byte => TypeId::of::<u8>(),
Self::TwoByteInteger => TypeId::of::<u16>(),
Self::FourByteInteger => TypeId::of::<u32>(),
Self::VariableByteInteger => TypeId::of::<i32>(),
Self::BinaryData => TypeId::of::<Binary>(),
Self::Utf8EncodedString => TypeId::of::<String>(),
Self::Utf8StringPair => TypeId::of::<(String, String)>(),
}
}
}
/// The enumerated codes for the MQTT v5 properties.
///
/// The property code defines both the meaning of the value in the property
/// (Correlation Data, Server Keep Alive) and the data type held by the
/// property.
#[repr(u32)]
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum PropertyCode {
PayloadFormatIndicator = 1,
MessageExpiryInterval = 2,
ContentType = 3,
ResponseTopic = 8,
CorrelationData = 9,
SubscriptionIdentifier = 11,
SessionExpiryInterval = 17,
AssignedClientIdentifer = 18,
ServerKeepAlive = 19,
AuthenticationMethod = 21,
AuthenticationData = 22,
RequestProblemInformation = 23,
WillDelayInterval = 24,
RequestResponseInformation = 25,
ResponseInformation = 26,
ServerReference = 28,
ReasonString = 31,
ReceiveMaximum = 33,
TopicAliasMaximum = 34,
TopicAlias = 35,
MaximumQos = 36,
RetainAvailable = 37,
UserProperty = 38,
MaximumPacketSize = 39,
WildcardSubscriptionAvailable = 40,
SubscriptionIdentifiersAvailable = 41,
SharedSubscriptionAvailable = 42,
}
// Local alias for the C property code integer type
type Code = ffi::MQTTPropertyCodes;
impl PropertyCode {
pub fn new(code: ffi::MQTTPropertyCodes) -> Option<Self> {
match code {
1 => Some(Self::PayloadFormatIndicator),
2 => Some(Self::MessageExpiryInterval),
3 => Some(Self::ContentType),
8 => Some(Self::ResponseTopic),
9 => Some(Self::CorrelationData),
11 => Some(Self::SubscriptionIdentifier),
17 => Some(Self::SessionExpiryInterval),
18 => Some(Self::AssignedClientIdentifer),
19 => Some(Self::ServerKeepAlive),
21 => Some(Self::AuthenticationMethod),
22 => Some(Self::AuthenticationData),
23 => Some(Self::RequestProblemInformation),
24 => Some(Self::WillDelayInterval),
25 => Some(Self::RequestResponseInformation),
26 => Some(Self::ResponseInformation),
28 => Some(Self::ServerReference),
31 => Some(Self::ReasonString),
33 => Some(Self::ReceiveMaximum),
34 => Some(Self::TopicAliasMaximum),
35 => Some(Self::TopicAlias),
36 => Some(Self::MaximumQos),
37 => Some(Self::RetainAvailable),
38 => Some(Self::UserProperty),
39 => Some(Self::MaximumPacketSize),
40 => Some(Self::WildcardSubscriptionAvailable),
41 => Some(Self::SubscriptionIdentifiersAvailable),
42 => Some(Self::SharedSubscriptionAvailable),
_ => None,
}
}
/// Get the property type from the code identifier.
pub fn property_type(&self) -> PropertyType {
let typ = unsafe { ffi::MQTTProperty_getType(*self as Code) as Type };
PropertyType::new(typ).unwrap()
}
/// Gets the any::TypeId that corresponds to the property type.
pub fn type_of(&self) -> TypeId {
self.property_type().type_of()
}
}
/////////////////////////////////////////////////////////////////////////////
/// A single MQTT v5 property.
///
/// An MQTT v5 property consists of both a property "code" and a value. The
/// code indicates what the property contains (Response Topic, Will Delay
/// Interval, etc), and also the data type for the value. Each copde
/// corresponds to a single, specific data type as described in the v5
/// spec, here:
/// https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901027
///
/// There are only a limited number of data types that are possible for
/// properties:
/// "Byte" - u8
/// "Two Byte Integer" - u16
/// "Four Byte Integer" - u32
/// "Binary Data" - Vec<u8>
/// "UTF-8 Encoded String" - String
/// "UTF-8 String Pair" - (String,String)
///
#[derive(Debug)]
pub struct Property {
pub(crate) cprop: ffi::MQTTProperty,
}
impl Property {
/// Creates a new property for a given code and value.
///
/// The type for the value must match the type expected for the given
/// property code exactly, otherwise it will be rejected and return None.
pub fn new<T>(code: PropertyCode, val: T) -> Result<Property>
where
T: Any + 'static,
{
let rval: &(dyn Any + 'static) = &val;
// Try some manual mappings first
if code.type_of() == TypeId::of::<Binary>() {
// A binary type can accept strings
if let Some(v) = rval.downcast_ref::<&str>() {
return Self::new_binary(code, v.as_bytes());
}
else if let Some(v) = rval.downcast_ref::<String>() {
return Self::new_binary(code, v.as_bytes());
}
}
// Note that we could potentially insist that the types must
// match exactly, but this seems too restrictive:
//
// if code.type_of() != TypeId::of::<T>() {
// return Err(INVALID_PROPERTY_ID.into());
// }
if let Some(v) = rval.downcast_ref::<u8>() {
Self::new_byte(code, *v)
}
else if let Some(v) = rval.downcast_ref::<u16>() {
Self::new_u16(code, *v)
}
else if let Some(v) = rval.downcast_ref::<i16>() {
Self::new_u16(code, *v as u16)
}
else if let Some(v) = rval.downcast_ref::<u32>() {
Self::new_u32(code, *v)
}
else if let Some(v) = rval.downcast_ref::<i32>() {
Self::new_int(code, *v)
}
else if let Some(v) = rval.downcast_ref::<Binary>() {
Self::new_binary(code, v.clone())
}
else if let Some(v) = rval.downcast_ref::<&[u8]>() {
Self::new_binary(code, *v)
}
else if let Some(v) = rval.downcast_ref::<&[u8; 1]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 2]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 3]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 4]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 5]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 6]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 7]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 8]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 9]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 10]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 11]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 12]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 13]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 14]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 15]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 16]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 17]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 18]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 19]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 20]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 21]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 22]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 23]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 24]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 25]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 26]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 27]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 28]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 29]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 30]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 31]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<&[u8; 32]>() {
Self::new_binary(code, v.to_vec())
}
else if let Some(v) = rval.downcast_ref::<String>() {
Self::new_string(code, &*v)
}
else if let Some(v) = rval.downcast_ref::<&str>() {
Self::new_string(code, v)
}
else if let Some(v) = rval.downcast_ref::<(String, String)>() {
Self::new_string_pair(code, &v.0, &v.1)
}
else if let Some(v) = rval.downcast_ref::<(&str, &str)>() {
Self::new_string_pair(code, v.0, v.1)
}
else if let Some(v) = rval.downcast_ref::<(&str, String)>() {
Self::new_string_pair(code, v.0, &v.1)
}
else if let Some(v) = rval.downcast_ref::<(String, &str)>() {
Self::new_string_pair(code, &v.0, v.1)
}
else {
Err(INVALID_PROPERTY_ID.into())
}
}
/// Creates a single-byte property
pub fn new_byte(code: PropertyCode, val: u8) -> Result<Property> {
match code.property_type() {
PropertyType::Byte => Self::new_int(code, val as i32),
_ => Err(INVALID_PROPERTY_ID.into()),
}
}
/// Creates a 2-byte integer property
pub fn new_u16(code: PropertyCode, val: u16) -> Result<Property> {
match code.property_type() {
PropertyType::TwoByteInteger => Self::new_int(code, val as i32),
_ => Err(INVALID_PROPERTY_ID.into()),
}
}
/// Creates a 4-byte integer property
pub fn new_u32(code: PropertyCode, val: u32) -> Result<Property> {
match code.property_type() {
PropertyType::FourByteInteger => Self::new_int(code, val as i32),
_ => Err(INVALID_PROPERTY_ID.into()),
}
}
/// Creates a new integer property.
///
/// This works for any sized integer type, from byte on up.
pub fn new_int(code: PropertyCode, val: i32) -> Result<Property> {
let value = match code.property_type() {
PropertyType::Byte => {
if val & !0xFF != 0 {
bail!(INVALID_PROPERTY_ID);
}
Value { byte: val as u8 }
}
PropertyType::TwoByteInteger => {
if val & !0xFFFF != 0 {
return Err(INVALID_PROPERTY_ID.into());
}
Value {
integer2: val as u16,
}
}
PropertyType::FourByteInteger | PropertyType::VariableByteInteger => Value {
integer4: val as u32,
},
_ => return Err(INVALID_PROPERTY_ID.into()),
};
Ok(Property {
cprop: ffi::MQTTProperty {
identifier: code as Code,
value,
},
})
}
/// Creates a new binary property.
pub fn new_binary<V>(code: PropertyCode, bin: V) -> Result<Property>
where
V: Into<Binary>,
{
if code.property_type() != PropertyType::BinaryData {
return Err(INVALID_PROPERTY_ID.into());
}
let mut v = bin.into();
v.shrink_to_fit();
let n = v.len();
let p = v.as_mut_ptr() as *mut c_char;
mem::forget(v);
Ok(Property::new_string_binary(code, p, n, ptr::null_mut(), 0))
}
/// Creates a new string property.
pub fn new_string(code: PropertyCode, s: &str) -> Result<Property> {
if code.property_type() != PropertyType::Utf8EncodedString {
return Err(INVALID_PROPERTY_ID.into());
}
let n = s.len();
let p = CString::new(s).unwrap().into_raw();
Ok(Property::new_string_binary(code, p, n, ptr::null_mut(), 0))
}
/// Creates a new string pair property.
pub fn new_string_pair(code: PropertyCode, key: &str, val: &str) -> Result<Property> {
if code.property_type() != PropertyType::Utf8StringPair {
return Err(INVALID_PROPERTY_ID.into());
}
let nkey = key.len();
let pkey = CString::new(key).unwrap().into_raw();
let nval = val.len();
let pval = CString::new(val).unwrap().into_raw();
Ok(Property::new_string_binary(code, pkey, nkey, pval, nval))
}
/// Creates a property from a C lib MQTTProperty struct.
fn from_c_property(cprop: &ffi::MQTTProperty) -> Result<Property> {
let mut cprop = *cprop;
let typ = match PropertyCode::new(cprop.identifier).map(|c| c.property_type()) {
Some(typ) => typ,
None => return Err(INVALID_PROPERTY_ID.into()),
};
unsafe {
let mut pdata = cprop.value.__bindgen_anon_1.data.data;
let n = cprop.value.__bindgen_anon_1.data.len as usize;
match typ {
PropertyType::BinaryData => {
if pdata.is_null() {
return Err(INVALID_PROPERTY_ID.into());
}
let v = Vec::from_raw_parts(pdata, n, n);
let mut vc = v.clone();
pdata = vc.as_mut_ptr() as *mut c_char;
mem::forget(v);
mem::forget(vc);
}
PropertyType::Utf8EncodedString => {
if pdata.is_null() {
return Err(INVALID_PROPERTY_ID.into());
}
let v = Vec::from_raw_parts(pdata as *mut u8, n, n);
let sr = CString::new(v.clone());
if sr.is_err() {
return Err(INVALID_PROPERTY_ID.into());
}
pdata = sr.unwrap().into_raw();
mem::forget(v);
}
PropertyType::Utf8StringPair => {
let pvalue = cprop.value.__bindgen_anon_1.value.data;
if pdata.is_null() || pvalue.is_null() {
return Err(INVALID_PROPERTY_ID.into());
}
let v = Vec::from_raw_parts(pdata as *mut u8, n, n);
let sr = CString::new(v.clone());
if sr.is_err() {
return Err(INVALID_PROPERTY_ID.into());
}
pdata = sr.unwrap().into_raw();
mem::forget(v);
let n = cprop.value.__bindgen_anon_1.value.len as usize;
let v = Vec::from_raw_parts(pvalue as *mut u8, n, n);
let sr = CString::new(v.clone());
if sr.is_err() {
return Err(INVALID_PROPERTY_ID.into());
}
cprop.value.__bindgen_anon_1.value.data = sr.unwrap().into_raw();
mem::forget(v);
}
_ => (),
}
// Lengths are the same as the originals
cprop.value.__bindgen_anon_1.data.data = pdata;
}
Ok(Property { cprop })
}
/// Creates a new string, string pair, or binary property given the raw
/// pointers and sizes.
/// This is a low-level, internal call to create a preperty that contains
/// dynamic data. It does no error checking; it simply assembles the
/// struct.
fn new_string_binary(
code: PropertyCode,
pdata: *mut c_char,
ndata: usize,
pval: *mut c_char,
nval: usize,
) -> Property {
Property {
cprop: ffi::MQTTProperty {
identifier: code as Code,
value: Value {
__bindgen_anon_1: ffi::MQTTProperty__bindgen_ty_1__bindgen_ty_1 {
data: LenString {
len: ndata as c_int,
data: pdata,
},
value: LenString {
len: nval as c_int,
data: pval,
},
},
},
},
}
}
/// Gets the MQTT code for the property.
pub fn property_code(&self) -> PropertyCode {
PropertyCode::new(self.cprop.identifier).unwrap()
}
/// Gets the type of this property.
pub fn property_type(&self) -> PropertyType {
self.property_code().property_type()
}
/// Gets the any::TypeId of this property.
pub fn type_of(&self) -> TypeId {
self.property_type().type_of()
}
/// Gets the property value
pub fn get<T>(&self) -> Option<T>
where
T: Any + 'static + Send + Default,
{
let mut v = T::default();
let x: &mut dyn Any = &mut v;
if let Some(val) = x.downcast_mut::<u8>() {
if let Some(n) = self.get_byte() {
*val = n;
return Some(v);
}
}
else if let Some(val) = x.downcast_mut::<u16>() {
if let Some(n) = self.get_u16() {
*val = n;
return Some(v);
}
}
else if let Some(val) = x.downcast_mut::<u32>() {
if let Some(n) = self.get_u32() {
*val = n;
return Some(v);
}
}
else if let Some(val) = x.downcast_mut::<i32>() {
if let Some(n) = self.get_int() {
*val = n;
return Some(v);
}
}
else if let Some(val) = x.downcast_mut::<Binary>() {
if let Some(n) = self.get_binary() {
*val = n;
return Some(v);
}
}
else if let Some(val) = x.downcast_mut::<String>() {
if let Some(n) = self.get_string() {
*val = n;
return Some(v);
}
}
else if let Some(val) = x.downcast_mut::<(String, String)>() {
if let Some(n) = self.get_string_pair() {
*val = n;
return Some(v);
}
}
None
}
/// Gets the property value as a byte.
pub fn get_byte(&self) -> Option<u8> {
match self.property_type() {
PropertyType::Byte => Some(unsafe { self.cprop.value.byte }),
_ => None,
}
}
/// Gets the property value as a u16.
pub fn get_u16(&self) -> Option<u16> {
match self.property_type() {
PropertyType::TwoByteInteger => Some(unsafe { self.cprop.value.integer2 }),
_ => None,
}
}
/// Gets the property value as a u16.
pub fn get_u32(&self) -> Option<u32> {
match self.property_type() {
PropertyType::FourByteInteger => Some(unsafe { self.cprop.value.integer4 }),
_ => None,
}
}
/// Gets the property value as an integer.
/// This extracts an integer value from the property. It works with any
/// of the int types, one, two, or four bytes.
/// If the Property contains an integer type it will be returned as
/// Some(val), otherwise it will return None.
pub fn get_int(&self) -> Option<i32> {
unsafe {
match self.property_type() {
PropertyType::Byte => Some(self.cprop.value.byte as i32),
PropertyType::TwoByteInteger => Some(self.cprop.value.integer2 as i32),
PropertyType::FourByteInteger | PropertyType::VariableByteInteger => {
Some(self.cprop.value.integer4 as i32)
}
_ => None,
}
}
}
/// Gets the property value as a binary blob.
pub fn get_binary(&self) -> Option<Binary> {
unsafe {
if self.property_type() == PropertyType::BinaryData {
let n = self.cprop.value.__bindgen_anon_1.data.len as usize;
let p = self.cprop.value.__bindgen_anon_1.data.data as *mut u8;
let v = Vec::from_raw_parts(p, n, n);
let vc = v.clone();
mem::forget(v);
Some(vc)
}
else {
None
}
}
}
/// Gets the property value as a string.
pub fn get_string(&self) -> Option<String> {
unsafe {
if self.property_type() == PropertyType::Utf8EncodedString {
let s = CString::from_raw(self.cprop.value.__bindgen_anon_1.data.data);
let sc = s.clone();
s.into_raw();
sc.into_string().ok()
}
else {
None
}
}
}
/// Gets the property value as a string pair.
pub fn get_string_pair(&self) -> Option<(String, String)> {
unsafe {
if self.property_type() == PropertyType::Utf8StringPair {
let s = CString::from_raw(self.cprop.value.__bindgen_anon_1.data.data);
let sc = s.clone();
s.into_raw();
let keyopt = sc.into_string().ok();
let s = CString::from_raw(self.cprop.value.__bindgen_anon_1.value.data);
let sc = s.clone();
s.into_raw();
let valopt = sc.into_string().ok();
keyopt.and_then(|key| valopt.map(|val| (key, val)))
}
else {
None
}
}
}
}
impl Drop for Property {
/// Drops the property.
/// For string any binary types, the heap memory will be freed.
fn drop(&mut self) {
unsafe {
match self.property_type() {
PropertyType::BinaryData => {
debug!(
"Dropping binary property: {:?}",
self.cprop.value.__bindgen_anon_1.data.data
);
let n = self.cprop.value.__bindgen_anon_1.data.len as usize;
let _ = Vec::from_raw_parts(self.cprop.value.__bindgen_anon_1.data.data, n, n);
}
PropertyType::Utf8EncodedString => {
debug!(
"Dropping string property: {:?}",
self.cprop.value.__bindgen_anon_1.data.data
);
let _ = CString::from_raw(self.cprop.value.__bindgen_anon_1.data.data);
}
PropertyType::Utf8StringPair => {
debug!(
"Dropping string pair property: {:?}, {:?}",
self.cprop.value.__bindgen_anon_1.data.data,
self.cprop.value.__bindgen_anon_1.value.data
);
let _ = CString::from_raw(self.cprop.value.__bindgen_anon_1.data.data);
let _ = CString::from_raw(self.cprop.value.__bindgen_anon_1.value.data);
}
_ => (),
}
}
}
}
impl Clone for Property {
/// Creates a clone of the property.
/// For string any binary properties, this also clones the heap memory
/// so that each property is managing separate allocations.
fn clone(&self) -> Self {
let mut cprop = self.cprop;
unsafe {
match self.property_type() {
PropertyType::BinaryData => {
// TODO: Can we just do a low-level mem copy?
let n = cprop.value.__bindgen_anon_1.data.len as usize;
let v = Vec::from_raw_parts(cprop.value.__bindgen_anon_1.data.data, n, n);
let mut vc = v.clone();
let p = vc.as_mut_ptr() as *mut c_char;
cprop.value.__bindgen_anon_1.data.data = p;
mem::forget(v);
mem::forget(vc);
}
PropertyType::Utf8EncodedString => {
let s = CString::from_raw(cprop.value.__bindgen_anon_1.data.data);
let sc = s.clone();
s.into_raw();
cprop.value.__bindgen_anon_1.data.data = sc.into_raw();
}
PropertyType::Utf8StringPair => {
let s = CString::from_raw(cprop.value.__bindgen_anon_1.data.data);
let sc = s.clone();
cprop.value.__bindgen_anon_1.data.data = sc.into_raw();
s.into_raw();
let s = CString::from_raw(cprop.value.__bindgen_anon_1.value.data);
let sc = s.clone();
cprop.value.__bindgen_anon_1.value.data = sc.into_raw();
s.into_raw();
}
_ => (),
}
}
Property { cprop }
}
}
/////////////////////////////////////////////////////////////////////////////
// Properties
/// A collection of MQTT v5 properties.
///
/// This is a collection of properties that can be added to outgoing packets
/// or retrieved from incoming packets.
#[derive(Debug)]
pub struct Properties {
pub(crate) cprops: ffi::MQTTProperties,
}
impl Properties {
/// Creates a new, empty collection of properties.
pub fn new() -> Self {
Properties::default()
}
pub fn from_c_struct(cprops: &ffi::MQTTProperties) -> Self {
// This does a deep copy in the C lib
let cprops = unsafe { ffi::MQTTProperties_copy(cprops) };
Properties { cprops }
}
/// Determines if the property list has no items in it.
pub fn is_empty(&self) -> bool {
self.cprops.count == 0
}
/// Gets the number of property items in the collection.
pub fn len(&self) -> usize {
self.cprops.count as usize
}
/// Gets the number of bytes required for the serialized list on
/// the wire.
pub fn byte_len(&self) -> usize {
let p = &self.cprops as *const _ as *mut ffi::MQTTProperties;
unsafe { ffi::MQTTProperties_len(p) as usize }
}
/// Removes all the items from the property list.
pub fn clear(&mut self) {
unsafe { ffi::MQTTProperties_free(&mut self.cprops) };
self.cprops = ffi::MQTTProperties::default();
}
/// Adds a property to the colletion.
pub fn push(&mut self, prop: Property) -> Result<()> {
let rc = unsafe { ffi::MQTTProperties_add(&mut self.cprops, &prop.cprop) };
if rc == 0 {
mem::forget(prop);
Ok(())
}
else {
Err(rc.into())
}
}
/// Adds a property to the collection given the property code and value.
pub fn push_val<T>(&mut self, code: PropertyCode, val: T) -> Result<()>
where
T: Any + 'static,
{
self.push(Property::new(code, val)?)
}
/// Adds an single-byte property to the collection.
pub fn push_byte(&mut self, code: PropertyCode, val: u8) -> Result<()> {
self.push(Property::new_byte(code, val)?)
}
/// Adds an two-byte integer property to the collection.
pub fn push_u16(&mut self, code: PropertyCode, val: u16) -> Result<()> {
self.push(Property::new_u16(code, val)?)
}
/// Adds a four-byte integer property to the collection.
pub fn push_u32(&mut self, code: PropertyCode, val: u32) -> Result<()> {
self.push(Property::new_u32(code, val)?)
}
/// Adds an integer property to the collection.
///
/// This works for any integer type.
pub fn push_int(&mut self, code: PropertyCode, val: i32) -> Result<()> {
self.push(Property::new_int(code, val)?)
}
/// Adds a binary property to the collection
pub fn push_binary<V>(&mut self, code: PropertyCode, bin: V) -> Result<()>
where
V: Into<Binary>,
{
self.push(Property::new_binary(code, bin)?)
}
/// Adds a string property to the collection
pub fn push_string(&mut self, code: PropertyCode, s: &str) -> Result<()> {
self.push(Property::new_string(code, s)?)
}
/// Adds a string pair property to the collection
pub fn push_string_pair(&mut self, code: PropertyCode, key: &str, val: &str) -> Result<()> {
self.push(Property::new_string_pair(code, key, val)?)
}
/// Gets a property instance
pub fn get(&self, code: PropertyCode) -> Option<Property> {
self.get_at(code, 0)
}
/// Gets a property instance when there are possibly multiple values.
pub fn get_at(&self, code: PropertyCode, idx: usize) -> Option<Property> {
let ps = &self.cprops as *const _ as *mut ffi::MQTTProperties;
unsafe {
let p = ffi::MQTTProperties_getPropertyAt(ps, code as Code, idx as c_int);
if !p.is_null() {
Property::from_c_property(&*p).ok()
}
else {
None
}
}
}
/// Gets an iterator for a property instance
pub fn iter(&self, code: PropertyCode) -> PropertyIterator {
PropertyIterator {
props: self,
code,
idx: 0,
}
}
/// Gets a value from the collection when there may be more than one
/// for the code.
pub fn get_val_at<T>(&self, code: PropertyCode, idx: usize) -> Option<T>
where
T: Any + 'static + Send + Default,
{
self.get_at(code, idx).and_then(|prop| prop.get())
}
/// Gets a value from the collection when there may be more than one
/// for the code.
pub fn get_val<T>(&self, code: PropertyCode) -> Option<T>
where
T: Any + 'static + Send + Default,
{
self.get_val_at(code, 0)
}
/// Gets an integer value of a specific property.
pub fn get_int(&self, code: PropertyCode) -> Option<i32> {
self.get(code).and_then(|prop| prop.get_int())
}
/// Gets an integer value of a specific value when there may be more than one.
pub fn get_int_at(&self, code: PropertyCode, idx: usize) -> Option<i32> {
self.get_at(code, idx).and_then(|prop| prop.get_int())
}
/// Gets a binary value of a specific property.
pub fn get_binary(&self, code: PropertyCode) -> Option<Binary> {
self.get(code).and_then(|prop| prop.get_binary())
}
/// Gets a binary value of a specific value when there may be more than one.
pub fn get_binary_at(&self, code: PropertyCode, idx: usize) -> Option<Binary> {
self.get_at(code, idx).and_then(|prop| prop.get_binary())
}
/// Gets a string value of a specific property.
pub fn get_string(&self, code: PropertyCode) -> Option<String> {
self.get(code).and_then(|prop| prop.get_string())
}
/// Gets a binary value of a specific value when there may be more than one.
pub fn get_string_at(&self, code: PropertyCode, idx: usize) -> Option<String> {
self.get_at(code, idx).and_then(|prop| prop.get_string())
}
/// Gets a string pair for a specific property.