#encoder

stun_codec_blazh

fork from stun_codec

1 unstable release

0.1.13 Feb 19, 2022

#2030 in Encoding

Download history 5674/week @ 2024-07-26 7234/week @ 2024-08-02 6701/week @ 2024-08-09 6202/week @ 2024-08-16 5550/week @ 2024-08-23 4966/week @ 2024-08-30 6024/week @ 2024-09-06 6571/week @ 2024-09-13 6386/week @ 2024-09-20 5428/week @ 2024-09-27 7164/week @ 2024-10-04 7700/week @ 2024-10-11 7897/week @ 2024-10-18 8054/week @ 2024-10-25 4261/week @ 2024-11-01 5726/week @ 2024-11-08

27,565 downloads per month
Used in nat-detect

MIT license

155KB
3.5K SLoC

fork from stun_codec


lib.rs:

Encoders and decoders for STUN (RFC 5389) and its extensions.

Examples

use bytecodec::{DecodeExt, EncodeExt, Error};
use stun_codec::{Message, MessageClass, MessageDecoder, MessageEncoder, TransactionId};
use stun_codec::rfc5389::{attributes::Software, methods::BINDING, Attribute};

// Creates a message
let mut message = Message::new(MessageClass::Request, BINDING, TransactionId::new([3; 12]));
message.add_attribute(Attribute::Software(Software::new("foo".to_owned())?));

// Encodes the message
let mut encoder = MessageEncoder::new();
let bytes = encoder.encode_into_bytes(message.clone())?;
assert_eq!(
    bytes,
    [
        0, 1, 0, 8, 33, 18, 164, 66, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 128, 34, 0, 3,
        102, 111, 111, 0
    ]
);

// Decodes the message
let mut decoder = MessageDecoder::<Attribute>::new();
let decoded = decoder.decode_from_bytes(&bytes)?.map_err(Error::from)?;
assert_eq!(decoded.class(), message.class());
assert_eq!(decoded.method(), message.method());
assert_eq!(decoded.transaction_id(), message.transaction_id());
assert!(decoded.attributes().eq(message.attributes()));

Define your own attribute enum

By using define_attribute_enums! macro, you can easily define an enum that includes arbitrary attributes.

The following is an example taken from rusturn crate:

#[macro_use] extern crate trackable;

use stun_codec::define_attribute_enums;
use stun_codec::rfc5389::attributes::*;
use stun_codec::rfc5766::attributes::*;

define_attribute_enums!(
    Attribute, AttributeDecoder, AttributeEncoder,
    [
        // RFC 5389
        MappedAddress, Username, MessageIntegrity, ErrorCode,
        UnknownAttributes, Realm, Nonce, XorMappedAddress,
        Software, AlternateServer, Fingerprint,

        // RFC 5766
        ChannelNumber, Lifetime, XorPeerAddress, Data,
        XorRelayAddress, EvenPort, RequestedTransport,
        DontFragment, ReservationToken
    ]
);

References

Dependencies

~2MB
~47K SLoC