mqrstt 0.1.3

Pure rust MQTTv5 client implementation for Smol, Tokio and soon sync too.
Documentation
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
use bitflags::bitflags;
use bytes::{Buf, BufMut, Bytes, BytesMut};

use super::{
    error::{DeserializeError, SerializeError},
    mqtt_traits::{MqttRead, MqttWrite, VariableHeaderRead, VariableHeaderWrite},
    read_variable_integer, variable_integer_len, write_variable_integer, PacketType, PropertyType,
    ProtocolVersion, QoS, WireLength,
};

/// Variable connect header:
///
///
/// ╔═══════════╦═══════════════════╦══════╦══════╦══════╦══════╦══════╦══════╦══════╦══════╗
/// ║           ║                   ║      ║      ║      ║      ║      ║      ║      ║      ║
/// ║           ║ Description       ║ 7    ║ 6    ║ 5    ║ 4    ║ 3    ║ 2    ║ 1    ║ 0    ║
/// ╠═══════════╩═══════════════════╩══════╩══════╩══════╩══════╩══════╩══════╩══════╩══════╣
/// ║                                                                                       ║
/// ║ Protocol Name                                                                         ║
/// ╠═══════════╦═══════════════════╦══════╦══════╦══════╦══════╦══════╦══════╦══════╦══════╣
/// ║           ║                   ║      ║      ║      ║      ║      ║      ║      ║      ║
/// ║ byte 1    ║ Length MSB (0)    ║ 0    ║ 0    ║ 0    ║ 0    ║ 0    ║ 0    ║ 0    ║ 0    ║
/// ╠═══════════╬═══════════════════╬══════╬══════╬══════╬══════╬══════╬══════╬══════╬══════╣
/// ║           ║                   ║      ║      ║      ║      ║      ║      ║      ║      ║
/// ║ byte 2    ║ Length LSB (4)    ║ 0    ║ 0    ║ 0    ║ 0    ║ 0    ║ 1    ║ 0    ║ 0    ║
/// ╠═══════════╬═══════════════════╬══════╬══════╬══════╬══════╬══════╬══════╬══════╬══════╣
/// ║           ║                   ║      ║      ║      ║      ║      ║      ║      ║      ║
/// ║ byte 3    ║ ‘M’               ║ 0    ║ 1    ║ 0    ║ 0    ║ 1    ║ 1    ║ 0    ║ 1    ║
/// ╠═══════════╬═══════════════════╬══════╬══════╬══════╬══════╬══════╬══════╬══════╬══════╣
/// ║           ║                   ║      ║      ║      ║      ║      ║      ║      ║      ║
/// ║ byte 4    ║ ‘Q’               ║ 0    ║ 1    ║ 0    ║ 1    ║ 0    ║ 0    ║ 0    ║ 1    ║
/// ╠═══════════╬═══════════════════╬══════╬══════╬══════╬══════╬══════╬══════╬══════╬══════╣
/// ║           ║                   ║      ║      ║      ║      ║      ║      ║      ║      ║
/// ║ byte 5    ║ ‘T’               ║ 0    ║ 1    ║ 0    ║ 1    ║ 0    ║ 1    ║ 0    ║ 0    ║
/// ╠═══════════╬═══════════════════╬══════╬══════╬══════╬══════╬══════╬══════╬══════╬══════╣
/// ║           ║                   ║      ║      ║      ║      ║      ║      ║      ║      ║
/// ║ byte 6    ║ ‘T’               ║ 0    ║ 1    ║ 0    ║ 1    ║ 0    ║ 1    ║ 0    ║ 0    ║
/// ╚═══════════╩═══════════════════╩══════╩══════╩══════╩══════╩══════╩══════╩══════╩══════╝
///
/// Byte 7:
/// The protocol version
///
/// Byte 8:
/// 3.1.2.3 Connect Flags :
/// ╔═════╦═══════════╦══════════╦═════════════╦═════╦════╦═══════════╦═════════════╦══════════╗
/// ║ Bit ║ 7         ║ 6        ║ 5           ║ 4   ║ 3  ║ 2         ║ 1           ║ 0        ║
/// ╠═════╬═══════════╬══════════╬═════════════╬═════╩════╬═══════════╬═════════════╬══════════╣
/// ║     ║ User Name ║ Password ║ Will Retain ║ Will QoS ║ Will Flag ║ Clean Start ║ Reserved ║
/// ╚═════╩═══════════╩══════════╩═════════════╩══════════╩═══════════╩═════════════╩══════════╝
///
/// Byte 9 and 10:
/// The keep alive
///
/// Byte 11:
/// Length of [`ConnectProperties`]
///
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Connect {
    /// Byte 7
    pub protocol_version: ProtocolVersion,

    /// 3.1.2.4 Clean Start Flag
    /// bit 1
    pub clean_session: bool,

    /// 3.1.2.5 Will Flag through option
    pub last_will: Option<LastWill>,

    /// 3.1.2.8 User Name Flag
    pub username: Option<String>,
    /// 3.1.2.9 Password Flag
    pub password: Option<String>,

    /// 3.1.2.10 Keep Alive
    /// Byte 9 and 10
    pub keep_alive: u16,

    /// 3.1.2.11 CONNECT Properties
    pub connect_properties: ConnectProperties,

    /// 3.1.3.1 Client Identifier (ClientID)
    pub client_id: String,
}

impl Default for Connect {
    fn default() -> Self {
        Self {
            protocol_version: ProtocolVersion::V5,
            clean_session: true,
            last_will: None,
            username: None,
            password: None,
            keep_alive: 60,
            connect_properties: ConnectProperties::default(),
            client_id: "MQRSTT".to_string(),
        }
    }
}

impl VariableHeaderRead for Connect {
    fn read(_: u8, _: usize, mut buf: Bytes) -> Result<Self, DeserializeError> {
        if String::read(&mut buf)? != "MQTT" {
            return Err(DeserializeError::MalformedPacketWithInfo(
                "Protocol not MQTT".to_string(),
            ));
        }

        let protocol_version = ProtocolVersion::read(&mut buf)?;

        let connect_flags_byte = buf.get_u8();
        let connect_flags = ConnectFlags::from_bits(connect_flags_byte)
            .ok_or("Can't read ConnectFlags".to_string())?;

        let clean_session = connect_flags.contains(ConnectFlags::CLEAN_START);
        let keep_alive = buf.get_u16();

        let connect_properties = ConnectProperties::read(&mut buf)?;

        let client_id = String::read(&mut buf)?;
        let mut last_will = None;
        if connect_flags.contains(ConnectFlags::WILL_FLAG) {
            let retain = connect_flags.contains(ConnectFlags::WILL_RETAIN);

            let qos = QoS::try_from(connect_flags)?;

            last_will = Some(LastWill::read(qos, retain, &mut buf)?);
        }

        let username = if connect_flags.contains(ConnectFlags::USERNAME) {
            Some(String::read(&mut buf)?)
        }
        else {
            None
        };
        let password = if connect_flags.contains(ConnectFlags::PASSWORD) {
            Some(String::read(&mut buf)?)
        }
        else {
            None
        };

        let connect = Connect {
            protocol_version,
            clean_session,
            last_will,
            username,
            password,
            keep_alive,
            connect_properties,
            client_id,
        };

        Ok(connect)
    }
}

impl VariableHeaderWrite for Connect {
    fn write(&self, buf: &mut BytesMut) -> Result<(), SerializeError> {
        "MQTT".write(buf)?;

        self.protocol_version.write(buf)?;

        let mut connect_flags = ConnectFlags::empty();

        if self.clean_session {
            connect_flags |= ConnectFlags::CLEAN_START;
        }
        if let Some(last_will) = &self.last_will {
            connect_flags |= ConnectFlags::WILL_FLAG;
            if last_will.retain {
                connect_flags |= ConnectFlags::WILL_RETAIN;
            }
            connect_flags |= last_will.qos.into();
        }
        if self.username.is_some() {
            connect_flags |= ConnectFlags::USERNAME;
        }
        if self.password.is_some() {
            connect_flags |= ConnectFlags::PASSWORD;
        }

        buf.put_u8(connect_flags.bits());

        buf.put_u16(self.keep_alive);

        self.connect_properties.write(buf)?;

        self.client_id.write(buf)?;

        if let Some(last_will) = &self.last_will {
            last_will.write(buf)?;
        }
        if let Some(username) = &self.username {
            username.write(buf)?;
        }
        if let Some(password) = &self.password {
            password.write(buf)?;
        }
        Ok(())
    }
}

impl WireLength for Connect {
    fn wire_len(&self) -> usize {
        let mut len = "MQTT".wire_len() + 1 + 1 + 2; // protocol version, connect_flags and keep alive

        len += variable_integer_len(self.connect_properties.wire_len());
        len += self.connect_properties.wire_len();

        if let Some(last_will) = &self.last_will {
            len += last_will.wire_len();
        }
        if let Some(username) = &self.username {
            len += username.wire_len()
        }
        if let Some(password) = &self.password {
            len += password.wire_len()
        }

        len += self.client_id.wire_len();

        len
    }
}

bitflags! {
    /// ╔═════╦═══════════╦══════════╦═════════════╦═════╦════╦═══════════╦═════════════╦══════════╗
    /// ║ Bit ║ 7         ║ 6        ║ 5           ║ 4   ║ 3  ║ 2         ║ 1           ║ 0        ║
    /// ╠═════╬═══════════╬══════════╬═════════════╬═════╩════╬═══════════╬═════════════╬══════════╣
    /// ║     ║ User Name ║ Password ║ Will Retain ║ Will QoS ║ Will Flag ║ Clean Start ║ Reserved ║
    /// ╚═════╩═══════════╩══════════╩═════════════╩══════════╩═══════════╩═════════════╩══════════╝
    pub struct ConnectFlags: u8 {
        const CLEAN_START   = 0b00000010;
        const WILL_FLAG     = 0b00000100;
        const WILL_QOS1     = 0b00001000;
        const WILL_QOS2     = 0b00010000;
        const WILL_RETAIN   = 0b00100000;
        const PASSWORD      = 0b01000000;
        const USERNAME      = 0b10000000;
    }
}

impl From<QoS> for ConnectFlags {
    fn from(q: QoS) -> Self {
        match q {
            QoS::AtMostOnce => ConnectFlags::empty(),
            QoS::AtLeastOnce => ConnectFlags::WILL_QOS1,
            QoS::ExactlyOnce => ConnectFlags::WILL_QOS2,
        }
    }
}

/// Connect Properties
///
/// The wire representation starts with the length of all properties after which
/// the identifiers and their actual value are given
///
/// 3.1.2.11.1 Property Length
/// The length of the Properties in the CONNECT packet Variable Header encoded as a Variable Byte Integer.
/// Followed by all possible connect properties:
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ConnectProperties {
    /// 3.1.2.11.2 Session Expiry Interval
    /// 17 (0x11) Byte Identifier of the Session Expiry Interval
    pub session_expiry_interval: Option<u32>,

    /// 3.1.2.11.3 Receive Maximum
    /// 33 (0x21) Byte, Identifier of the Receive Maximum
    pub receive_maximum: Option<u16>,

    /// 3.1.2.11.4 Maximum Packet Size
    /// 39 (0x27) Byte, Identifier of the Maximum Packet Size
    pub maximum_packet_size: Option<u32>,

    /// 3.1.2.11.5 Topic Alias Maximum
    /// 34 (0x22) Byte, Identifier of the Topic Alias Maximum
    pub topic_alias_maximum: Option<u16>,

    /// 3.1.2.11.6 Request Response Information
    /// 25 (0x19) Byte, Identifier of the Request Response Information
    pub request_response_information: Option<u8>,

    /// 3.1.2.11.7 Request Problem Information
    /// 23 (0x17) Byte, Identifier of the Request Problem Information
    pub request_problem_information: Option<u8>,

    /// 3.1.2.11.8 User Property
    /// 38 (0x26) Byte, Identifier of the User Property
    pub user_properties: Vec<(String, String)>,

    /// 3.1.2.11.9 Authentication Method
    /// 21 (0x15) Byte, Identifier of the Authentication Method
    pub authentication_method: Option<String>,

    /// 3.1.2.11.10 Authentication Data
    /// 22 (0x16) Byte, Identifier of the Authentication Data
    pub authentication_data: Bytes,
}

impl MqttWrite for ConnectProperties {
    fn write(&self, buf: &mut BytesMut) -> Result<(), SerializeError> {
        write_variable_integer(buf, self.wire_len())?;

        if let Some(session_expiry_interval) = self.session_expiry_interval {
            PropertyType::SessionExpiryInterval.write(buf)?;
            buf.put_u32(session_expiry_interval);
        }
        if let Some(receive_maximum) = self.receive_maximum {
            PropertyType::ReceiveMaximum.write(buf)?;
            buf.put_u16(receive_maximum);
        }
        if let Some(maximum_packet_size) = self.maximum_packet_size {
            PropertyType::MaximumPacketSize.write(buf)?;
            buf.put_u32(maximum_packet_size);
        }
        if let Some(topic_alias_maximum) = self.topic_alias_maximum {
            PropertyType::TopicAliasMaximum.write(buf)?;
            buf.put_u16(topic_alias_maximum);
        }
        if let Some(request_response_information) = self.request_response_information {
            PropertyType::RequestResponseInformation.write(buf)?;
            buf.put_u8(request_response_information);
        }
        if let Some(request_problem_information) = self.request_problem_information {
            PropertyType::RequestProblemInformation.write(buf)?;
            buf.put_u8(request_problem_information);
        }
        for (key, value) in &self.user_properties {
            PropertyType::UserProperty.write(buf)?;
            key.write(buf)?;
            value.write(buf)?;
        }
        if let Some(authentication_method) = &self.authentication_method {
            PropertyType::AuthenticationMethod.write(buf)?;
            authentication_method.write(buf)?;
        }
        if !self.authentication_data.is_empty() {
            if self.authentication_method.is_none() {
                return Err(SerializeError::AuthDataWithoutAuthMethod);
            }
            PropertyType::AuthenticationData.write(buf)?;
            self.authentication_data.write(buf)?;
        }

        Ok(())
    }
}

impl MqttRead for ConnectProperties {
    fn read(buf: &mut Bytes) -> Result<Self, DeserializeError> {
        let (len, _) = read_variable_integer(buf)?;

        let mut properties = Self::default();
        if len == 0 {
            return Ok(properties);
        }
        else if buf.len() < len {
            return Err(DeserializeError::InsufficientData(
                "ConnectProperties".to_string(),
                buf.len(),
                len,
            ));
        }

        let mut property_data = buf.split_to(len);

        loop {
            match PropertyType::read(&mut property_data)? {
                PropertyType::SessionExpiryInterval => {
                    if properties.session_expiry_interval.is_some() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::SessionExpiryInterval,
                        ));
                    }
                    properties.session_expiry_interval = Some(property_data.get_u32());
                }
                PropertyType::ReceiveMaximum => {
                    if properties.receive_maximum.is_some() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::ReceiveMaximum,
                        ));
                    }
                    properties.receive_maximum = Some(property_data.get_u16());
                }
                PropertyType::MaximumPacketSize => {
                    if properties.maximum_packet_size.is_some() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::MaximumPacketSize,
                        ));
                    }
                    properties.maximum_packet_size = Some(property_data.get_u32());
                }
                PropertyType::TopicAliasMaximum => {
                    if properties.topic_alias_maximum.is_some() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::TopicAliasMaximum,
                        ));
                    }
                    properties.topic_alias_maximum = Some(property_data.get_u16());
                }
                PropertyType::RequestResponseInformation => {
                    if properties.request_response_information.is_some() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::RequestResponseInformation,
                        ));
                    }
                    properties.request_response_information = Some(property_data.get_u8());
                }
                PropertyType::RequestProblemInformation => {
                    if properties.request_problem_information.is_some() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::RequestProblemInformation,
                        ));
                    }
                    properties.request_problem_information = Some(property_data.get_u8());
                }
                PropertyType::UserProperty => properties.user_properties.push((
                    String::read(&mut property_data)?,
                    String::read(&mut property_data)?,
                )),
                PropertyType::AuthenticationMethod => {
                    if properties.authentication_method.is_some() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::AuthenticationMethod,
                        ));
                    }
                    properties.authentication_method = Some(String::read(&mut property_data)?);
                }
                PropertyType::AuthenticationData => {
                    if properties.authentication_data.is_empty() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::AuthenticationData,
                        ));
                    }
                    properties.authentication_data = Bytes::read(&mut property_data)?;
                }
                e => return Err(DeserializeError::UnexpectedProperty(e, PacketType::Connect)),
            }

            if property_data.is_empty() {
                break;
            }
        }

        if !properties.authentication_data.is_empty() && properties.authentication_method.is_none()
        {
            return Err(DeserializeError::MalformedPacketWithInfo(
                "Authentication data is not empty while authentication method is".to_string(),
            ));
        }

        Ok(properties)
    }
}

impl WireLength for ConnectProperties {
    fn wire_len(&self) -> usize {
        let mut len: usize = 0;

        if self.session_expiry_interval.is_some() {
            len += 1 + 4;
        }
        if self.receive_maximum.is_some() {
            len += 1 + 2;
        }
        if self.maximum_packet_size.is_some() {
            len += 1 + 4;
        }
        if self.topic_alias_maximum.is_some() {
            len += 1 + 2;
        }
        if self.request_response_information.is_some() {
            len += 2;
        }
        if self.request_problem_information.is_some() {
            len += 2;
        }
        for (key, value) in &self.user_properties {
            len += 1;
            len += key.wire_len();
            len += value.wire_len();
        }
        if let Some(authentication_method) = &self.authentication_method {
            len += 1 + authentication_method.wire_len();
        }
        if !self.authentication_data.is_empty() && self.authentication_method.is_some() {
            len += 1 + self.authentication_data.wire_len();
        }

        len
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LastWill {
    /// 3.1.2.6 Will QoS
    pub qos: QoS,
    /// 3.1.2.7 Will Retain
    pub retain: bool,

    /// 3.1.3.2 Will properties
    pub last_will_properties: LastWillProperties,
    /// 3.1.3.3 Will Topic
    pub topic: String,
    /// 3.1.3.4 Will payload
    pub payload: Bytes,
}

impl LastWill {
    pub fn new<T: Into<String>, P: Into<Vec<u8>>>(
        qos: QoS,
        retain: bool,
        topic: T,
        payload: P,
    ) -> LastWill {
        Self {
            qos,
            retain,
            last_will_properties: LastWillProperties::default(),
            topic: topic.into(),
            payload: Bytes::from(payload.into()),
        }
    }
    pub fn read(qos: QoS, retain: bool, buf: &mut Bytes) -> Result<Self, DeserializeError> {
        let last_will_properties = LastWillProperties::read(buf)?;
        let topic = String::read(buf)?;
        let payload = Bytes::read(buf)?;

        Ok(Self {
            qos,
            retain,
            topic,
            payload,
            last_will_properties,
        })
    }
}

impl MqttWrite for LastWill {
    fn write(&self, buf: &mut BytesMut) -> Result<(), SerializeError> {
        self.last_will_properties.write(buf)?;
        self.topic.write(buf)?;
        self.payload.write(buf)?;
        Ok(())
    }
}

impl WireLength for LastWill {
    fn wire_len(&self) -> usize {
        self.topic.wire_len() + self.payload.wire_len() + self.last_will_properties.wire_len()
    }
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct LastWillProperties {
    /// 3.1.3.2.2 Will Delay Interval
    delay_interval: Option<u32>,
    /// 3.1.3.2.3 Payload Format Indicator
    payload_format_indicator: Option<u8>,
    /// 3.1.3.2.4 Message Expiry Interval
    message_expiry_interval: Option<u32>,
    /// 3.1.3.2.5 Content Type
    content_type: Option<String>,
    /// 3.1.3.2.6 Response Topic
    response_topic: Option<String>,
    /// 3.1.3.2.7 Correlation Data
    correlation_data: Option<Bytes>,
    /// 3.1.3.2.8 User Property
    user_properties: Vec<(String, String)>,
}

impl MqttRead for LastWillProperties {
    fn read(buf: &mut Bytes) -> Result<Self, DeserializeError> {
        let (len, _) = read_variable_integer(buf)?;

        let mut properties = Self::default();
        if len == 0 {
            return Ok(properties);
        }
        else if buf.len() < len {
            return Err(DeserializeError::InsufficientData(
                "LastWillProperties".to_string(),
                buf.len(),
                len,
            ));
        }

        let mut property_data = buf.split_to(len);

        loop {
            match PropertyType::read(&mut property_data)? {
                PropertyType::WillDelayInterval => {
                    if properties.delay_interval.is_some() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::WillDelayInterval,
                        ));
                    }
                    properties.delay_interval = Some(u32::read(&mut property_data)?);
                }
                PropertyType::PayloadFormatIndicator => {
                    if properties.payload_format_indicator.is_none() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::PayloadFormatIndicator,
                        ));
                    }
                    properties.payload_format_indicator = Some(u8::read(&mut property_data)?);
                }
                PropertyType::MessageExpiryInterval => {
                    if properties.message_expiry_interval.is_some() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::MessageExpiryInterval,
                        ));
                    }
                    properties.message_expiry_interval = Some(u32::read(&mut property_data)?);
                }
                PropertyType::ContentType => {
                    if properties.content_type.is_some() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::ContentType,
                        ));
                    }
                    properties.content_type = Some(String::read(&mut property_data)?);
                }
                PropertyType::ResponseTopic => {
                    if properties.response_topic.is_some() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::ResponseTopic,
                        ));
                    }
                    properties.response_topic = Some(String::read(&mut property_data)?);
                }
                PropertyType::CorrelationData => {
                    if properties.correlation_data.is_some() {
                        return Err(DeserializeError::DuplicateProperty(
                            PropertyType::CorrelationData,
                        ));
                    }
                    properties.correlation_data = Some(Bytes::read(&mut property_data)?);
                }
                PropertyType::UserProperty => properties.user_properties.push((
                    String::read(&mut property_data)?,
                    String::read(&mut property_data)?,
                )),
                e => return Err(DeserializeError::UnexpectedProperty(e, PacketType::Connect)),
            }

            if property_data.is_empty() {
                break;
            }
        }

        Ok(properties)
    }
}

impl MqttWrite for LastWillProperties {
    fn write(&self, buf: &mut BytesMut) -> Result<(), SerializeError> {
        write_variable_integer(buf, self.wire_len())?;

        if let Some(delay_interval) = self.delay_interval {
            PropertyType::WillDelayInterval.write(buf)?;
            buf.put_u32(delay_interval);
        }
        if let Some(payload_format_indicator) = self.payload_format_indicator {
            PropertyType::PayloadFormatIndicator.write(buf)?;
            buf.put_u8(payload_format_indicator);
        }
        if let Some(message_expiry_interval) = self.message_expiry_interval {
            PropertyType::MessageExpiryInterval.write(buf)?;
            buf.put_u32(message_expiry_interval);
        }
        if let Some(content_type) = &self.content_type {
            PropertyType::ContentType.write(buf)?;
            content_type.write(buf)?;
        }
        if let Some(response_topic) = &self.response_topic {
            PropertyType::ResponseTopic.write(buf)?;
            response_topic.write(buf)?;
        }
        if let Some(correlation_data) = &self.correlation_data {
            PropertyType::CorrelationData.write(buf)?;
            correlation_data.write(buf)?;
        }
        if !self.user_properties.is_empty() {
            for (key, value) in &self.user_properties {
                PropertyType::UserProperty.write(buf)?;
                key.write(buf)?;
                value.write(buf)?;
            }
        }
        Ok(())
    }
}

impl WireLength for LastWillProperties {
    fn wire_len(&self) -> usize {
        let mut len: usize = 0;

        len += self.delay_interval.map_or(0, |_| 5);
        len += self.payload_format_indicator.map_or(0, |_| 2);
        len += self.message_expiry_interval.map_or(0, |_| 5);
        len += self
            .content_type
            .as_ref()
            .map_or_else(|| 0, |s| s.wire_len());
        len += self
            .response_topic
            .as_ref()
            .map_or_else(|| 0, |s| s.wire_len());
        len += self
            .correlation_data
            .as_ref()
            .map_or_else(|| 0, |b| b.wire_len());
        for (key, value) in &self.user_properties {
            len += key.wire_len() + value.wire_len();
        }

        len
    }
}

#[cfg(test)]
mod tests {
    use crate::packets::{
        mqtt_traits::{MqttWrite, VariableHeaderRead, VariableHeaderWrite},
        QoS,
    };

    use super::{Connect, LastWill};

    #[test]
    fn read_connect() {
        let mut buf = bytes::BytesMut::new();
        let packet = &[
            // 0x10,
            // 39, // packet type, flags and remaining len
            0x00,
            0x04,
            b'M',
            b'Q',
            b'T',
            b'T',
            0x05,
            0b1100_1110, // Connect Flags, username, password, will retain=false, will qos=1, last_will, clean_session
            0x00,        // Keep alive = 10 sec
            0x0a,
            0x00, // Length of Connect properties
            0x00, // client_id length
            0x04,
            b't', // client_id
            b'e',
            b's',
            b't',
            0x00, // Will properties length
            0x00, // length topic
            0x02,
            b'/', // Will topic = '/a'
            b'a',
            0x00, // Will payload length
            0x0B,
            b'h', // Will payload = 'hello world'
            b'e',
            b'l',
            b'l',
            b'o',
            b' ',
            b'w',
            b'o',
            b'r',
            b'l',
            b'd',
            0x00, // length username
            0x04,
            b'u', // username = 'user'
            b's',
            b'e',
            b'r',
            0x00, // length password
            0x04,
            b'p', // Password = 'pass'
            b'a',
            b's',
            b's',
            0xAB, // extra packets in the stream
            0xCD,
            0xEF,
        ];

        buf.extend_from_slice(packet);
        let c = Connect::read(0, 0, buf.into()).unwrap();

        dbg!(c);
    }

    #[test]
    fn read_and_write_connect() {
        let mut buf = bytes::BytesMut::new();
        let packet = &[
            // 0x10,
            // 39, // packet type, flags and remaining len
            0x00,
            0x04,
            b'M',
            b'Q',
            b'T',
            b'T',
            0x05,        // variable header
            0b1100_1110, // variable header. +username, +password, -will retain, will qos=1, +last_will, +clean_session
            0x00,        // Keep alive = 10 sec
            0x0a,
            0x00, // Length of Connect properties
            0x00, // client_id length
            0x04,
            b't', // client_id
            b'e',
            b's',
            b't',
            0x00, // Will properties length
            0x00, // length topic
            0x02,
            b'/', // Will topic = '/a'
            b'a',
            0x00, // Will payload length
            0x0B,
            b'h', // Will payload = 'hello world'
            b'e',
            b'l',
            b'l',
            b'o',
            b' ',
            b'w',
            b'o',
            b'r',
            b'l',
            b'd',
            0x00, // length username
            0x04,
            b'u', // username
            b's',
            b'e',
            b'r',
            0x00, // length password
            0x04,
            b'p', // payload. password = 'pass'
            b'a',
            b's',
            b's',
        ];

        buf.extend_from_slice(packet);
        let c = Connect::read(0, 0, buf.into()).unwrap();

        let mut write_buf = bytes::BytesMut::new();
        c.write(&mut write_buf).unwrap();

        assert_eq!(packet.to_vec(), write_buf.to_vec());

        dbg!(c);
    }

    #[test]
    fn parsing_last_will() {
        let last_will = &[
            0x00, // Will properties length
            0x00, // length topic
            0x02, b'/', // Will topic = '/a'
            b'a', 0x00, // Will payload length
            0x0B, b'h', // Will payload = 'hello world'
            b'e', b'l', b'l', b'o', b' ', b'w', b'o', b'r', b'l', b'd',
        ];
        let mut buf = bytes::Bytes::from_static(last_will);

        assert!(LastWill::read(QoS::AtLeastOnce, false, &mut buf).is_ok());
    }

    #[test]
    fn read_and_write_connect2() {
        let _packet = [
            0x10, 0x1d, 0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x05, 0x80, 0x00, 0x3c, 0x05, 0x11,
            0xff, 0xff, 0xff, 0xff, 0x00, 0x05, 0x39, 0x2e, 0x30, 0x2e, 0x31, 0x00, 0x04, 0x54,
            0x65, 0x73, 0x74,
        ];

        let data = [
            0x00, 0x04, 0x4d, 0x51, 0x54, 0x54, 0x05, 0x80, 0x00, 0x3c, 0x05, 0x11, 0xff, 0xff,
            0xff, 0xff, 0x00, 0x05, 0x39, 0x2e, 0x30, 0x2e, 0x31, 0x00, 0x04, 0x54, 0x65, 0x73,
            0x74,
        ];

        let mut buf = bytes::BytesMut::new();
        buf.extend_from_slice(&data);

        let c = Connect::read(0, 0, buf.into()).unwrap();

        dbg!(c.clone());

        let mut write_buf = bytes::BytesMut::new();
        c.write(&mut write_buf).unwrap();

        assert_eq!(data.to_vec(), write_buf.to_vec());
    }

    #[test]
    fn parsing_and_writing_last_will() {
        let last_will = &[
            0x00, // Will properties length
            0x00, // length topic
            0x02, b'/', // Will topic = '/a'
            b'a', 0x00, // Will payload length
            0x0B, b'h', // Will payload = 'hello world'
            b'e', b'l', b'l', b'o', b' ', b'w', b'o', b'r', b'l', b'd',
        ];
        let mut buf = bytes::Bytes::from_static(last_will);

        let lw = LastWill::read(QoS::AtLeastOnce, false, &mut buf).unwrap();

        let mut write_buf = bytes::BytesMut::new();
        lw.write(&mut write_buf).unwrap();

        assert_eq!(last_will.to_vec(), write_buf.to_vec());
    }
}