use byteable::Byteable;
use byteable::io::{ReadValue, ReadableError, WriteValue};
use std::io::Cursor;
#[derive(Debug, PartialEq, Byteable)]
#[byteable(discriminant = u8)]
enum Message {
#[byteable(tag = 0x01)]
Ping,
#[byteable(tag = 0x02)]
Pong,
#[byteable(tag = 0x10)]
Subscribe { topic: String },
#[byteable(tag = 0x11)]
Publish { topic: String, payload: Vec<u8> },
#[byteable(tag = 0xFF)]
Error {
#[byteable(big_endian)]
code: u16,
description: String,
},
}
fn main() -> Result<(), ReadableError> {
let outgoing = vec![
Message::Ping,
Message::Subscribe {
topic: "sensors/temperature".into(),
},
Message::Publish {
topic: "sensors/temperature".into(),
payload: vec![0x41, 0x20, 0x00, 0x00], },
Message::Pong,
Message::Error {
code: 403,
description: "not authorized".into(),
},
];
let mut stream = Cursor::new(Vec::<u8>::new());
stream.write_value(&outgoing)?;
println!(
"Encoded {} messages into {} bytes\n",
outgoing.len(),
stream.position()
);
stream.set_position(0);
let received: Vec<Message> = stream.read_value()?;
for msg in &received {
match msg {
Message::Ping => println!("→ Ping"),
Message::Pong => println!("→ Pong"),
Message::Subscribe { topic } => println!("→ Subscribe({topic})"),
Message::Publish { topic, payload } => {
println!("→ Publish({topic}, {} bytes)", payload.len())
}
Message::Error { code, description } => {
println!("→ Error({code}: {description})")
}
}
}
assert_eq!(outgoing, received);
println!(
"\nAll {} messages round-tripped successfully.",
received.len()
);
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn main() {
super::main().unwrap();
}
}