fn encode()

in mqtt/mqtt3/src/proto/packet.rs [254:335]


    fn encode<B>(&self, dst: &mut B) -> Result<(), super::EncodeError>
    where
        B: ByteBuf,
    {
        let Connect {
            username,
            password,
            will,
            client_id,
            keep_alive,
            protocol_name,
            protocol_level,
        } = self;

        super::encode_utf8_str(protocol_name, dst)?;

        dst.put_u8_bytes(*protocol_level);

        {
            let mut connect_flags = 0x00_u8;
            if username.is_some() {
                connect_flags |= 0x80;
            }
            if password.is_some() {
                connect_flags |= 0x40;
            }
            if let Some(will) = &will {
                if will.retain {
                    connect_flags |= 0x20;
                }
                connect_flags |= match will.qos {
                    QoS::AtMostOnce => 0x00,
                    QoS::AtLeastOnce => 0x08,
                    QoS::ExactlyOnce => 0x10,
                };
                connect_flags |= 0x04;
            }
            match client_id {
                super::ClientId::ServerGenerated | super::ClientId::IdWithCleanSession(_) => {
                    connect_flags |= 0x02;
                }
                super::ClientId::IdWithExistingSession(_) => (),
            }
            dst.put_u8_bytes(connect_flags);
        }

        dst.put_u16_bytes(
            keep_alive
                .as_secs()
                .try_into()
                .map_err(|_| super::EncodeError::KeepAliveTooHigh(*keep_alive))?,
        );

        match client_id {
            super::ClientId::ServerGenerated => super::encode_utf8_str("", dst)?,
            super::ClientId::IdWithCleanSession(id)
            | super::ClientId::IdWithExistingSession(id) => super::encode_utf8_str(id, dst)?,
        }

        if let Some(will) = will {
            super::encode_utf8_str(&will.topic_name, dst)?;

            let will_len = will.payload.len();
            dst.put_u16_bytes(
                will_len
                    .try_into()
                    .map_err(|_| super::EncodeError::WillTooLarge(will_len))?,
            );

            dst.put_slice_bytes(&will.payload);
        }

        if let Some(username) = username {
            super::encode_utf8_str(username, dst)?;
        }

        if let Some(password) = password {
            super::encode_utf8_str(password, dst)?;
        }

        Ok(())
    }