connection-utils 0.8.0

Connection related utilities.
Documentation
use serde::{Serialize, Deserialize};
use std::{fmt::{Debug, self}, cmp::Ordering};
use cs_utils::{random_number, traits::Random, random_str, random_str_rg};

/// A test message for framed stream testing purposes.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub enum TestStreamMessage {
    Ping(String),
    Pong(Option<String>, String),
    Data(Vec<u8>),
    Eof,
}

impl fmt::Display for TestStreamMessage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TestStreamMessage::Ping(id) => {
                return f.debug_tuple("TestStreamMessage::Ping")
                    .field(id)
                    .finish();
            },
            TestStreamMessage::Pong(data, id) => {
                return f.debug_tuple("TestStreamMessage::Pong")
                    .field(id)
                    .field(data)
                    .finish();
            },
            TestStreamMessage::Data(data) => {
                return f.debug_tuple("TestStreamMessage::Data")
                    .field(&data.len())
                    .finish();
            },
            TestStreamMessage::Eof => {
                return f.debug_tuple("TestStreamMessage::Eof")
                    .finish();
            },
        };
    }
}

impl TestStreamMessage {
    fn compare(&self, other: &TestStreamMessage) -> Ordering {
        let self_str = format!("{:?}", self);
        let other_str = format!("{:?}", other);

        if self_str < other_str {
            return Ordering::Less;
        }

        if self_str > other_str {
            return Ordering::Greater;
        }

        return Ordering::Equal;
    }
}

impl PartialOrd for TestStreamMessage {
    fn partial_cmp(&self, other: &TestStreamMessage) -> Option<Ordering> {
        return Some(self.compare(other));
    }
}

impl Ord for TestStreamMessage {
    fn cmp(&self, other: &TestStreamMessage) -> Ordering {
        return self.compare(other);
    }
}

impl Random for TestStreamMessage {
    fn random() -> TestStreamMessage {
        return match random_number(0..=u16::MAX) % 4 {
            0 => TestStreamMessage::Ping(random_str_rg(16..=32)),
            1 => TestStreamMessage::Pong(Some(random_str(32)), random_str_rg(32..=64)),
            2 => TestStreamMessage::Data(random_str_rg(8..=256).as_bytes().to_vec()),
            3 => TestStreamMessage::Eof,
            _ => unreachable!(),
        };
    }
}