use std::fmt;
use colored::Colorize;
bitflags::bitflags! {
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
pub struct ConnectionParams: u8 {
const NONE = 0b0000_0000;
const COMPRESSED = 0b0000_0001;
const ENCRYPTED = 0b0000_0010;
const ENCODED = 0b0000_0100;
const SIGNATURE = 0b0000_1000;
const OPTIMIZED = 0b0000_1111; const INSECURE = 0b0001_0000;
}
}
impl ConnectionParams {
pub fn expect(&self, val: ConnectionParams) -> bool {
*self == val
}
}
impl fmt::Display for ConnectionParams {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut flags = vec![];
if self.contains(ConnectionParams::COMPRESSED) {
flags.push("Compressed".cyan().to_string());
}
if self.contains(ConnectionParams::ENCRYPTED) {
flags.push("Encrypted".magenta().to_string());
}
if self.contains(ConnectionParams::ENCODED) {
flags.push("Encoded".blue().to_string());
}
if self.contains(ConnectionParams::SIGNATURE) {
flags.push("Signed".yellow().to_string());
}
if self.contains(ConnectionParams::OPTIMIZED) {
flags.push("SECURE".bright_green().bold().to_string());
}
if self.contains(ConnectionParams::INSECURE) {
flags.push("INSECURE".bright_red().bold().to_string());
}
write!(f, "{}", flags.join(", "))
}
}
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum MsgType {
Hello = 0,
HelloAck = 1,
Open = 2,
OpenAck = 3,
Data = 4,
Heartbeat = 5,
Close = 6,
Error = 7,
Rekey = 8,
Unknown = 255,
}
impl From<u8> for MsgType {
fn from(b: u8) -> Self {
match b {
0 => MsgType::Hello,
1 => MsgType::HelloAck,
2 => MsgType::Open,
3 => MsgType::OpenAck,
4 => MsgType::Data,
5 => MsgType::Heartbeat,
6 => MsgType::Close,
7 => MsgType::Error,
8 => MsgType::Rekey,
_ => MsgType::Unknown,
}
}
}
impl From<MsgType> for u8 {
fn from(t: MsgType) -> u8 {
t as u8
}
}
impl MsgType {
pub fn bits(self) -> u8 {
self.into()
}
}
#[cfg(test)]
mod msg_type_tests {
use super::MsgType;
#[test]
fn msg_type_bits_roundtrip() {
let variants = [
MsgType::Hello,
MsgType::HelloAck,
MsgType::Open,
MsgType::OpenAck,
MsgType::Data,
MsgType::Heartbeat,
MsgType::Close,
MsgType::Error,
MsgType::Rekey,
];
for v in variants {
assert_eq!(MsgType::from(v.bits()), v);
}
assert_eq!(MsgType::from(254u8), MsgType::Unknown);
}
}