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
use crate::{
    codec::*,
    core::{base_types::*, error::CodecError, properties::*},
};
use core::time::Duration;

/// Connection options, represented as a consuming builder.
/// Used during [connection request](crate::Context::connect), translated to the CONNECT packet.
///
#[derive(Default)]
pub struct ConnectOpts<'a> {
    builder: ConnectTxBuilder<'a>,
}

impl<'a> ConnectOpts<'a> {
    /// Creates a new [ConnectOpts] instance.
    ///
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the client identifier.
    ///
    pub fn client_identifier(mut self, val: &'a str) -> Self {
        self.builder.client_identifier(UTF8StringRef(val));
        self
    }

    /// Sets the session keep alive.
    ///
    /// # Arguments
    /// `val` - [Duration] value less than [u16::MAX] in seconds.
    ///
    /// # Panics
    /// When the duration in seconds is greater than [u16::MAX].
    ///
    pub fn keep_alive(mut self, val: Duration) -> Self {
        self.builder
            .keep_alive(u16::try_from(val.as_secs()).unwrap());
        self
    }

    /// Sets the session expiry interval.
    ///
    /// # Arguments
    /// `val` - [Duration] value less than [u32::MAX] in seconds.
    ///
    /// # Panics
    /// When the duration in seconds is greater than [u32::MAX].
    ///
    pub fn session_expiry_interval(mut self, val: Duration) -> Self {
        self.builder
            .session_expiry_interval(SessionExpiryInterval::from(
                u32::try_from(val.as_secs()).unwrap(),
            ));
        self
    }

    /// Sets the maximum incoming QoS>0 publish messages handled at once.
    ///
    /// # Arguments
    /// `val` - value greater than 0
    ///
    /// # Panics
    /// When `val` equals 0.
    ///
    pub fn receive_maximum(mut self, val: u16) -> Self {
        self.builder
            .receive_maximum(ReceiveMaximum::from(NonZero::try_from(val).unwrap()));
        self
    }

    /// Sets the maximum packet size (in bytes).
    ///
    /// # Arguments
    /// `val` - value greater than 0
    ///
    /// # Panics
    /// When `val` equals 0.
    ///
    pub fn maximum_packet_size(mut self, val: u32) -> Self {
        self.builder
            .maximum_packet_size(MaximumPacketSize::from(NonZero::try_from(val).unwrap()));
        self
    }

    /// Sets the maximum accepted value of topic alias.
    ///
    pub fn topic_alias_maximum(mut self, val: u16) -> Self {
        self.builder
            .topic_alias_maximum(TopicAliasMaximum::from(val));
        self
    }

    /// Requests the broker to return response information in [ConnectRsp](super::rsp::ConnectRsp).
    ///
    pub fn request_response_information(mut self, val: bool) -> Self {
        self.builder
            .request_response_information(RequestResponseInformation::from(val));
        self
    }

    /// Requests the broker to return additional diagnostic data ([reason string](super::rsp::ConnectRsp::reason_string),
    /// [user properties](super::rsp::ConnectRsp::user_properties)) in [ConnectRsp](super::rsp::ConnectRsp).
    ///
    pub fn request_problem_information(mut self, val: bool) -> Self {
        self.builder
            .request_problem_information(RequestProblemInformation::from(val));
        self
    }

    /// Sets the name of the authentication method used for extended authorization.
    ///
    pub fn authentication_method(mut self, val: &'a str) -> Self {
        self.builder
            .authentication_method(AuthenticationMethodRef::from(UTF8StringRef(val)));
        self
    }

    /// Sets the binary authentication data. Note that setting authentication data without
    /// [authentication_method][ConnectOpts::authentication_method] set will result in an error.
    ///
    pub fn authentication_data(mut self, val: &'a [u8]) -> Self {
        self.builder
            .authentication_data(AuthenticationDataRef::from(BinaryRef(val)));
        self
    }

    /// Sets user properties as key-value pairs. Multiple user properties may be set.
    ///
    pub fn user_property(mut self, (key, val): (&'a str, &'a str)) -> Self {
        self.builder
            .user_property(UserPropertyRef::from(UTF8StringPairRef(key, val)));
        self
    }

    /// [QoS] used for will messages.
    ///
    pub fn will_qos(mut self, val: QoS) -> Self {
        self.builder.will_qos(val);
        self
    }

    /// Retain for will messages.
    ///
    pub fn will_retain(mut self, val: bool) -> Self {
        self.builder.will_retain(val);
        self
    }

    /// Clears the session upon connection.
    ///
    pub fn clean_start(mut self, val: bool) -> Self {
        self.builder.clean_start(val);
        self
    }

    /// Sets delay before publishing will messages.
    ///
    /// # Arguments
    /// `val` - [Duration] value less than [u32::MAX] in seconds.
    ///
    /// # Panics
    /// When the duration in seconds is greater than [u32::MAX].
    ///
    pub fn will_delay_interval(mut self, val: Duration) -> Self {
        self.builder.will_delay_interval(WillDelayInterval::from(
            u32::try_from(val.as_secs()).unwrap(),
        ));
        self
    }

    /// Sets payload format indicator for will messages.
    /// Value `false` indicates that the will payload is in unspecified format.
    /// Value `true` indicates that the payload is UTF8 encoded character data.
    ///
    pub fn will_payload_format_indicator(mut self, val: bool) -> Self {
        self.builder
            .will_payload_format_indicator(PayloadFormatIndicator::from(val));
        self
    }

    /// Sets the expiry interval of the will messages.
    ///
    /// # Arguments
    /// `val` - [Duration] value less than [u32::MAX] in seconds.
    ///
    /// # Panics
    /// When the duration in seconds is greater than [u32::MAX].
    ///
    pub fn will_message_expiry_interval(mut self, val: Duration) -> Self {
        self.builder
            .will_message_expiry_interval(MessageExpiryInterval::from(
                u32::try_from(val.as_secs()).unwrap(),
            ));
        self
    }

    /// Sets the content type of will messages.
    ///
    pub fn will_content_type(mut self, val: &'a str) -> Self {
        self.builder
            .will_content_type(ContentTypeRef::from(UTF8StringRef(val)));
        self
    }

    /// Sets the response topic for will messages.
    ///
    pub fn will_response_topic(mut self, val: &'a str) -> Self {
        self.builder
            .will_response_topic(ResponseTopicRef::from(UTF8StringRef(val)));
        self
    }

    /// Sets the correlation data for will messages.
    ///
    pub fn will_correlation_data(mut self, val: &'a [u8]) -> Self {
        self.builder
            .will_correlation_data(CorrelationDataRef::from(BinaryRef(val)));
        self
    }

    /// Sets user properties for will messages as key-value pairs. Multiple user properties may be set.
    ///
    pub fn will_user_property(mut self, (key, val): (&'a str, &'a str)) -> Self {
        self.builder
            .will_user_property(UserPropertyRef::from(UTF8StringPairRef(key, val)));
        self
    }

    /// Sets the topic for will messages.
    ///
    pub fn will_topic(mut self, val: &'a str) -> Self {
        self.builder.will_topic(UTF8StringRef(val));
        self
    }

    /// Sets the binary payload for will messages.
    ///
    pub fn will_payload(mut self, val: &'a [u8]) -> Self {
        self.builder.will_payload(BinaryRef(val));
        self
    }

    /// Sets the username for normal authorization.
    ///
    pub fn username(mut self, val: &'a str) -> Self {
        self.builder.username(UTF8StringRef(val));
        self
    }

    /// Sets the password for normal authorization.
    ///
    pub fn password(mut self, val: &'a [u8]) -> Self {
        self.builder.password(BinaryRef(val));
        self
    }

    pub(crate) fn build(self) -> Result<ConnectTx<'a>, CodecError> {
        self.builder.build()
    }
}

/// Authorization options, represented as a consuming builder.
/// Used during [extended authorization](crate::Context::authorize), translated to the AUTH packet.
///
#[derive(Default)]
pub struct AuthOpts<'a> {
    builder: AuthTxBuilder<'a>,
}

impl<'a> AuthOpts<'a> {
    /// Creates a new [AuthOpts] instance.
    ///
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets a reason value.
    ///
    pub fn reason(mut self, val: AuthReason) -> Self {
        self.builder.reason(val);
        self
    }

    /// Sets a reason string property.
    ///
    pub fn reason_string(mut self, val: &'a str) {
        self.builder
            .reason_string(ReasonStringRef::from(UTF8StringRef(val)));
    }

    /// Sets the name of the authentication method used for extended authorization.
    ///
    pub fn authentication_method(mut self, val: &'a str) -> Self {
        self.builder
            .authentication_method(AuthenticationMethodRef::from(UTF8StringRef(val)));
        self
    }

    /// Sets the binary authentication data. Note that setting authentication data without
    /// [authentication_method][ConnectOpts::authentication_method] set will result in an error.
    ///
    pub fn authentication_data(mut self, val: &'a [u8]) -> Self {
        self.builder
            .authentication_data(AuthenticationDataRef::from(BinaryRef(val)));
        self
    }

    /// Sets user properties as key-value pairs. Multiple user properties may be set.
    ///
    pub fn user_property(mut self, (key, val): (&'a str, &'a str)) -> Self {
        self.builder
            .user_property(UserPropertyRef::from(UTF8StringPairRef(key, val)));
        self
    }

    pub(crate) fn build(self) -> Result<AuthTx<'a>, CodecError> {
        self.builder.build()
    }
}

/// Disconnection options, represented as a consuming builder.
/// Used during [disconnection request](super::handle::ContextHandle::disconnect), translated to the DISCONNECT packet.
///
#[derive(Default)]
pub struct DisconnectOpts<'a> {
    builder: DisconnectTxBuilder<'a>,
}

impl<'a> DisconnectOpts<'a> {
    /// Creates a new [DisconnectOpts] instance.
    ///
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets a reason for disconnection.
    ///
    pub fn reason(mut self, reason: DisconnectReason) -> Self {
        self.builder.reason(reason);
        self
    }

    /// Sets session expiration interval.
    ///
    /// # Arguments
    /// `val` - [Duration] value less than [u32::MAX] in seconds.
    ///
    /// # Panics
    /// When the duration in seconds is greater than [u32::MAX].
    ///
    pub fn session_expiry_interval(mut self, val: Duration) -> Self {
        self.builder
            .session_expiry_interval(SessionExpiryInterval::from(
                u32::try_from(val.as_secs()).unwrap(),
            ));
        self
    }

    /// Sets a reason string property.
    ///
    pub fn reason_string(mut self, val: &'a str) -> Self {
        self.builder
            .reason_string(ReasonStringRef::from(UTF8StringRef(val)));
        self
    }

    /// Sets user properties. Multiple user properties may be set.
    ///
    pub fn user_property(mut self, (key, val): (&'a str, &'a str)) -> Self {
        self.builder
            .user_property(UserPropertyRef::from(UTF8StringPairRef(key, val)));
        self
    }

    pub(crate) fn build(self) -> Result<DisconnectTx<'a>, CodecError> {
        self.builder.build()
    }
}

/// Subscription options, represented as a consuming builder.
/// Used during [subscription request](super::handle::ContextHandle::subscribe), translated to the SUBSCRIBE packet.
/// Note that multiple topic filters may be supplied.
///
#[derive(Default)]
pub struct SubscribeOpts<'a> {
    builder: SubscribeTxBuilder<'a>,
}

impl<'a> SubscribeOpts<'a> {
    /// Creates a new [SubscribeOpts] instance.
    ///
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets a new subscription with the given topic filter and options.
    /// Multiple subscriptions may be created.
    ///
    pub fn subscription(mut self, topic: &'a str, opts: SubscriptionOptions) -> Self {
        self.builder.payload((UTF8StringRef(topic), opts));
        self
    }

    /// Sets user properties as key-value pairs. Multiple user properties may be set.
    ///
    pub fn user_property(mut self, (key, val): (&'a str, &'a str)) -> Self {
        self.builder
            .user_property(UserPropertyRef::from(UTF8StringPairRef(key, val)));
        self
    }

    pub(crate) fn packet_identifier(mut self, val: u16) -> Self {
        self.builder
            .packet_identifier(NonZero::try_from(val).unwrap());
        self
    }

    pub(crate) fn subscription_identifier(mut self, val: u32) -> Self {
        self.builder.subscription_identifier(
            VarSizeInt::try_from(val)
                .and_then(NonZero::try_from)
                .map(SubscriptionIdentifier::from)
                .unwrap(),
        );
        self
    }

    pub(crate) fn build(self) -> Result<SubscribeTx<'a>, CodecError> {
        self.builder.build()
    }
}

/// Publish options, represented as a consuming builder.
/// Used during [publish request](super::handle::ContextHandle::publish), translated to the PUBLISH packet.
///
#[derive(Default)]
pub struct PublishOpts<'a> {
    pub(crate) qos: Option<QoS>,
    builder: PublishTxBuilder<'a>,
}

impl<'a> PublishOpts<'a> {
    /// Creates a new [PublishOpts] instance.
    ///
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets a retain flag.
    ///
    pub fn retain(mut self, val: bool) -> Self {
        self.builder.retain(val);
        self
    }

    /// Sets QoS level.
    ///
    pub fn qos(mut self, val: QoS) -> Self {
        self.qos = Some(val);
        self.builder.qos(val);
        self
    }

    /// Sets topic.
    ///
    pub fn topic(mut self, val: &'a str) -> Self {
        self.builder.topic_name(UTF8StringRef(val));
        self
    }

    /// Sets payload format indicator.
    /// Value `false` indicates that the will payload is in unspecified format.
    /// Value `true` indicates that the payload is UTF8 encoded character data.
    ///
    pub fn payload_format_indicator(mut self, val: bool) -> Self {
        self.builder
            .payload_format_indicator(PayloadFormatIndicator::from(val));
        self
    }

    /// Sets the topic alias.
    ///
    /// # Arguments
    /// `val` - value greater than 0
    ///
    /// # Panics
    /// When `val` equals 0.
    ///
    pub fn topic_alias(mut self, val: u16) -> Self {
        self.builder
            .topic_alias(TopicAlias::from(NonZero::try_from(val).unwrap()));
        self
    }

    /// Sets the expiry interval of the message.
    ///
    /// # Arguments
    /// `val` - [Duration] value less than [u32::MAX] in seconds.
    ///
    /// # Panics
    /// When the duration in seconds is greater than [u32::MAX].
    ///
    pub fn message_expiry_interval(mut self, val: Duration) -> Self {
        self.builder
            .message_expiry_interval(MessageExpiryInterval::from(
                u32::try_from(val.as_secs()).unwrap(),
            ));
        self
    }

    /// Sets correlation data.
    ///
    pub fn correlation_data(mut self, val: &'a [u8]) -> Self {
        self.builder
            .correlation_data(CorrelationDataRef::from(BinaryRef(val)));
        self
    }

    /// Sets response topic.
    ///
    pub fn response_topic(mut self, val: &'a str) -> Self {
        self.builder
            .response_topic(ResponseTopicRef::from(UTF8StringRef(val)));
        self
    }

    /// Sets message content type.
    ///
    pub fn content_type(mut self, val: &'a str) -> Self {
        self.builder
            .content_type(ContentTypeRef::from(UTF8StringRef(val)));
        self
    }

    /// Sets user properties as key-value pairs. Multiple user properties may be set.
    ///
    pub fn user_property(mut self, (key, val): (&'a str, &'a str)) -> Self {
        self.builder
            .user_property(UserPropertyRef::from(UTF8StringPairRef(key, val)));
        self
    }

    /// Sets message data.
    ///
    pub fn data(mut self, val: &'a [u8]) -> Self {
        self.builder.payload(PayloadRef(val));
        self
    }

    pub(crate) fn packet_identifier(mut self, val: u16) -> Self {
        self.builder
            .packet_identifier(NonZero::try_from(val).unwrap());
        self
    }

    pub(crate) fn build(self) -> Result<PublishTx<'a>, CodecError> {
        self.builder.build()
    }
}

/// Unsubscribe options, represented as a consuming builder.
/// Used during [unsubscribe request](super::handle::ContextHandle::unsubscribe), translated to the UNSUBSCRIBE packet.
///
#[derive(Default)]
pub struct UnsubscribeOpts<'a> {
    builder: UnsubscribeTxBuilder<'a>,
}

impl<'a> UnsubscribeOpts<'a> {
    /// Creates a new [UnsubscribeOpts] instance.
    ///
    pub fn new() -> Self {
        Self::default()
    }

    /// Topic filter to unsubscribe from.
    pub fn topic(mut self, val: &'a str) -> Self {
        self.builder.payload(UTF8StringRef(val));
        self
    }

    /// Sets user properties as key-value pairs. Multiple user properties may be set.
    ///
    pub fn user_property(mut self, (key, val): (&'a str, &'a str)) -> Self {
        self.builder
            .user_property(UserPropertyRef::from(UTF8StringPairRef(key, val)));
        self
    }

    pub(crate) fn packet_identifier(mut self, val: u16) -> Self {
        self.builder
            .packet_identifier(NonZero::try_from(val).unwrap());
        self
    }

    pub(crate) fn build(self) -> Result<UnsubscribeTx<'a>, CodecError> {
        self.builder.build()
    }
}