-
The bigger question is the best way to read in a binary stream, decode/parse the data into it's individual parts. I'm using a combination of tokio::TcpStream and BytesCodec. I think the next approach is to use binrw to parse the data. Eventually, I could incorporate that into a custom Codec, but I'm not there yet. I'm having trouble figuring out how to add the binrw to the chain. As I'm learning Rust, I'm getting turned around on the various constructs for streams, io, traits, etc. Looking for help on finishing the problem, or maybe I'm approaching this all wrong in the first place. NOTE: I recognize there needs to be an accommodation to handle the async part of the problem. async fn process(stream: TcpStream, iqpub: jetstream::Context) -> Result<(), Box<dyn Error>> {
// create a framed codec for the stream. Converts each block to a message as determined by the codec
let mut framed = BytesCodec::new().framed(stream);
// while more messages
while let Some(message) = framed.next().await {
let buf = message.freeze();
let vpacket = get_iq_packet(buf); //how do I implement this function?
} And the parser: #[binrw(little)]
pub struct VitaIQ {
#[bw(try_calc(u16::try_from(payload.len() + 28)))] // set size of packet based on payload
/* 2B B0-2 */ size : u16,
/* 2B B3-4 */ header : u16,
/* 2B B5-6 */ stream_id : u32,
/* 8B B7-14 */ class_id : u32,
/* 2B B11-12 */ timestamp_int : u32,
/* 2B B13-16 */ timestamp_frac : u64,
#[br(count = size-28)]
/* ** B17... */ payload : Vec<u32>,
/* 4B B*+4 */ trailer : u32,
}
pub fn get_iq_packet(bytes: Bytes) -> Result() {
???
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
minor heads up, you can tell markdown what language your code block contains, and then github will syntax highlight it for you. (I edited your original post, you can click the edit button to observe how that was done) onto the actual question: what I think you're asking is "Given a set of bytes in memory, how can I tell binrw to parse it?" Your friend here is From there, you can use one of the methods on BinRead or one of the methods on BinReaderExt to read the bytes into your struct. As a side note: what units is your |
Beta Was this translation helpful? Give feedback.
minor heads up, you can tell markdown what language your code block contains, and then github will syntax highlight it for you. (I edited your original post, you can click the edit button to observe how that was done)
onto the actual question: what I think you're asking is "Given a set of bytes in memory, how can I tell binrw to parse it?" Your friend here is
std::io::Cursor
, which wraps byte-like objects (slices, arrays, vectors) and implements io::Read/Seek/Write, as applicable. That's either going to beCursor::new(bytes)
,Cursor::new(&bytes)
,Cursor::new(bytes.as_slice())
, or something similar. (If you're in a no_std environment, binrw provides a polyfill in thebinrw::io
module.)Fro…