Last active
February 16, 2022 00:27
-
-
Save 10maurycy10/01a0380f172eda516a84c91160ee2c95 to your computer and use it in GitHub Desktop.
Shim to use nom parser with tokio codec.
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
// 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