extern crate uuid;
use self::uuid::{Bytes, Uuid};
use snafu::ensure;
use std::mem::size_of;
use crate::{error, Result};
pub(crate) trait WithFixedPayloadLength {
const FIXED_PAYLOAD_LENGTH: u16;
fn verify_payload_length(
payload_length: u16,
message_type: &'static str,
) -> Result<()> {
ensure!(
payload_length == Self::FIXED_PAYLOAD_LENGTH,
error::InvalidPayloadLength {
message_type,
received: payload_length,
required: Self::FIXED_PAYLOAD_LENGTH
}
);
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::<Bytes>() 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);
}
}