use bytes::{BufMut, Bytes, BytesMut}; use tokio_hglib::codec::{ChannelDecoder, ChannelMessage}; use tokio_util::codec::Decoder; #[test] fn channel_decode_valid_message() { assert_eq!( Some(ChannelMessage::Data(b'o', Bytes::new())), decode_one(b"o\0\0\0\0") ); assert_eq!( Some(ChannelMessage::Data(b'o', Bytes::from(b"foo".as_ref()))), decode_one(b"o\0\0\0\x03foo") ); assert_eq!( Some(ChannelMessage::Data(b'e', Bytes::from(b"foo".as_ref()))), decode_one(b"e\0\0\0\x03foo") ); assert_eq!( Some(ChannelMessage::Data( b'r', Bytes::from(b"\0\0\0\0".as_ref()) )), decode_one(b"r\0\0\0\x04\0\0\0\0") ); assert_eq!( Some(ChannelMessage::InputRequest(0xdeadbeef)), decode_one(b"I\xde\xad\xbe\xef") ); assert_eq!( Some(ChannelMessage::LineRequest(0xdeadbeef)), decode_one(b"L\xde\xad\xbe\xef") ); assert_eq!( Some(ChannelMessage::SystemRequest(Bytes::from(b"foo".as_ref()))), decode_one(b"S\0\0\0\x03foo") ); } #[test] fn channel_decode_unsupported() { let mut codec = ChannelDecoder::new(); assert!(codec .decode(&mut BytesMut::from(b"X\0\0\0\0".as_ref())) .is_err()); } #[test] fn channel_decode_immature() { let mut codec = ChannelDecoder::new(); let mut src = BytesMut::with_capacity(100); assert_eq!(None, codec.decode(&mut src).unwrap()); src.put_slice(b"o\0\0\0"); assert_eq!(None, codec.decode(&mut src).unwrap()); src.put_slice(b"\0"); assert_eq!( Some(ChannelMessage::Data(b'o', Bytes::new())), codec.decode(&mut src).unwrap() ); // read data/input requests one by one assert_eq!(None, codec.decode(&mut src).unwrap()); src.put_slice(b"e\0\0\0\x03"); assert_eq!(None, codec.decode(&mut src).unwrap()); src.put_slice(b"fooI\xde\xad\xbe\xef"); assert_eq!( Some(ChannelMessage::Data(b'e', Bytes::from(b"foo".as_ref()))), codec.decode(&mut src).unwrap() ); assert_eq!( Some(ChannelMessage::InputRequest(0xdeadbeef)), codec.decode(&mut src).unwrap() ); assert!(src.is_empty()); // input request with data src.put_slice(b"S\0\0\0\x03"); assert_eq!(None, codec.decode(&mut src).unwrap()); src.put_slice(b"fo"); assert_eq!(None, codec.decode(&mut src).unwrap()); src.put_slice(b"o"); assert_eq!( Some(ChannelMessage::SystemRequest(Bytes::from(b"foo".as_ref()))), codec.decode(&mut src).unwrap() ); assert!(src.is_empty()); } fn decode_one>(s: S) -> Option { let mut codec = ChannelDecoder::new(); codec.decode(&mut BytesMut::from(s.as_ref())).unwrap() }