unsigned_varint/
nom.rs

1// Copyright (c) 2020 Aleksa Sarai <cyphar@cyphar.com>
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy of
4// this software and associated documentation files (the "Software"), to deal in
5// the Software without restriction, including without limitation the rights to
6// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7// the Software, and to permit persons to whom the Software is furnished to do so,
8// subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
16// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
17// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
20//! `nom` combinators to decode unsigned varints.
21
22use crate::decode::{self, Error};
23use nom::{error::ErrorKind, Err as NomErr, IResult, Needed};
24
25macro_rules! gen {
26    ($($type:ident, $d:expr);*) => {
27        $(
28            #[doc = " `nom` combinator to decode a variable-length encoded "]
29            #[doc = $d]
30            #[doc = "."]
31            pub fn $type(input: &[u8]) -> IResult<&[u8], $type, (&[u8], ErrorKind)> {
32                let (n, remain) = decode::$type(input).map_err(|err| match err {
33                    Error::Insufficient => NomErr::Incomplete(Needed::Unknown),
34                    Error::Overflow => NomErr::Error((input, ErrorKind::TooLarge)),
35                    Error::NotMinimal => NomErr::Error((input, ErrorKind::Verify)),
36                })?;
37                Ok((remain, n))
38            }
39        )*
40    }
41}
42
43gen! {
44    u8,    "`u8`";
45    u16,   "`u16`";
46    u32,   "`u32`";
47    u64,   "`u64`";
48    u128,  "`u128`";
49    usize, "`usize`"
50}