pub struct MessageType(_);
Expand description

The type of a Message. A combination of a MessageClass and a STUN method.

Implementations§

Create a new MessageType from the provided MessageClass and method

Examples
let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
assert_eq!(mtype.has_class(MessageClass::Indication), true);
assert_eq!(mtype.has_method(BINDING), true);
Examples found in repository?
src/stun/message.rs (line 353)
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
    pub fn new_request(method: u16) -> Self {
        Message::new(
            MessageType::from_class_method(MessageClass::Request, method),
            Message::generate_transaction(),
        )
    }

    /// Create a new success [`Message`] response from the provided request
    ///
    /// # Panics
    ///
    /// When a non-request [`Message`] is passed as the original input [`Message`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// let success = Message::new_success(&message);
    /// assert!(success.has_class(MessageClass::Success));
    /// assert!(success.has_method(BINDING));
    /// ```
    pub fn new_success(orig: &Message) -> Self {
        if !orig.has_class(MessageClass::Request) {
            panic!(
                "A success response message was attempted to be created from a non-request message"
            );
        }
        Message::new(
            MessageType::from_class_method(MessageClass::Success, orig.method()),
            orig.transaction_id(),
        )
    }

    /// Create a new error [`Message`] response from the provided request
    ///
    /// # Panics
    ///
    /// When a non-request [`Message`] is passed as the original input [`Message`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// let success = Message::new_error(&message);
    /// assert!(success.has_class(MessageClass::Error));
    /// assert!(success.has_method(BINDING));
    /// ```
    pub fn new_error(orig: &Message) -> Self {
        Message::new(
            MessageType::from_class_method(MessageClass::Error, orig.method()),
            orig.transaction_id(),
        )
    }

Retrieves the class of a MessageType

Examples
let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
assert_eq!(mtype.class(), MessageClass::Indication);
Examples found in repository?
src/stun/message.rs (line 117)
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
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "MessageType(class: {:?}, method: {} ({:#x}))",
            self.class(),
            self.method(),
            self.method()
        )
    }
}

impl MessageType {
    /// Create a new [`MessageType`] from the provided [`MessageClass`] and method
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{MessageType, MessageClass, BINDING};
    /// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
    /// assert_eq!(mtype.has_class(MessageClass::Indication), true);
    /// assert_eq!(mtype.has_method(BINDING), true);
    /// ```
    pub fn from_class_method(class: MessageClass, method: u16) -> Self {
        let class_bits = MessageClass::to_bits(class);
        let method_bits = method & 0xf | (method & 0x70) << 1 | (method & 0xf80) << 2;
        // trace!("MessageType from class {:?} and method {:?} into {:?}", class, method,
        //     class_bits | method_bits);
        Self(class_bits | method_bits)
    }

    /// Retrieves the class of a [`MessageType`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{MessageType, MessageClass, BINDING};
    /// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
    /// assert_eq!(mtype.class(), MessageClass::Indication);
    /// ```
    pub fn class(self) -> MessageClass {
        let class = (self.0 & 0x10) >> 4 | (self.0 & 0x100) >> 7;
        match class {
            0x0 => MessageClass::Request,
            0x1 => MessageClass::Indication,
            0x2 => MessageClass::Success,
            0x3 => MessageClass::Error,
            _ => unreachable!(),
        }
    }

    /// Returns whether class of a [`MessageType`] is equal to the provided [`MessageClass`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{MessageType, MessageClass, BINDING};
    /// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
    /// assert!(mtype.has_class(MessageClass::Indication));
    /// ```
    pub fn has_class(self, cls: MessageClass) -> bool {
        self.class() == cls
    }

    /// Returns whether class of a [`MessageType`] indicates a response [`Message`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{MessageType, MessageClass, BINDING};
    /// assert_eq!(MessageType::from_class_method(MessageClass::Indication, BINDING)
    ///     .is_response(), false);
    /// assert_eq!(MessageType::from_class_method(MessageClass::Request, BINDING)
    ///     .is_response(), false);
    /// assert_eq!(MessageType::from_class_method(MessageClass::Success, BINDING)
    ///     .is_response(), true);
    /// assert_eq!(MessageType::from_class_method(MessageClass::Error, BINDING)
    ///     .is_response(), true);
    /// ```
    pub fn is_response(self) -> bool {
        self.class().is_response()
    }

    /// Returns the method of a [`MessageType`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{MessageType, MessageClass, BINDING};
    /// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
    /// assert_eq!(mtype.method(), BINDING);
    /// ```
    pub fn method(self) -> u16 {
        self.0 & 0xf | (self.0 & 0xe0) >> 1 | (self.0 & 0x3e00) >> 2
    }

    /// Returns whether the method of a [`MessageType`] is equal to the provided value
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{MessageType, MessageClass, BINDING};
    /// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
    /// assert_eq!(mtype.has_method(BINDING), true);
    /// ```
    pub fn has_method(self, method: u16) -> bool {
        self.method() == method
    }

    /// Convert a [`MessageType`] to network bytes
    pub fn to_bytes(self) -> Vec<u8> {
        let mut ret = vec![0; 2];
        BigEndian::write_u16(&mut ret[0..2], self.0);
        ret
    }

    /// Convert a set of network bytes into a [`MessageType`] or return an error
    pub fn from_bytes(data: &[u8]) -> Result<Self, StunError> {
        let data = BigEndian::read_u16(data);
        if data & 0xc000 != 0x0 {
            /* not a stun packet */
            return Err(StunError::ParseError(StunParseError::WrongImplementation));
        }
        Ok(Self(data))
    }
}
impl From<MessageType> for Vec<u8> {
    fn from(f: MessageType) -> Self {
        f.to_bytes()
    }
}
impl TryFrom<&[u8]> for MessageType {
    type Error = StunError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        MessageType::from_bytes(value)
    }
}

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct TransactionId {
    id: u128,
}

impl From<u128> for TransactionId {
    fn from(id: u128) -> Self {
        Self {
            id: id & 0xffff_ffff_ffff_ffff_ffff_ffff,
        }
    }
}
impl From<TransactionId> for u128 {
    fn from(id: TransactionId) -> Self {
        id.id
    }
}
impl std::fmt::Display for TransactionId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:#x}", self.id)
    }
}

/// The structure that encapsulates the entirety of a STUN message
///
/// Contains the [`MessageType`], a transaction ID, and a list of STUN
/// [`Attribute`](crate::stun::attribute::Attribute)s.
#[derive(Debug, Clone)]
pub struct Message {
    msg_type: MessageType,
    transaction: TransactionId,
    attributes: Vec<RawAttribute>,
}

impl std::fmt::Display for Message {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Message(class: {:?}, method: {} ({:#x}), transaction: {}, attributes: ",
            self.get_type().class(),
            self.get_type().method(),
            self.get_type().method(),
            self.transaction_id()
        )?;
        if self.attributes.is_empty() {
            write!(f, "[]")?;
        } else {
            write!(f, "[")?;
            for (i, a) in self.attributes.iter().enumerate() {
                if i > 0 {
                    write!(f, ", ")?;
                }
                write!(f, "{}", a)?;
            }
            write!(f, "]")?;
        }
        write!(f, ")")
    }
}

fn padded_attr_size(attr: &RawAttribute) -> usize {
    if attr.length() % 4 == 0 {
        4 + attr.length() as usize
    } else {
        8 + attr.length() as usize - attr.length() as usize % 4
    }
}

impl Message {
    /// Create a new [`Message`] with the provided [`MessageType`] and transaction ID
    ///
    /// Note you probably want to use one of the other helper constructors instead.
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
    /// let message = Message::new(mtype, 0.into());
    /// assert!(message.has_class(MessageClass::Indication));
    /// assert!(message.has_method(BINDING));
    /// ```
    pub fn new(mtype: MessageType, transaction: TransactionId) -> Self {
        Self {
            msg_type: mtype,
            transaction,
            attributes: vec![],
        }
    }

    /// Create a new request [`Message`] of the provided method
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// assert!(message.has_class(MessageClass::Request));
    /// assert!(message.has_method(BINDING));
    /// ```
    pub fn new_request(method: u16) -> Self {
        Message::new(
            MessageType::from_class_method(MessageClass::Request, method),
            Message::generate_transaction(),
        )
    }

    /// Create a new success [`Message`] response from the provided request
    ///
    /// # Panics
    ///
    /// When a non-request [`Message`] is passed as the original input [`Message`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// let success = Message::new_success(&message);
    /// assert!(success.has_class(MessageClass::Success));
    /// assert!(success.has_method(BINDING));
    /// ```
    pub fn new_success(orig: &Message) -> Self {
        if !orig.has_class(MessageClass::Request) {
            panic!(
                "A success response message was attempted to be created from a non-request message"
            );
        }
        Message::new(
            MessageType::from_class_method(MessageClass::Success, orig.method()),
            orig.transaction_id(),
        )
    }

    /// Create a new error [`Message`] response from the provided request
    ///
    /// # Panics
    ///
    /// When a non-request [`Message`] is passed as the original input [`Message`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// let success = Message::new_error(&message);
    /// assert!(success.has_class(MessageClass::Error));
    /// assert!(success.has_method(BINDING));
    /// ```
    pub fn new_error(orig: &Message) -> Self {
        Message::new(
            MessageType::from_class_method(MessageClass::Error, orig.method()),
            orig.transaction_id(),
        )
    }

    /// Retrieve the [`MessageType`] of a [`Message`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// assert!(message.get_type().has_class(MessageClass::Request));
    /// assert!(message.get_type().has_method(BINDING));
    /// ```
    pub fn get_type(&self) -> MessageType {
        self.msg_type
    }

    /// Retrieve the [`MessageClass`] of a [`Message`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// assert_eq!(message.class(), MessageClass::Request);
    /// ```
    pub fn class(&self) -> MessageClass {
        self.get_type().class()
    }

Returns whether class of a MessageType is equal to the provided MessageClass

Examples
let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
assert!(mtype.has_class(MessageClass::Indication));

Returns whether class of a MessageType indicates a response Message

Examples
assert_eq!(MessageType::from_class_method(MessageClass::Indication, BINDING)
    .is_response(), false);
assert_eq!(MessageType::from_class_method(MessageClass::Request, BINDING)
    .is_response(), false);
assert_eq!(MessageType::from_class_method(MessageClass::Success, BINDING)
    .is_response(), true);
assert_eq!(MessageType::from_class_method(MessageClass::Error, BINDING)
    .is_response(), true);

Returns the method of a MessageType

Examples
let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
assert_eq!(mtype.method(), BINDING);
Examples found in repository?
src/stun/message.rs (line 118)
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
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "MessageType(class: {:?}, method: {} ({:#x}))",
            self.class(),
            self.method(),
            self.method()
        )
    }
}

impl MessageType {
    /// Create a new [`MessageType`] from the provided [`MessageClass`] and method
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{MessageType, MessageClass, BINDING};
    /// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
    /// assert_eq!(mtype.has_class(MessageClass::Indication), true);
    /// assert_eq!(mtype.has_method(BINDING), true);
    /// ```
    pub fn from_class_method(class: MessageClass, method: u16) -> Self {
        let class_bits = MessageClass::to_bits(class);
        let method_bits = method & 0xf | (method & 0x70) << 1 | (method & 0xf80) << 2;
        // trace!("MessageType from class {:?} and method {:?} into {:?}", class, method,
        //     class_bits | method_bits);
        Self(class_bits | method_bits)
    }

    /// Retrieves the class of a [`MessageType`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{MessageType, MessageClass, BINDING};
    /// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
    /// assert_eq!(mtype.class(), MessageClass::Indication);
    /// ```
    pub fn class(self) -> MessageClass {
        let class = (self.0 & 0x10) >> 4 | (self.0 & 0x100) >> 7;
        match class {
            0x0 => MessageClass::Request,
            0x1 => MessageClass::Indication,
            0x2 => MessageClass::Success,
            0x3 => MessageClass::Error,
            _ => unreachable!(),
        }
    }

    /// Returns whether class of a [`MessageType`] is equal to the provided [`MessageClass`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{MessageType, MessageClass, BINDING};
    /// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
    /// assert!(mtype.has_class(MessageClass::Indication));
    /// ```
    pub fn has_class(self, cls: MessageClass) -> bool {
        self.class() == cls
    }

    /// Returns whether class of a [`MessageType`] indicates a response [`Message`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{MessageType, MessageClass, BINDING};
    /// assert_eq!(MessageType::from_class_method(MessageClass::Indication, BINDING)
    ///     .is_response(), false);
    /// assert_eq!(MessageType::from_class_method(MessageClass::Request, BINDING)
    ///     .is_response(), false);
    /// assert_eq!(MessageType::from_class_method(MessageClass::Success, BINDING)
    ///     .is_response(), true);
    /// assert_eq!(MessageType::from_class_method(MessageClass::Error, BINDING)
    ///     .is_response(), true);
    /// ```
    pub fn is_response(self) -> bool {
        self.class().is_response()
    }

    /// Returns the method of a [`MessageType`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{MessageType, MessageClass, BINDING};
    /// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
    /// assert_eq!(mtype.method(), BINDING);
    /// ```
    pub fn method(self) -> u16 {
        self.0 & 0xf | (self.0 & 0xe0) >> 1 | (self.0 & 0x3e00) >> 2
    }

    /// Returns whether the method of a [`MessageType`] is equal to the provided value
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{MessageType, MessageClass, BINDING};
    /// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
    /// assert_eq!(mtype.has_method(BINDING), true);
    /// ```
    pub fn has_method(self, method: u16) -> bool {
        self.method() == method
    }

    /// Convert a [`MessageType`] to network bytes
    pub fn to_bytes(self) -> Vec<u8> {
        let mut ret = vec![0; 2];
        BigEndian::write_u16(&mut ret[0..2], self.0);
        ret
    }

    /// Convert a set of network bytes into a [`MessageType`] or return an error
    pub fn from_bytes(data: &[u8]) -> Result<Self, StunError> {
        let data = BigEndian::read_u16(data);
        if data & 0xc000 != 0x0 {
            /* not a stun packet */
            return Err(StunError::ParseError(StunParseError::WrongImplementation));
        }
        Ok(Self(data))
    }
}
impl From<MessageType> for Vec<u8> {
    fn from(f: MessageType) -> Self {
        f.to_bytes()
    }
}
impl TryFrom<&[u8]> for MessageType {
    type Error = StunError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        MessageType::from_bytes(value)
    }
}

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct TransactionId {
    id: u128,
}

impl From<u128> for TransactionId {
    fn from(id: u128) -> Self {
        Self {
            id: id & 0xffff_ffff_ffff_ffff_ffff_ffff,
        }
    }
}
impl From<TransactionId> for u128 {
    fn from(id: TransactionId) -> Self {
        id.id
    }
}
impl std::fmt::Display for TransactionId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:#x}", self.id)
    }
}

/// The structure that encapsulates the entirety of a STUN message
///
/// Contains the [`MessageType`], a transaction ID, and a list of STUN
/// [`Attribute`](crate::stun::attribute::Attribute)s.
#[derive(Debug, Clone)]
pub struct Message {
    msg_type: MessageType,
    transaction: TransactionId,
    attributes: Vec<RawAttribute>,
}

impl std::fmt::Display for Message {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Message(class: {:?}, method: {} ({:#x}), transaction: {}, attributes: ",
            self.get_type().class(),
            self.get_type().method(),
            self.get_type().method(),
            self.transaction_id()
        )?;
        if self.attributes.is_empty() {
            write!(f, "[]")?;
        } else {
            write!(f, "[")?;
            for (i, a) in self.attributes.iter().enumerate() {
                if i > 0 {
                    write!(f, ", ")?;
                }
                write!(f, "{}", a)?;
            }
            write!(f, "]")?;
        }
        write!(f, ")")
    }
}

fn padded_attr_size(attr: &RawAttribute) -> usize {
    if attr.length() % 4 == 0 {
        4 + attr.length() as usize
    } else {
        8 + attr.length() as usize - attr.length() as usize % 4
    }
}

impl Message {
    /// Create a new [`Message`] with the provided [`MessageType`] and transaction ID
    ///
    /// Note you probably want to use one of the other helper constructors instead.
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
    /// let message = Message::new(mtype, 0.into());
    /// assert!(message.has_class(MessageClass::Indication));
    /// assert!(message.has_method(BINDING));
    /// ```
    pub fn new(mtype: MessageType, transaction: TransactionId) -> Self {
        Self {
            msg_type: mtype,
            transaction,
            attributes: vec![],
        }
    }

    /// Create a new request [`Message`] of the provided method
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// assert!(message.has_class(MessageClass::Request));
    /// assert!(message.has_method(BINDING));
    /// ```
    pub fn new_request(method: u16) -> Self {
        Message::new(
            MessageType::from_class_method(MessageClass::Request, method),
            Message::generate_transaction(),
        )
    }

    /// Create a new success [`Message`] response from the provided request
    ///
    /// # Panics
    ///
    /// When a non-request [`Message`] is passed as the original input [`Message`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// let success = Message::new_success(&message);
    /// assert!(success.has_class(MessageClass::Success));
    /// assert!(success.has_method(BINDING));
    /// ```
    pub fn new_success(orig: &Message) -> Self {
        if !orig.has_class(MessageClass::Request) {
            panic!(
                "A success response message was attempted to be created from a non-request message"
            );
        }
        Message::new(
            MessageType::from_class_method(MessageClass::Success, orig.method()),
            orig.transaction_id(),
        )
    }

    /// Create a new error [`Message`] response from the provided request
    ///
    /// # Panics
    ///
    /// When a non-request [`Message`] is passed as the original input [`Message`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// let success = Message::new_error(&message);
    /// assert!(success.has_class(MessageClass::Error));
    /// assert!(success.has_method(BINDING));
    /// ```
    pub fn new_error(orig: &Message) -> Self {
        Message::new(
            MessageType::from_class_method(MessageClass::Error, orig.method()),
            orig.transaction_id(),
        )
    }

    /// Retrieve the [`MessageType`] of a [`Message`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// assert!(message.get_type().has_class(MessageClass::Request));
    /// assert!(message.get_type().has_method(BINDING));
    /// ```
    pub fn get_type(&self) -> MessageType {
        self.msg_type
    }

    /// Retrieve the [`MessageClass`] of a [`Message`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// assert_eq!(message.class(), MessageClass::Request);
    /// ```
    pub fn class(&self) -> MessageClass {
        self.get_type().class()
    }

    /// Returns whether the [`Message`] is of the specified [`MessageClass`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// assert!(message.has_class(MessageClass::Request));
    /// ```
    pub fn has_class(&self, cls: MessageClass) -> bool {
        self.class() == cls
    }

    /// Returns whether the [`Message`] is a response
    ///
    /// This means that the [`Message`] has a class of either success or error
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// assert_eq!(message.is_response(), false);
    ///
    /// let error = Message::new_error(&message);
    /// assert_eq!(error.is_response(), true);
    ///
    /// let success = Message::new_success(&message);
    /// assert_eq!(success.is_response(), true);
    /// ```
    pub fn is_response(&self) -> bool {
        self.class().is_response()
    }

    /// Retrieves the method of the [`Message`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::message::{Message, MessageType, MessageClass, BINDING};
    /// let message = Message::new_request(BINDING);
    /// assert_eq!(message.method(), BINDING);
    /// ```
    pub fn method(&self) -> u16 {
        self.get_type().method()
    }

Returns whether the method of a MessageType is equal to the provided value

Examples
let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
assert_eq!(mtype.has_method(BINDING), true);

Convert a MessageType to network bytes

Examples found in repository?
src/stun/message.rs (line 240)
239
240
241
    fn from(f: MessageType) -> Self {
        f.to_bytes()
    }

Convert a set of network bytes into a MessageType or return an error

Examples found in repository?
src/stun/message.rs (line 247)
246
247
248
    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        MessageType::from_bytes(value)
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Formats the value using the given formatter. Read more
Converts to this type from the input type.
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
The type returned in the event of a conversion error.
Performs the conversion.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more