use reliakit_codec::{decode_from_slice_exact, encode_to_vec, CodecErrorKind};
use reliakit_derive::{CanonicalDecode, CanonicalEncode};
#[derive(Debug, PartialEq, CanonicalEncode, CanonicalDecode)]
struct Header {
version: u8,
request_id: u32,
}
#[derive(Debug, PartialEq, CanonicalEncode, CanonicalDecode)]
enum Frame {
Ping,
SetName(String),
Connect { header: Header, port: u16 },
}
fn main() {
let frames = [
Frame::Ping,
Frame::SetName("router-1".to_string()),
Frame::Connect {
header: Header {
version: 1,
request_id: 42,
},
port: 8080,
},
];
for frame in &frames {
let bytes = encode_to_vec(frame).expect("encode");
let decoded = decode_from_slice_exact::<Frame>(&bytes).expect("decode");
println!("{frame:?}");
println!(" encoded ({} bytes): {bytes:02x?}", bytes.len());
println!(" decoded: {decoded:?}");
assert_eq!(&decoded, frame, "round-trip must be lossless");
}
assert_eq!(encode_to_vec(&Frame::Ping).unwrap(), [0, 0, 0, 0]);
let err = decode_from_slice_exact::<Frame>(&[9, 0, 0, 0]).unwrap_err();
assert_eq!(err.kind(), CodecErrorKind::InvalidValue);
println!("unknown tag rejected: {}", err.message());
println!("all frames round-tripped");
}