feat(users/Profpatsch/netencode): add dec::Try

Tries to decode the inner type, turning it into an Option.

Change-Id: I29d1286fe873c28d7c4a4b71f220acaf2d23f8e1
Reviewed-on: https://cl.tvl.fyi/c/depot/+/2522
Tested-by: BuildkiteCI
Reviewed-by: Profpatsch <mail@profpatsch.de>
This commit is contained in:
Profpatsch 2021-02-13 14:23:29 +01:00
parent 1b706b5ae3
commit 1d752f031b

View file

@ -758,11 +758,19 @@ pub mod dec {
}
}
fn dec_u(b: &[u8]) -> Result<U, DecodeError> {
match parse::u_u(b) {
Ok((b"", u)) => Ok(u),
Ok((rest, _)) => Err(DecodeError(format!("Cannot decode nested U, it contains trailing bytes"))),
Err(err) => Err(DecodeError(format!("Cannot decode nested U bytes: {:?}", err))),
#[derive(Clone)]
pub struct Try<T>(pub T);
impl <'a, Inner> Decoder<'a> for Try<Inner>
where Inner: Decoder<'a>
{
type A = Option<Inner::A>;
fn dec(&self, u: U<'a>) -> Result<Self::A, DecodeError> {
match self.0.dec(u) {
Ok(inner) => Ok(Some(inner)),
Err(err) => Ok(None)
}
}
}
}