Skip to content

Instantly share code, notes, and snippets.

@10maurycy10
Last active February 16, 2022 00:27
Show Gist options
  • Save 10maurycy10/01a0380f172eda516a84c91160ee2c95 to your computer and use it in GitHub Desktop.
Save 10maurycy10/01a0380f172eda516a84c91160ee2c95 to your computer and use it in GitHub Desktop.
Shim to use nom parser with tokio codec.
// Change packet to your parsers result type
/// Shim to use the parser with tokio codec.
pub struct Shim {}
impl Shim {
pub fn new() -> Proto {
Proto {}
}
}
impl Decoder for Shim {
type Item = Packet;
type Error = anyhow::Error;
// Err(e) -> decoding failed
// Ok(Some(msg)) -> decoding worked
// Ok(None) -> not enough data
fn decode(&mut self,src: &mut BytesMut) -> Result<Option<Self::Item>, anyhow::Error> {
// Change this to your parser
match parse_packet(src) {
Ok((i, msg)) => {
src.advance(src.len() - i.len());
Ok(Some(msg))
},
Err(e) => {
use nom::Err as NomErr;
let e = e.to_owned();
match e {
NomErr::Error(_) => Err(e.into()),
NomErr::Failure(_) => Err(e.into()),
NomErr::Incomplete(_) => Ok(None)
}
},
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment