-
-
Save rust-play/3a8121101770f0ee5e76847fccf8f684 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I'm looking to implement a parser for the following type of streaming | |
// and framed data | |
// | |
// message format | |
// ====================================== | |
// [ | |
// STX : 0x02 as u8, | |
// SYNC: 0x55 as u8, | |
// LEN : N as u8 | |
// PAYL: N bytes | |
// ETX : 0x03 as u8 | |
// ] | |
// | |
// Where the PAYL bytes are stuffed as follows: | |
// - Following every occurance of 0x02 in the packet (other than initial STX) | |
// an extra 0x00 byte is added to the data | |
// - Stuffed 0x00 byte is removed | |
// - Length does not include stuffed bytes | |
// | |
// This data is coming in from a serial port unaligned, such as: | |
// | |
// ringbuffer = spsc::Queue(); | |
// let (producer, consumer) = ringbuffer.split(); | |
// | |
// pub fn receiver_thread() { | |
// loop { | |
// SERIAL_PORT.read(&mut producer); | |
// } | |
// } | |
pub fn deframe() { | |
// Continue decoding messages from the consumer | |
// buffer until Pending or Error | |
loop { | |
let msg = decode(&mut consumer); // IResult<Frame>? Poll type? | |
match msg { | |
Ok(frame) => handle(frame), // <-- do something with frame | |
Ok(Pending) => break, // <-- return later and try again | |
Err(e) => break, // <-- do something with error | |
} | |
} | |
} | |
pub struct ByteDestuffer { | |
pub fn next() -> Poll(Result) | |
} | |
pub fn decode(buf: &mut consumer) -> IResult/Poll { | |
// Behavior: | |
// - should drop data from "buf" as long as it doesn't | |
// start with the sync sequence. | |
let sync = drop_until(&mut buf, [0x02, 0x055])?; | |
// After we have found the sync pattern | |
// all bytes should be passed through destuffer until next frame sync | |
let destuffer = ByteDestuffer::new(&mut buf); | |
let len = take(destuffer, 1)?; | |
let payl = take(destuffer, len)?; | |
let etx = take(destuffer, 1)?; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, this is just pseudo-code above.
It seems like this type of streaming/deframing decoder should already exist in other forms. I'm wondering if others have ideas for how other libraries/applications have structured this type of problem.