xio_common 0.5.0

XIO commonly used functionality
Documentation
extern crate uuid;

use self::uuid::{Uuid, UuidBytes};
use std::io;
use std::mem::size_of;

pub(crate) trait WithFixedPayloadLength {
    const FIXED_PAYLOAD_LENGTH: u16;

    fn verify_payload_length(
        payload_length: u16,
        msg_type: &str,
    ) -> io::Result<()> {
        if payload_length != Self::FIXED_PAYLOAD_LENGTH {
            Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "Invalid {} payload length. Received {}, required {}.\n\
                     Dismissing remaining data",
                    msg_type,
                    payload_length,
                    Self::FIXED_PAYLOAD_LENGTH
                ),
            ))
        } else {
            Ok(())
        }
    }
}

impl WithFixedPayloadLength for bool {
    const FIXED_PAYLOAD_LENGTH: u16 = size_of::<bool>() as u16;
}

impl WithFixedPayloadLength for i8 {
    const FIXED_PAYLOAD_LENGTH: u16 = size_of::<i8>() as u16;
}

impl WithFixedPayloadLength for i16 {
    const FIXED_PAYLOAD_LENGTH: u16 = size_of::<i16>() as u16;
}

impl WithFixedPayloadLength for i32 {
    const FIXED_PAYLOAD_LENGTH: u16 = size_of::<i32>() as u16;
}

impl WithFixedPayloadLength for i64 {
    const FIXED_PAYLOAD_LENGTH: u16 = size_of::<i64>() as u16;
}

impl WithFixedPayloadLength for u8 {
    const FIXED_PAYLOAD_LENGTH: u16 = size_of::<u8>() as u16;
}

impl WithFixedPayloadLength for u16 {
    const FIXED_PAYLOAD_LENGTH: u16 = size_of::<u16>() as u16;
}

impl WithFixedPayloadLength for u32 {
    const FIXED_PAYLOAD_LENGTH: u16 = size_of::<u32>() as u16;
}

impl WithFixedPayloadLength for u64 {
    const FIXED_PAYLOAD_LENGTH: u16 = size_of::<u64>() as u16;
}

impl WithFixedPayloadLength for Uuid {
    const FIXED_PAYLOAD_LENGTH: u16 = size_of::<UuidBytes>() as u16;
}

#[cfg(test)]
mod tests {
    use super::{Uuid, WithFixedPayloadLength};
    #[test]
    fn test() {
        assert_eq!(bool::FIXED_PAYLOAD_LENGTH, 1u16);
        assert_eq!(i8::FIXED_PAYLOAD_LENGTH, 1u16);
        assert_eq!(i16::FIXED_PAYLOAD_LENGTH, 2u16);
        assert_eq!(i32::FIXED_PAYLOAD_LENGTH, 4u16);
        assert_eq!(i64::FIXED_PAYLOAD_LENGTH, 8u16);
        assert_eq!(u8::FIXED_PAYLOAD_LENGTH, 1u16);
        assert_eq!(u16::FIXED_PAYLOAD_LENGTH, 2u16);
        assert_eq!(u32::FIXED_PAYLOAD_LENGTH, 4u16);
        assert_eq!(u64::FIXED_PAYLOAD_LENGTH, 8u16);
        assert_eq!(Uuid::FIXED_PAYLOAD_LENGTH, 16u16);
    }
}