{"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "expression_ast.rs", "content": "use nom::{\n branch::alt,\n bytes::complete::tag,\n character::complete::{alphanumeric1 as alphanumeric, digit1 as digit},\n combinator::{map, map_res},\n multi::separated_list0,\n sequence::delimited,\n IResult, Parser,\n};\nuse nom_language::precedence::{binary_op, precedence, unary_op, Assoc, Operation};\n\n// Elements of the abstract syntax tree (ast) that represents an expression.\n#[derive(Debug)]\npub enum Expr {\n // A number literal.\n Num(i64),\n // An identifier.\n Iden(String),\n // Arithmetic operations. Each have a left hand side (lhs) and a right hand side (rhs).\n Add(Box, Box),\n Sub(Box, Box),\n Mul(Box, Box),\n Div(Box, Box),\n // The function call operation. Left is the expression the function is called on, right is the list of parameters.\n Call(Box, Vec),\n // The ternary operator, the expressions from left to right are: The condition, the true case, the false case.\n Tern(Box, Box, Box),\n}\n\n// Prefix operators.\nenum PrefixOp {\n Identity, // +\n Negate, // -\n}\n\n// Postfix operators.\nenum PostfixOp {\n // The function call operator. In addition to its own representation \"()\" it carries additional information that we need to keep here.\n // Specifically the vector of expressions that make up the parameters.\n Call(Vec), // ()\n}\n\n// Binary operators.\nenum BinaryOp {\n Addition, // +\n Subtraction, // -\n Multiplication, // *\n Division, // /\n // The ternary operator can contain a single expression.\n Ternary(Expr), // ?:\n}\n\n// Parser for function calls.\nfn function_call(i: &str) -> IResult<&str, PostfixOp> {\n map(\n delimited(\n tag(\"(\"),\n // Subexpressions are evaluated by recursing back into the expression parser.\n separated_list0(tag(\",\"), expression),\n tag(\")\"),\n ),\n |v: Vec| PostfixOp::Call(v),\n )\n .parse(i)\n}\n\n// The ternary operator is actually just a binary operator that contains another expression. So it can be\n// handled similarly to the function call operator except its in a binary position and can only contain\n// a single expression.\n//\n// For example the expression \"a IResult<&str, BinaryOp> {\n map(delimited(tag(\"?\"), expression, tag(\":\")), |e: Expr| {\n BinaryOp::Ternary(e)\n })\n .parse(i)\n}\n\n// The actual expression parser .\nfn expression(i: &str) -> IResult<&str, Expr> {\n precedence(\n alt((\n unary_op(2, map(tag(\"+\"), |_| PrefixOp::Identity)),\n unary_op(2, map(tag(\"-\"), |_| PrefixOp::Negate)),\n )),\n // Function calls are implemented as postfix unary operators.\n unary_op(1, function_call),\n alt((\n binary_op(\n 3,\n Assoc::Left,\n alt((\n map(tag(\"*\"), |_| BinaryOp::Multiplication),\n map(tag(\"/\"), |_| BinaryOp::Division),\n )),\n ),\n binary_op(\n 4,\n Assoc::Left,\n alt((\n map(tag(\"+\"), |_| BinaryOp::Addition),\n map(tag(\"-\"), |_| BinaryOp::Subtraction),\n )),\n ),\n // Ternary operators are just binary operators with a subexpression.\n binary_op(5, Assoc::Right, ternary_operator),\n )),\n alt((\n map_res(digit, |s: &str| match s.parse::() {\n Ok(s) => Ok(Expr::Num(s)),\n Err(e) => Err(e),\n }),\n map(alphanumeric, |s: &str| Expr::Iden(s.to_string())),\n delimited(tag(\"(\"), expression, tag(\")\")),\n )),\n |op: Operation| -> Result {\n use nom_language::precedence::Operation::*;\n use BinaryOp::*;\n use PostfixOp::*;\n use PrefixOp::*;\n match op {\n // The identity operator (prefix +) is ignored.\n Prefix(Identity, e) => Ok(e),\n\n // Unary minus gets evaluated to the same representation as a multiplication with -1.\n Prefix(Negate, e) => Ok(Expr::Mul(Expr::Num(-1).into(), e.into())),\n\n // The list of parameters are taken from the operator and placed into the ast.\n Postfix(e, Call(p)) => Ok(Expr::Call(e.into(), p)),\n\n // Meaning is assigned to the expressions of the ternary operator during evaluation.\n // The lhs becomes the condition, the contained expression is the true case, rhs the false case.\n Binary(lhs, Ternary(e), rhs) => Ok(Expr::Tern(lhs.into(), e.into(), rhs.into())),\n\n // Raw operators get turned into their respective ast nodes.\n Binary(lhs, Multiplication, rhs) => Ok(Expr::Mul(lhs.into(), rhs.into())),\n Binary(lhs, Division, rhs) => Ok(Expr::Div(lhs.into(), rhs.into())),\n Binary(lhs, Addition, rhs) => Ok(Expr::Add(lhs.into(), rhs.into())),\n Binary(lhs, Subtraction, rhs) => Ok(Expr::Sub(lhs.into(), rhs.into())),\n }\n },\n )(i)\n}\n\n#[test]\nfn expression_test() {\n assert_eq!(\n expression(\"-2*max(2,3)-2\").map(|(i, x)| (i, format!(\"{:?}\", x))),\n Ok((\n \"\",\n String::from(\"Sub(Mul(Mul(Num(-1), Num(2)), Call(Iden(\\\"max\\\"), [Num(2), Num(3)])), Num(2))\")\n ))\n );\n\n assert_eq!(\n expression(\"a?2+c:-2*2\").map(|(i, x)| (i, format!(\"{:?}\", x))),\n Ok((\n \"\",\n String::from(\n \"Tern(Iden(\\\"a\\\"), Add(Num(2), Iden(\\\"c\\\")), Mul(Mul(Num(-1), Num(2)), Num(2)))\"\n )\n ))\n );\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "overflow.rs", "content": "#![allow(clippy::unreadable_literal)]\n#![cfg(target_pointer_width = \"64\")]\n\nuse nom::bytes::streaming::take;\n#[cfg(feature = \"alloc\")]\nuse nom::multi::{length_data, many};\n#[cfg(feature = \"alloc\")]\nuse nom::number::streaming::be_u64;\nuse nom::{Err, IResult, Needed, Parser};\n\n// Parser definition\n\n// We request a length that would trigger an overflow if computing consumed + requested\nfn parser02(i: &[u8]) -> IResult<&[u8], (&[u8], &[u8])> {\n (take(1_usize), take(18446744073709551615_usize)).parse(i)\n}\n\n#[test]\nfn overflow_incomplete_tuple() {\n assert_eq!(\n parser02(&b\"3\"[..]),\n Err(Err::Incomplete(Needed::new(18446744073709551615)))\n );\n}\n\n#[test]\n#[cfg(feature = \"alloc\")]\nfn overflow_incomplete_length_bytes() {\n fn multi(i: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {\n many(0.., length_data(be_u64)).parse(i)\n }\n\n // Trigger an overflow in length_data\n assert_eq!(\n multi(&b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xaa\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\"[..]),\n Err(Err::Incomplete(Needed::new(18446744073709551615)))\n );\n}\n\n#[test]\n#[cfg(feature = \"alloc\")]\nfn overflow_incomplete_many0() {\n fn multi(i: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {\n many(0.., length_data(be_u64)).parse(i)\n }\n\n // Trigger an overflow in many0\n assert_eq!(\n multi(&b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xaa\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xef\"[..]),\n Err(Err::Incomplete(Needed::new(18446744073709551599)))\n );\n}\n\n#[test]\n#[cfg(feature = \"alloc\")]\nfn overflow_incomplete_many1() {\n fn multi(i: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {\n many(1.., length_data(be_u64)).parse(i)\n }\n\n // Trigger an overflow in many1\n assert_eq!(\n multi(&b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xaa\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xef\"[..]),\n Err(Err::Incomplete(Needed::new(18446744073709551599)))\n );\n}\n\n#[test]\n#[cfg(feature = \"alloc\")]\nfn overflow_incomplete_many_till() {\n use nom::{bytes::complete::tag, multi::many_till};\n\n #[allow(clippy::type_complexity)]\n fn multi(i: &[u8]) -> IResult<&[u8], (Vec<&[u8]>, &[u8])> {\n many_till(length_data(be_u64), tag(\"abc\")).parse(i)\n }\n\n // Trigger an overflow in many_till\n assert_eq!(\n multi(&b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xaa\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xef\"[..]),\n Err(Err::Incomplete(Needed::new(18446744073709551599)))\n );\n}\n\n#[test]\n#[cfg(feature = \"alloc\")]\nfn overflow_incomplete_many_m_n() {\n fn multi(i: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {\n many(2..=4, length_data(be_u64)).parse(i)\n }\n\n // Trigger an overflow in many_m_n\n assert_eq!(\n multi(&b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xaa\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xef\"[..]),\n Err(Err::Incomplete(Needed::new(18446744073709551599)))\n );\n}\n\n#[test]\n#[cfg(feature = \"alloc\")]\nfn overflow_incomplete_count() {\n use nom::multi::count;\n\n fn counter(i: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {\n count(length_data(be_u64), 2).parse(i)\n }\n\n assert_eq!(\n counter(&b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xaa\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xef\"[..]),\n Err(Err::Incomplete(Needed::new(18446744073709551599)))\n );\n}\n\n#[test]\n#[cfg(feature = \"alloc\")]\nfn overflow_incomplete_length_count() {\n use nom::multi::length_count;\n use nom::number::streaming::be_u8;\n\n fn multi(i: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {\n length_count(be_u8, length_data(be_u64)).parse(i)\n }\n\n assert_eq!(\n multi(&b\"\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xaa\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xee\"[..]),\n Err(Err::Incomplete(Needed::new(18446744073709551598)))\n );\n}\n\n#[test]\n#[cfg(feature = \"alloc\")]\nfn overflow_incomplete_length_data() {\n fn multi(i: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {\n many(0.., length_data(be_u64)).parse(i)\n }\n\n assert_eq!(\n multi(&b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xaa\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\"[..]),\n Err(Err::Incomplete(Needed::new(18446744073709551615)))\n );\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "float.rs", "content": "use nom::branch::alt;\nuse nom::bytes::complete::tag;\nuse nom::character::streaming::digit1 as digit;\nuse nom::combinator::{map, map_res, opt, recognize};\nuse nom::error::ErrorKind;\nuse nom::number::complete::f32;\nuse nom::number::complete::f64;\nuse nom::number::Endianness;\nuse nom::sequence::{delimited, pair};\nuse nom::Err;\nuse nom::{IResult, Parser};\nuse std::str;\nuse std::str::FromStr;\n\nfn unsigned_float(i: &[u8]) -> IResult<&[u8], f32> {\n let float_bytes = recognize(alt((\n delimited(digit, tag(\".\"), opt(digit)),\n delimited(opt(digit), tag(\".\"), digit),\n )));\n let float_str = map_res(float_bytes, str::from_utf8);\n map_res(float_str, FromStr::from_str).parse(i)\n}\n\nfn float(i: &[u8]) -> IResult<&[u8], f32> {\n map(\n pair(opt(alt((tag(\"+\"), tag(\"-\")))), unsigned_float),\n |(sign, value)| {\n sign\n .and_then(|s| if s[0] == b'-' { Some(-1f32) } else { None })\n .unwrap_or(1f32)\n },\n )\n .parse(i)\n}\n\n#[test]\nfn unsigned_float_test() {\n assert_eq!(unsigned_float(&b\"123.456;\"[..]), Ok((&b\";\"[..], 123.456)));\n assert_eq!(unsigned_float(&b\"0.123;\"[..]), Ok((&b\";\"[..], 0.123)));\n assert_eq!(unsigned_float(&b\"123.0;\"[..]), Ok((&b\";\"[..], 123.0)));\n assert_eq!(unsigned_float(&b\"123.;\"[..]), Ok((&b\";\"[..], 123.0)));\n assert_eq!(unsigned_float(&b\".123;\"[..]), Ok((&b\";\"[..], 0.123)));\n}\n\n#[test]\nfn float_test() {\n assert_eq!(float(&b\"123.456;\"[..]), Ok((&b\";\"[..], 123.456)));\n assert_eq!(float(&b\"+123.456;\"[..]), Ok((&b\";\"[..], 123.456)));\n assert_eq!(float(&b\"-123.456;\"[..]), Ok((&b\";\"[..], -123.456)));\n}\n\n#[test]\nfn test_f32_big_endian() {\n let be_f32 = |s| f32::<_, (_, ErrorKind)>(Endianness::Big)(s);\n\n assert_eq!(\n be_f32(&[0x41, 0x48, 0x00, 0x00][..]),\n Ok((&[] as &[u8], 12.5))\n );\n}\n\n#[test]\nfn test_f32_little_endian() {\n let le_f32 = |s| f32::<_, (_, ErrorKind)>(Endianness::Little)(s);\n\n assert_eq!(\n le_f32(&[0x00, 0x00, 0x48, 0x41][..]),\n Ok((&[] as &[u8], 12.5))\n );\n}\n\n#[test]\nfn test_f64_big_endian() {\n let be_f64 = |s| f64::<&[u8], (&[u8], ErrorKind)>(Endianness::Big)(s);\n\n let input = &[0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..];\n let expected = 12.5f64;\n match be_f64(input) {\n Ok((rest, value)) => {\n assert!(rest.is_empty());\n assert_eq!(value, expected);\n }\n Err(_) => assert!(false, \"Failed to parse big-endian f64\"),\n }\n\n let incomplete_input = &b\"abc\"[..];\n assert!(matches!(be_f64(incomplete_input), Err(Err::Error(_))));\n}\n\n#[test]\nfn test_f64_little_endian() {\n let le_f64 = |s| f64::<&[u8], (&[u8], ErrorKind)>(Endianness::Little)(s);\n\n let input = &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40][..];\n let expected = 12.5f64;\n match le_f64(input) {\n Ok((rest, value)) => {\n assert!(rest.is_empty());\n assert_eq!(value, expected);\n }\n Err(_) => assert!(false, \"Failed to parse little-endian f64\"),\n }\n\n let incomplete_input = &b\"abc\"[..];\n assert!(matches!(le_f64(incomplete_input), Err(Err::Error(_))));\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "ini_str.rs", "content": "use nom::{\n bytes::complete::{is_a, tag, take_till, take_while},\n character::complete::{alphanumeric1 as alphanumeric, char, space0 as space},\n combinator::opt,\n multi::many,\n sequence::{delimited, pair, terminated},\n IResult, Parser,\n};\n\nuse std::collections::HashMap;\n\nfn is_line_ending_or_comment(chr: char) -> bool {\n chr == ';' || chr == '\\n'\n}\n\nfn not_line_ending(i: &str) -> IResult<&str, &str> {\n take_while(|c| c != '\\r' && c != '\\n')(i)\n}\n\nfn space_or_line_ending(i: &str) -> IResult<&str, &str> {\n is_a(\" \\r\\n\")(i)\n}\n\nfn category(i: &str) -> IResult<&str, &str> {\n terminated(\n delimited(char('['), take_while(|c| c != ']'), char(']')),\n opt(is_a(\" \\r\\n\")),\n )\n .parse(i)\n}\n\nfn key_value(i: &str) -> IResult<&str, (&str, &str)> {\n let (i, key) = alphanumeric(i)?;\n let (i, _) = (opt(space), tag(\"=\"), opt(space)).parse(i)?;\n let (i, val) = take_till(is_line_ending_or_comment)(i)?;\n let (i, _) = opt(space).parse(i)?;\n let (i, _) = opt(pair(tag(\";\"), not_line_ending)).parse(i)?;\n let (i, _) = opt(space_or_line_ending).parse(i)?;\n\n Ok((i, (key, val)))\n}\n\nfn keys_and_values_aggregator(i: &str) -> IResult<&str, Vec<(&str, &str)>> {\n many(0.., key_value).parse(i)\n}\n\nfn keys_and_values(input: &str) -> IResult<&str, HashMap<&str, &str>> {\n match keys_and_values_aggregator(input) {\n Ok((i, tuple_vec)) => Ok((i, tuple_vec.into_iter().collect())),\n Err(e) => Err(e),\n }\n}\n\nfn category_and_keys(i: &str) -> IResult<&str, (&str, HashMap<&str, &str>)> {\n pair(category, keys_and_values).parse(i)\n}\n\n#[allow(clippy::type_complexity)]\nfn categories_aggregator(i: &str) -> IResult<&str, Vec<(&str, HashMap<&str, &str>)>> {\n many(0.., category_and_keys).parse(i)\n}\n\nfn categories(input: &str) -> IResult<&str, HashMap<&str, HashMap<&str, &str>>> {\n match categories_aggregator(input) {\n Ok((i, tuple_vec)) => Ok((i, tuple_vec.into_iter().collect())),\n Err(e) => Err(e),\n }\n}\n\n#[test]\nfn parse_category_test() {\n let ini_file = \"[category]\n\nparameter=value\nkey = value2\";\n\n let ini_without_category = \"parameter=value\nkey = value2\";\n\n let res = category(ini_file);\n println!(\"{:?}\", res);\n match res {\n Ok((i, o)) => println!(\"i: {} | o: {:?}\", i, o),\n _ => println!(\"error\"),\n }\n\n assert_eq!(res, Ok((ini_without_category, \"category\")));\n}\n\n#[test]\nfn parse_key_value_test() {\n let ini_file = \"parameter=value\nkey = value2\";\n\n let ini_without_key_value = \"key = value2\";\n\n let res = key_value(ini_file);\n println!(\"{:?}\", res);\n match res {\n Ok((i, (o1, o2))) => println!(\"i: {} | o: ({:?},{:?})\", i, o1, o2),\n _ => println!(\"error\"),\n }\n\n assert_eq!(res, Ok((ini_without_key_value, (\"parameter\", \"value\"))));\n}\n\n#[test]\nfn parse_key_value_with_space_test() {\n let ini_file = \"parameter = value\nkey = value2\";\n\n let ini_without_key_value = \"key = value2\";\n\n let res = key_value(ini_file);\n println!(\"{:?}\", res);\n match res {\n Ok((i, (o1, o2))) => println!(\"i: {} | o: ({:?},{:?})\", i, o1, o2),\n _ => println!(\"error\"),\n }\n\n assert_eq!(res, Ok((ini_without_key_value, (\"parameter\", \"value\"))));\n}\n\n#[test]\nfn parse_key_value_with_comment_test() {\n let ini_file = \"parameter=value;abc\nkey = value2\";\n\n let ini_without_key_value = \"key = value2\";\n\n let res = key_value(ini_file);\n println!(\"{:?}\", res);\n match res {\n Ok((i, (o1, o2))) => println!(\"i: {} | o: ({:?},{:?})\", i, o1, o2),\n _ => println!(\"error\"),\n }\n\n assert_eq!(res, Ok((ini_without_key_value, (\"parameter\", \"value\"))));\n}\n\n#[test]\nfn parse_multiple_keys_and_values_test() {\n let ini_file = \"parameter=value;abc\n\nkey = value2\n\n[category]\";\n\n let ini_without_key_value = \"[category]\";\n\n let res = keys_and_values(ini_file);\n println!(\"{:?}\", res);\n match res {\n Ok((i, ref o)) => println!(\"i: {} | o: {:?}\", i, o),\n _ => println!(\"error\"),\n }\n\n let mut expected: HashMap<&str, &str> = HashMap::new();\n expected.insert(\"parameter\", \"value\");\n expected.insert(\"key\", \"value2\");\n assert_eq!(res, Ok((ini_without_key_value, expected)));\n}\n\n#[test]\nfn parse_category_then_multiple_keys_and_values_test() {\n //FIXME: there can be an empty line or a comment line after a category\n let ini_file = \"[abcd]\nparameter=value;abc\n\nkey = value2\n\n[category]\";\n\n let ini_after_parser = \"[category]\";\n\n let res = category_and_keys(ini_file);\n println!(\"{:?}\", res);\n match res {\n Ok((i, ref o)) => println!(\"i: {} | o: {:?}\", i, o),\n _ => println!(\"error\"),\n }\n\n let mut expected_h: HashMap<&str, &str> = HashMap::new();\n expected_h.insert(\"parameter\", \"value\");\n expected_h.insert(\"key\", \"value2\");\n assert_eq!(res, Ok((ini_after_parser, (\"abcd\", expected_h))));\n}\n\n#[test]\nfn parse_multiple_categories_test() {\n let ini_file = \"[abcd]\n\nparameter=value;abc\n\nkey = value2\n\n[category]\nparameter3=value3\nkey4 = value4\n\";\n\n let res = categories(ini_file);\n //println!(\"{:?}\", res);\n match res {\n Ok((i, ref o)) => println!(\"i: {} | o: {:?}\", i, o),\n _ => println!(\"error\"),\n }\n\n let mut expected_1: HashMap<&str, &str> = HashMap::new();\n expected_1.insert(\"parameter\", \"value\");\n expected_1.insert(\"key\", \"value2\");\n let mut expected_2: HashMap<&str, &str> = HashMap::new();\n expected_2.insert(\"parameter3\", \"value3\");\n expected_2.insert(\"key4\", \"value4\");\n let mut expected_h: HashMap<&str, HashMap<&str, &str>> = HashMap::new();\n expected_h.insert(\"abcd\", expected_1);\n expected_h.insert(\"category\", expected_2);\n assert_eq!(res, Ok((\"\", expected_h)));\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "reborrow_fold.rs", "content": "#![allow(dead_code)]\n// #![allow(unused_variables)]\n\nuse std::str;\n\nuse nom::bytes::complete::is_not;\nuse nom::character::complete::char;\nuse nom::combinator::{map, map_res};\nuse nom::multi::fold;\nuse nom::sequence::delimited;\nuse nom::{IResult, Parser};\n\nfn atom(_tomb: &mut ()) -> impl for<'a> FnMut(&'a [u8]) -> IResult<&'a [u8], String> {\n move |input| {\n map(\n map_res(is_not(\" \\t\\r\\n\"), str::from_utf8),\n ToString::to_string,\n )\n .parse(input)\n }\n}\n\n// FIXME: should we support the use case of borrowing data mutably in a parser?\nfn list<'a>(i: &'a [u8], tomb: &mut ()) -> IResult<&'a [u8], String> {\n delimited(\n char('('),\n fold(0.., atom(tomb), String::new, |acc: String, next: String| {\n acc + next.as_str()\n }),\n char(')'),\n )\n .parse(i)\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "custom_errors.rs", "content": "#![allow(dead_code)]\n\nuse nom::bytes::streaming::tag;\nuse nom::character::streaming::digit1 as digit;\nuse nom::combinator::verify;\nuse nom::error::{ErrorKind, ParseError};\n#[cfg(feature = \"alloc\")]\nuse nom::multi::count;\nuse nom::sequence::terminated;\nuse nom::{IResult, Parser};\n\n#[derive(Debug)]\npub struct CustomError(String);\n\nimpl<'a> From<(&'a str, ErrorKind)> for CustomError {\n fn from(error: (&'a str, ErrorKind)) -> Self {\n CustomError(format!(\"error code was: {:?}\", error))\n }\n}\n\nimpl<'a> ParseError<&'a str> for CustomError {\n fn from_error_kind(_: &'a str, kind: ErrorKind) -> Self {\n CustomError(format!(\"error code was: {:?}\", kind))\n }\n\n fn append(_: &'a str, kind: ErrorKind, other: CustomError) -> Self {\n CustomError(format!(\"{:?}\\nerror code was: {:?}\", other, kind))\n }\n}\n\nfn test1(input: &str) -> IResult<&str, &str, CustomError> {\n //fix_error!(input, CustomError, tag!(\"abcd\"))\n tag(\"abcd\")(input)\n}\n\nfn test2(input: &str) -> IResult<&str, &str, CustomError> {\n //terminated!(input, test1, fix_error!(CustomError, digit))\n terminated(test1, digit).parse(input)\n}\n\nfn test3(input: &str) -> IResult<&str, &str, CustomError> {\n verify(test1, |s: &str| s.starts_with(\"abcd\")).parse(input)\n}\n\n#[cfg(feature = \"alloc\")]\nfn test4(input: &str) -> IResult<&str, Vec<&str>, CustomError> {\n count(test1, 4).parse(input)\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "arithmetic.rs", "content": "use nom::{\n branch::alt,\n bytes::complete::tag,\n character::complete::char,\n character::complete::{digit1 as digit, space0 as space},\n combinator::map_res,\n multi::fold,\n sequence::{delimited, pair},\n IResult, Parser,\n};\n\n// Parser definition\n\nuse std::str::FromStr;\n\n// We parse any expr surrounded by parens, ignoring all whitespaces around those\nfn parens(i: &str) -> IResult<&str, i64> {\n delimited(space, delimited(tag(\"(\"), expr, tag(\")\")), space).parse(i)\n}\n\n// We transform an integer string into a i64, ignoring surrounding whitespaces\n// We look for a digit suite, and try to convert it.\n// If either str::from_utf8 or FromStr::from_str fail,\n// we fallback to the parens parser defined above\nfn factor(i: &str) -> IResult<&str, i64> {\n alt((\n map_res(delimited(space, digit, space), FromStr::from_str),\n parens,\n ))\n .parse(i)\n}\n\n// We read an initial factor and for each time we find\n// a * or / operator followed by another factor, we do\n// the math by folding everything\nfn term(i: &str) -> IResult<&str, i64> {\n let (i, init) = factor(i)?;\n\n fold(\n 0..,\n pair(alt((char('*'), char('/'))), factor),\n move || init,\n |acc, (op, val): (char, i64)| {\n if op == '*' {\n acc * val\n } else {\n acc / val\n }\n },\n )\n .parse(i)\n}\n\nfn expr(i: &str) -> IResult<&str, i64> {\n let (i, init) = term(i)?;\n\n fold(\n 0..,\n pair(alt((char('+'), char('-'))), term),\n move || init,\n |acc, (op, val): (char, i64)| {\n if op == '+' {\n acc + val\n } else {\n acc - val\n }\n },\n )\n .parse(i)\n}\n\n#[test]\nfn factor_test() {\n assert_eq!(factor(\"3\"), Ok((\"\", 3)));\n assert_eq!(factor(\" 12\"), Ok((\"\", 12)));\n assert_eq!(factor(\"537 \"), Ok((\"\", 537)));\n assert_eq!(factor(\" 24 \"), Ok((\"\", 24)));\n}\n\n#[test]\nfn term_test() {\n assert_eq!(term(\" 12 *2 / 3\"), Ok((\"\", 8)));\n assert_eq!(term(\" 2* 3 *2 *2 / 3\"), Ok((\"\", 8)));\n assert_eq!(term(\" 48 / 3/2\"), Ok((\"\", 8)));\n}\n\n#[test]\nfn expr_test() {\n assert_eq!(expr(\" 1 + 2 \"), Ok((\"\", 3)));\n assert_eq!(expr(\" 12 + 6 - 4+ 3\"), Ok((\"\", 17)));\n assert_eq!(expr(\" 1 + 2*3 + 4\"), Ok((\"\", 11)));\n}\n\n#[test]\nfn parens_test() {\n assert_eq!(expr(\" ( 2 )\"), Ok((\"\", 2)));\n assert_eq!(expr(\" 2* ( 3 + 4 ) \"), Ok((\"\", 14)));\n assert_eq!(expr(\" 2*2 / ( 5 - 1) + 3\"), Ok((\"\", 4)));\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "issues.rs", "content": "//#![feature(trace_macros)]\n#![allow(dead_code)]\n#![allow(clippy::redundant_closure)]\n\nuse nom::{error::ErrorKind, Err, IResult, Needed, Parser};\n\n#[allow(dead_code)]\nstruct Range {\n start: char,\n end: char,\n}\n\npub fn take_char(input: &[u8]) -> IResult<&[u8], char> {\n if !input.is_empty() {\n Ok((&input[1..], input[0] as char))\n } else {\n Err(Err::Incomplete(Needed::new(1)))\n }\n}\n\n#[cfg(feature = \"std\")]\nmod parse_int {\n use nom::{\n character::streaming::{digit1 as digit, space1 as space},\n combinator::{complete, map, opt},\n multi::many,\n IResult,\n };\n use nom::{HexDisplay, Parser};\n use std::str;\n\n fn parse_ints(input: &[u8]) -> IResult<&[u8], Vec> {\n many(0.., spaces_or_int).parse(input)\n }\n\n fn spaces_or_int(input: &[u8]) -> IResult<&[u8], i32> {\n println!(\"{}\", input.to_hex(8));\n let (i, _) = opt(complete(space)).parse(input)?;\n let (i, res) = map(complete(digit), |x| {\n println!(\"x: {:?}\", x);\n let result = str::from_utf8(x).unwrap();\n println!(\"Result: {}\", result);\n println!(\"int is empty?: {}\", x.is_empty());\n match result.parse() {\n Ok(i) => i,\n Err(e) => panic!(\"UH OH! NOT A DIGIT! {:?}\", e),\n }\n })\n .parse(i)?;\n\n Ok((i, res))\n }\n\n #[test]\n fn issue_142() {\n let subject = parse_ints(&b\"12 34 5689a\"[..]);\n let expected = Ok((&b\"a\"[..], vec![12, 34, 5689]));\n assert_eq!(subject, expected);\n\n let subject = parse_ints(&b\"12 34 5689 \"[..]);\n let expected = Ok((&b\" \"[..], vec![12, 34, 5689]));\n assert_eq!(subject, expected)\n }\n}\n\n#[test]\nfn usize_length_bytes_issue() {\n use nom::multi::length_data;\n use nom::number::streaming::be_u16;\n let _: IResult<&[u8], &[u8], (&[u8], ErrorKind)> = length_data(be_u16).parse(b\"012346\");\n}\n\n#[test]\nfn take_till_issue() {\n use nom::bytes::streaming::take_till;\n\n fn nothing(i: &[u8]) -> IResult<&[u8], &[u8]> {\n take_till(|_| true)(i)\n }\n\n assert_eq!(nothing(b\"\"), Err(Err::Incomplete(Needed::new(1))));\n assert_eq!(nothing(b\"abc\"), Ok((&b\"abc\"[..], &b\"\"[..])));\n}\n\n#[test]\nfn issue_655() {\n use nom::character::streaming::{line_ending, not_line_ending};\n fn twolines(i: &str) -> IResult<&str, (&str, &str)> {\n let (i, l1) = not_line_ending(i)?;\n let (i, _) = line_ending(i)?;\n let (i, l2) = not_line_ending(i)?;\n let (i, _) = line_ending(i)?;\n\n Ok((i, (l1, l2)))\n }\n\n assert_eq!(twolines(\"foo\\nbar\\n\"), Ok((\"\", (\"foo\", \"bar\"))));\n assert_eq!(twolines(\"f\u00e9o\\nbar\\n\"), Ok((\"\", (\"f\u00e9o\", \"bar\"))));\n assert_eq!(twolines(\"fo\u00e9\\nbar\\n\"), Ok((\"\", (\"fo\u00e9\", \"bar\"))));\n assert_eq!(twolines(\"fo\u00e9\\r\\nbar\\n\"), Ok((\"\", (\"fo\u00e9\", \"bar\"))));\n}\n\n#[cfg(feature = \"alloc\")]\nfn issue_717(i: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {\n use nom::bytes::complete::{is_not, tag};\n use nom::multi::separated_list0;\n\n separated_list0(tag(&[0x0][..]), is_not([0x0u8])).parse(i)\n}\n\nmod issue_647 {\n use nom::bytes::streaming::tag;\n use nom::combinator::complete;\n use nom::multi::separated_list0;\n use nom::Parser;\n use nom::{error::Error, number::streaming::be_f64, Err, IResult};\n pub type Input<'a> = &'a [u8];\n\n #[derive(PartialEq, Debug, Clone)]\n struct Data {\n c: f64,\n v: Vec,\n }\n\n #[allow(clippy::type_complexity)]\n fn list<'a>(\n input: Input<'a>,\n _cs: &'_ f64,\n ) -> Result<(Input<'a>, Vec), Err>> {\n separated_list0(complete(tag(\",\")), complete(be_f64)).parse(input)\n }\n\n fn data(input: Input<'_>) -> IResult, Data> {\n let (i, c) = be_f64(input)?;\n let (i, _) = tag(\"\\n\")(i)?;\n let (i, v) = list(i, &c)?;\n Ok((i, Data { c, v }))\n }\n}\n\n#[test]\nfn issue_848_overflow_incomplete_bits_to_bytes() {\n fn take(i: &[u8]) -> IResult<&[u8], &[u8]> {\n use nom::bytes::streaming::take;\n take(0x2000000000000000_usize)(i)\n }\n fn parser(i: &[u8]) -> IResult<&[u8], &[u8]> {\n use nom::bits::{bits, bytes};\n\n bits(bytes(take))(i)\n }\n assert_eq!(\n parser(&b\"\"[..]),\n Err(Err::Failure(nom::error_position!(\n &b\"\"[..],\n ErrorKind::TooLarge\n )))\n );\n}\n\n#[test]\nfn issue_942() {\n use nom::error::{ContextError, ParseError};\n pub fn parser<'a, E: ParseError<&'a str> + ContextError<&'a str>>(\n i: &'a str,\n ) -> IResult<&'a str, usize, E> {\n use nom::{character::complete::char, error::context, multi::many0_count};\n many0_count(context(\"char_a\", char('a'))).parse(i)\n }\n assert_eq!(parser::<()>(\"aaa\"), Ok((\"\", 3)));\n}\n\n#[test]\nfn issue_many_m_n_with_zeros() {\n use nom::character::complete::char;\n use nom::multi::many;\n let mut parser = many::<_, (), Vec, _, _>(0..=0, char('a'));\n assert_eq!(parser.parse(\"aaa\"), Ok((\"aaa\", vec!())));\n}\n\n#[test]\nfn issue_1231_bits_expect_fn_closure() {\n use nom::bits::{bits, complete::take};\n use nom::error::Error;\n pub fn example(input: &[u8]) -> IResult<&[u8], (u8, u8)> {\n bits::<_, _, Error<_>, _, _>((take(1usize), take(1usize)))(input)\n }\n assert_eq!(example(&[0xff]), Ok((&b\"\"[..], (1, 1))));\n}\n\n#[test]\nfn issue_1282_findtoken_char() {\n use nom::character::complete::one_of;\n use nom::error::Error;\n let mut parser = one_of::<_, _, Error<_>>(&['a', 'b', 'c'][..]);\n assert_eq!(parser(\"aaa\"), Ok((\"aa\", 'a')));\n}\n\n#[test]\nfn issue_x_looser_fill_bounds() {\n use nom::{\n bytes::streaming::tag, character::streaming::digit1, error_position, multi::fill,\n sequence::terminated,\n };\n\n fn fill_pair(i: &[u8]) -> IResult<&[u8], [&[u8]; 2]> {\n let mut buf = [&[][..], &[][..]];\n let (i, _) = fill(terminated(digit1, tag(\",\")), &mut buf).parse(i)?;\n Ok((i, buf))\n }\n\n assert_eq!(\n fill_pair(b\"123,456,\"),\n Ok((&b\"\"[..], [&b\"123\"[..], &b\"456\"[..]]))\n );\n assert_eq!(\n fill_pair(b\"123,456,789\"),\n Ok((&b\"789\"[..], [&b\"123\"[..], &b\"456\"[..]]))\n );\n assert_eq!(\n fill_pair(b\"123,,\"),\n Err(Err::Error(error_position!(&b\",\"[..], ErrorKind::Digit)))\n );\n}\n\n#[test]\nfn issue_1459_clamp_capacity() {\n use nom::character::complete::char;\n\n // shouldn't panic\n use nom::multi::many_m_n;\n let mut parser = many_m_n::<_, (), _>(usize::MAX, usize::MAX, char('a'));\n assert_eq!(parser.parse(\"a\"), Err(nom::Err::Error(())));\n\n // shouldn't panic\n use nom::multi::count;\n let mut parser = count(char('a'), usize::MAX);\n assert_eq!(parser.parse(\"a\"), Err(nom::Err::Error(())));\n}\n\n#[test]\nfn issue_1617_count_parser_returning_zero_size() {\n use nom::{bytes::complete::tag, combinator::map, error::Error, multi::count};\n\n // previously, `count()` panicked if the parser had type `O = ()`\n let parser = map(tag::<_, _, Error<&str>>(\"abc\"), |_| ());\n // shouldn't panic\n let result = count(parser, 3)\n .parse(\"abcabcabcdef\")\n .expect(\"parsing should succeed\");\n assert_eq!(result, (\"def\", vec![(), (), ()]));\n}\n\n#[test]\nfn issue_1586_parser_iterator_impl() {\n use nom::{\n character::complete::{digit1, newline},\n combinator::{iterator, opt},\n sequence::terminated,\n IResult,\n };\n fn parse_line(i: &str) -> IResult<&str, &str> {\n terminated(digit1, opt(newline)).parse(i)\n }\n\n fn parse_input(i: &str) -> impl Iterator + '_ {\n iterator(i, parse_line).map(|x| x.parse::().unwrap())\n }\n\n assert_eq!(parse_input(\"123\\n456\").collect::>(), vec![123, 456]);\n}\n\n#[test]\nfn issue_1808_complete_string_parser_returns_wrong_slice() {\n use nom::character::complete::multispace0;\n use nom::combinator::recognize;\n\n let input = \"\\n\";\n assert_eq!(\n recognize::<_, nom::error::Error<_>, _>(multispace0).parse(input),\n Ok((\"\", \"\\n\"))\n );\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "json.rs", "content": "#![cfg(feature = \"alloc\")]\n\nuse nom::{\n branch::alt,\n bytes::complete::{tag, take},\n character::complete::{anychar, char, multispace0, none_of},\n combinator::{map, map_opt, map_res, value, verify},\n error::ParseError,\n multi::{fold, separated_list0},\n number::complete::double,\n sequence::{delimited, preceded, separated_pair},\n IResult, Parser,\n};\n\nuse std::collections::HashMap;\n\n#[derive(Debug, PartialEq, Clone)]\npub enum JsonValue {\n Null,\n Bool(bool),\n Str(String),\n Num(f64),\n Array(Vec),\n Object(HashMap),\n}\n\nfn boolean(input: &str) -> IResult<&str, bool> {\n alt((value(false, tag(\"false\")), value(true, tag(\"true\")))).parse(input)\n}\n\nfn u16_hex(input: &str) -> IResult<&str, u16> {\n map_res(take(4usize), |s| u16::from_str_radix(s, 16)).parse(input)\n}\n\nfn unicode_escape(input: &str) -> IResult<&str, char> {\n map_opt(\n alt((\n // Not a surrogate\n map(verify(u16_hex, |cp| !(0xD800..0xE000).contains(cp)), |cp| {\n cp as u32\n }),\n // See https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF for details\n map(\n verify(\n separated_pair(u16_hex, tag(\"\\\\u\"), u16_hex),\n |(high, low)| (0xD800..0xDC00).contains(high) && (0xDC00..0xE000).contains(low),\n ),\n |(high, low)| {\n let high_ten = (high as u32) - 0xD800;\n let low_ten = (low as u32) - 0xDC00;\n (high_ten << 10) + low_ten + 0x10000\n },\n ),\n )),\n // Could be probably replaced with .unwrap() or _unchecked due to the verify checks\n std::char::from_u32,\n )\n .parse(input)\n}\n\nfn character(input: &str) -> IResult<&str, char> {\n let (input, c) = none_of(\"\\\"\")(input)?;\n if c == '\\\\' {\n alt((\n map_res(anychar, |c| {\n Ok(match c {\n '\"' | '\\\\' | '/' => c,\n 'b' => '\\x08',\n 'f' => '\\x0C',\n 'n' => '\\n',\n 'r' => '\\r',\n 't' => '\\t',\n _ => return Err(()),\n })\n }),\n preceded(char('u'), unicode_escape),\n ))\n .parse(input)\n } else {\n Ok((input, c))\n }\n}\n\nfn string(input: &str) -> IResult<&str, String> {\n delimited(\n char('\"'),\n fold(0.., character, String::new, |mut string, c| {\n string.push(c);\n string\n }),\n char('\"'),\n )\n .parse(input)\n}\n\nfn ws<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, Output = O, Error = E>>(\n f: F,\n) -> impl Parser<&'a str, Output = O, Error = E> {\n delimited(multispace0, f, multispace0)\n}\n\nfn array(input: &str) -> IResult<&str, Vec> {\n delimited(\n char('['),\n ws(separated_list0(ws(char(',')), json_value)),\n char(']'),\n )\n .parse(input)\n}\n\nfn object(input: &str) -> IResult<&str, HashMap> {\n map(\n delimited(\n char('{'),\n ws(separated_list0(\n ws(char(',')),\n separated_pair(string, ws(char(':')), json_value),\n )),\n char('}'),\n ),\n |key_values| key_values.into_iter().collect(),\n )\n .parse(input)\n}\n\nfn json_value(input: &str) -> IResult<&str, JsonValue> {\n use JsonValue::*;\n\n alt((\n value(Null, tag(\"null\")),\n map(boolean, Bool),\n map(string, Str),\n map(double, Num),\n map(array, Array),\n map(object, Object),\n ))\n .parse(input)\n}\n\nfn json(input: &str) -> IResult<&str, JsonValue> {\n ws(json_value).parse(input)\n}\n\n#[test]\nfn json_string() {\n assert_eq!(string(\"\\\"\\\"\"), Ok((\"\", \"\".to_string())));\n assert_eq!(string(\"\\\"abc\\\"\"), Ok((\"\", \"abc\".to_string())));\n assert_eq!(\n string(\"\\\"abc\\\\\\\"\\\\\\\\\\\\/\\\\b\\\\f\\\\n\\\\r\\\\t\\\\u0001\\\\u2014\\u{2014}def\\\"\"),\n Ok((\"\", \"abc\\\"\\\\/\\x08\\x0C\\n\\r\\t\\x01\u2014\u2014def\".to_string())),\n );\n assert_eq!(string(\"\\\"\\\\uD83D\\\\uDE10\\\"\"), Ok((\"\", \"\ud83d\ude10\".to_string())));\n\n assert!(string(\"\\\"\").is_err());\n assert!(string(\"\\\"abc\").is_err());\n assert!(string(\"\\\"\\\\\\\"\").is_err());\n assert!(string(\"\\\"\\\\u123\\\"\").is_err());\n assert!(string(\"\\\"\\\\uD800\\\"\").is_err());\n assert!(string(\"\\\"\\\\uD800\\\\uD800\\\"\").is_err());\n assert!(string(\"\\\"\\\\uDC00\\\"\").is_err());\n}\n\n#[test]\nfn json_object() {\n use JsonValue::*;\n\n let input = r#\"{\"a\":42,\"b\":\"x\"}\"#;\n\n let expected = Object(\n vec![\n (\"a\".to_string(), Num(42.0)),\n (\"b\".to_string(), Str(\"x\".to_string())),\n ]\n .into_iter()\n .collect(),\n );\n\n assert_eq!(json(input), Ok((\"\", expected)));\n}\n\n#[test]\nfn json_array() {\n use JsonValue::*;\n\n let input = r#\"[42,\"x\"]\"#;\n\n let expected = Array(vec![Num(42.0), Str(\"x\".to_string())]);\n\n assert_eq!(json(input), Ok((\"\", expected)));\n}\n\n#[test]\nfn json_whitespace() {\n use JsonValue::*;\n\n let input = r#\"\n {\n \"null\" : null,\n \"true\" :true ,\n \"false\": false ,\n \"number\" : 123e4 ,\n \"string\" : \" abc 123 \" ,\n \"array\" : [ false , 1 , \"two\" ] ,\n \"object\" : { \"a\" : 1.0 , \"b\" : \"c\" } ,\n \"empty_array\" : [ ] ,\n \"empty_object\" : { }\n }\n \"#;\n\n assert_eq!(\n json(input),\n Ok((\n \"\",\n Object(\n vec![\n (\"null\".to_string(), Null),\n (\"true\".to_string(), Bool(true)),\n (\"false\".to_string(), Bool(false)),\n (\"number\".to_string(), Num(123e4)),\n (\"string\".to_string(), Str(\" abc 123 \".to_string())),\n (\n \"array\".to_string(),\n Array(vec![Bool(false), Num(1.0), Str(\"two\".to_string())])\n ),\n (\n \"object\".to_string(),\n Object(\n vec![\n (\"a\".to_string(), Num(1.0)),\n (\"b\".to_string(), Str(\"c\".to_string())),\n ]\n .into_iter()\n .collect()\n )\n ),\n (\"empty_array\".to_string(), Array(vec![]),),\n (\"empty_object\".to_string(), Object(HashMap::new()),),\n ]\n .into_iter()\n .collect()\n )\n ))\n );\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "arithmetic_ast.rs", "content": "use std::fmt;\nuse std::fmt::{Debug, Display, Formatter};\n\nuse std::str::FromStr;\n\nuse nom::Parser;\nuse nom::{\n branch::alt,\n bytes::complete::tag,\n character::complete::{digit1 as digit, multispace0 as multispace},\n combinator::{map, map_res},\n multi::many,\n sequence::{delimited, preceded},\n IResult,\n};\n\npub enum Expr {\n Value(i64),\n Add(Box, Box),\n Sub(Box, Box),\n Mul(Box, Box),\n Div(Box, Box),\n Paren(Box),\n}\n\n#[derive(Debug)]\npub enum Oper {\n Add,\n Sub,\n Mul,\n Div,\n}\n\nimpl Display for Expr {\n fn fmt(&self, format: &mut Formatter<'_>) -> fmt::Result {\n use self::Expr::*;\n match *self {\n Value(val) => write!(format, \"{}\", val),\n Add(ref left, ref right) => write!(format, \"{} + {}\", left, right),\n Sub(ref left, ref right) => write!(format, \"{} - {}\", left, right),\n Mul(ref left, ref right) => write!(format, \"{} * {}\", left, right),\n Div(ref left, ref right) => write!(format, \"{} / {}\", left, right),\n Paren(ref expr) => write!(format, \"({})\", expr),\n }\n }\n}\n\nimpl Debug for Expr {\n fn fmt(&self, format: &mut Formatter<'_>) -> fmt::Result {\n use self::Expr::*;\n match *self {\n Value(val) => write!(format, \"{}\", val),\n Add(ref left, ref right) => write!(format, \"({:?} + {:?})\", left, right),\n Sub(ref left, ref right) => write!(format, \"({:?} - {:?})\", left, right),\n Mul(ref left, ref right) => write!(format, \"({:?} * {:?})\", left, right),\n Div(ref left, ref right) => write!(format, \"({:?} / {:?})\", left, right),\n Paren(ref expr) => write!(format, \"[{:?}]\", expr),\n }\n }\n}\n\nfn parens(i: &str) -> IResult<&str, Expr> {\n delimited(\n multispace,\n delimited(tag(\"(\"), map(expr, |e| Expr::Paren(Box::new(e))), tag(\")\")),\n multispace,\n )\n .parse(i)\n}\n\nfn factor(i: &str) -> IResult<&str, Expr> {\n alt((\n map(\n map_res(delimited(multispace, digit, multispace), FromStr::from_str),\n Expr::Value,\n ),\n parens,\n ))\n .parse(i)\n}\n\nfn fold_exprs(initial: Expr, remainder: Vec<(Oper, Expr)>) -> Expr {\n remainder.into_iter().fold(initial, |acc, pair| {\n let (oper, expr) = pair;\n match oper {\n Oper::Add => Expr::Add(Box::new(acc), Box::new(expr)),\n Oper::Sub => Expr::Sub(Box::new(acc), Box::new(expr)),\n Oper::Mul => Expr::Mul(Box::new(acc), Box::new(expr)),\n Oper::Div => Expr::Div(Box::new(acc), Box::new(expr)),\n }\n })\n}\n\nfn term(i: &str) -> IResult<&str, Expr> {\n let (i, initial) = factor(i)?;\n let (i, remainder) = many(\n 0..,\n alt((\n |i| {\n let (i, mul) = preceded(tag(\"*\"), factor).parse(i)?;\n Ok((i, (Oper::Mul, mul)))\n },\n |i| {\n let (i, div) = preceded(tag(\"/\"), factor).parse(i)?;\n Ok((i, (Oper::Div, div)))\n },\n )),\n )\n .parse(i)?;\n\n Ok((i, fold_exprs(initial, remainder)))\n}\n\nfn expr(i: &str) -> IResult<&str, Expr> {\n let (i, initial) = term(i)?;\n let (i, remainder) = many(\n 0..,\n alt((\n |i| {\n let (i, add) = preceded(tag(\"+\"), term).parse(i)?;\n Ok((i, (Oper::Add, add)))\n },\n |i| {\n let (i, sub) = preceded(tag(\"-\"), term).parse(i)?;\n Ok((i, (Oper::Sub, sub)))\n },\n )),\n )\n .parse(i)?;\n\n Ok((i, fold_exprs(initial, remainder)))\n}\n\n#[test]\nfn factor_test() {\n assert_eq!(\n factor(\" 3 \").map(|(i, x)| (i, format!(\"{:?}\", x))),\n Ok((\"\", String::from(\"3\")))\n );\n}\n\n#[test]\nfn term_test() {\n assert_eq!(\n term(\" 3 * 5 \").map(|(i, x)| (i, format!(\"{:?}\", x))),\n Ok((\"\", String::from(\"(3 * 5)\")))\n );\n}\n\n#[test]\nfn expr_test() {\n assert_eq!(\n expr(\" 1 + 2 * 3 \").map(|(i, x)| (i, format!(\"{:?}\", x))),\n Ok((\"\", String::from(\"(1 + (2 * 3))\")))\n );\n assert_eq!(\n expr(\" 1 + 2 * 3 / 4 - 5 \").map(|(i, x)| (i, format!(\"{:?}\", x))),\n Ok((\"\", String::from(\"((1 + ((2 * 3) / 4)) - 5)\")))\n );\n assert_eq!(\n expr(\" 72 / 2 / 3 \").map(|(i, x)| (i, format!(\"{:?}\", x))),\n Ok((\"\", String::from(\"((72 / 2) / 3)\")))\n );\n}\n\n#[test]\nfn parens_test() {\n assert_eq!(\n expr(\" ( 1 + 2 ) * 3 \").map(|(i, x)| (i, format!(\"{:?}\", x))),\n Ok((\"\", String::from(\"([(1 + 2)] * 3)\")))\n );\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "ini.rs", "content": "use nom::{\n bytes::complete::take_while,\n character::complete::{\n alphanumeric1 as alphanumeric, char, multispace0 as multispace, space0 as space,\n },\n combinator::{map, map_res, opt},\n multi::many,\n sequence::{delimited, pair, separated_pair, terminated},\n IResult, Parser,\n};\n\nuse std::collections::HashMap;\nuse std::str;\n\nfn category(i: &[u8]) -> IResult<&[u8], &str> {\n map_res(\n delimited(char('['), take_while(|c| c != b']'), char(']')),\n str::from_utf8,\n )\n .parse(i)\n}\n\nfn key_value(i: &[u8]) -> IResult<&[u8], (&str, &str)> {\n let (i, key) = map_res(alphanumeric, str::from_utf8).parse(i)?;\n let (i, _) = (opt(space), char('='), opt(space)).parse(i)?;\n let (i, val) = map_res(take_while(|c| c != b'\\n' && c != b';'), str::from_utf8).parse(i)?;\n let (i, _) = opt(pair(char(';'), take_while(|c| c != b'\\n'))).parse(i)?;\n Ok((i, (key, val)))\n}\n\nfn keys_and_values(i: &[u8]) -> IResult<&[u8], HashMap<&str, &str>> {\n many(0.., terminated(key_value, opt(multispace))).parse(i)\n}\n\nfn category_and_keys(i: &[u8]) -> IResult<&[u8], (&str, HashMap<&str, &str>)> {\n let (i, category) = terminated(category, opt(multispace)).parse(i)?;\n let (i, keys) = keys_and_values(i)?;\n Ok((i, (category, keys)))\n}\n\nfn categories(i: &[u8]) -> IResult<&[u8], HashMap<&str, HashMap<&str, &str>>> {\n map(\n many(\n 0..,\n separated_pair(\n category,\n opt(multispace),\n map(\n many(0.., terminated(key_value, opt(multispace))),\n |vec: Vec<_>| vec.into_iter().collect(),\n ),\n ),\n ),\n |vec: Vec<_>| vec.into_iter().collect(),\n )\n .parse(i)\n}\n\n#[test]\nfn parse_category_test() {\n let ini_file = &b\"[category]\n\nparameter=value\nkey = value2\"[..];\n\n let ini_without_category = &b\"\\n\\nparameter=value\nkey = value2\"[..];\n\n let res = category(ini_file);\n println!(\"{:?}\", res);\n match res {\n Ok((i, o)) => println!(\"i: {:?} | o: {:?}\", str::from_utf8(i), o),\n _ => println!(\"error\"),\n }\n\n assert_eq!(res, Ok((ini_without_category, \"category\")));\n}\n\n#[test]\nfn parse_key_value_test() {\n let ini_file = &b\"parameter=value\nkey = value2\"[..];\n\n let ini_without_key_value = &b\"\\nkey = value2\"[..];\n\n let res = key_value(ini_file);\n println!(\"{:?}\", res);\n match res {\n Ok((i, (o1, o2))) => println!(\"i: {:?} | o: ({:?},{:?})\", str::from_utf8(i), o1, o2),\n _ => println!(\"error\"),\n }\n\n assert_eq!(res, Ok((ini_without_key_value, (\"parameter\", \"value\"))));\n}\n\n#[test]\nfn parse_key_value_with_space_test() {\n let ini_file = &b\"parameter = value\nkey = value2\"[..];\n\n let ini_without_key_value = &b\"\\nkey = value2\"[..];\n\n let res = key_value(ini_file);\n println!(\"{:?}\", res);\n match res {\n Ok((i, (o1, o2))) => println!(\"i: {:?} | o: ({:?},{:?})\", str::from_utf8(i), o1, o2),\n _ => println!(\"error\"),\n }\n\n assert_eq!(res, Ok((ini_without_key_value, (\"parameter\", \"value\"))));\n}\n\n#[test]\nfn parse_key_value_with_comment_test() {\n let ini_file = &b\"parameter=value;abc\nkey = value2\"[..];\n\n let ini_without_key_value = &b\"\\nkey = value2\"[..];\n\n let res = key_value(ini_file);\n println!(\"{:?}\", res);\n match res {\n Ok((i, (o1, o2))) => println!(\"i: {:?} | o: ({:?},{:?})\", str::from_utf8(i), o1, o2),\n _ => println!(\"error\"),\n }\n\n assert_eq!(res, Ok((ini_without_key_value, (\"parameter\", \"value\"))));\n}\n\n#[test]\nfn parse_multiple_keys_and_values_test() {\n let ini_file = &b\"parameter=value;abc\n\nkey = value2\n\n[category]\"[..];\n\n let ini_without_key_value = &b\"[category]\"[..];\n\n let res = keys_and_values(ini_file);\n println!(\"{:?}\", res);\n match res {\n Ok((i, ref o)) => println!(\"i: {:?} | o: {:?}\", str::from_utf8(i), o),\n _ => println!(\"error\"),\n }\n\n let mut expected: HashMap<&str, &str> = HashMap::new();\n expected.insert(\"parameter\", \"value\");\n expected.insert(\"key\", \"value2\");\n assert_eq!(res, Ok((ini_without_key_value, expected)));\n}\n\n#[test]\nfn parse_category_then_multiple_keys_and_values_test() {\n //FIXME: there can be an empty line or a comment line after a category\n let ini_file = &b\"[abcd]\nparameter=value;abc\n\nkey = value2\n\n[category]\"[..];\n\n let ini_after_parser = &b\"[category]\"[..];\n\n let res = category_and_keys(ini_file);\n println!(\"{:?}\", res);\n match res {\n Ok((i, ref o)) => println!(\"i: {:?} | o: {:?}\", str::from_utf8(i), o),\n _ => println!(\"error\"),\n }\n\n let mut expected_h: HashMap<&str, &str> = HashMap::new();\n expected_h.insert(\"parameter\", \"value\");\n expected_h.insert(\"key\", \"value2\");\n assert_eq!(res, Ok((ini_after_parser, (\"abcd\", expected_h))));\n}\n\n#[test]\nfn parse_multiple_categories_test() {\n let ini_file = &b\"[abcd]\n\nparameter=value;abc\n\nkey = value2\n\n[category]\nparameter3=value3\nkey4 = value4\n\"[..];\n\n let ini_after_parser = &b\"\"[..];\n\n let res = categories(ini_file);\n //println!(\"{:?}\", res);\n match res {\n Ok((i, ref o)) => println!(\"i: {:?} | o: {:?}\", str::from_utf8(i), o),\n _ => println!(\"error\"),\n }\n\n let mut expected_1: HashMap<&str, &str> = HashMap::new();\n expected_1.insert(\"parameter\", \"value\");\n expected_1.insert(\"key\", \"value2\");\n let mut expected_2: HashMap<&str, &str> = HashMap::new();\n expected_2.insert(\"parameter3\", \"value3\");\n expected_2.insert(\"key4\", \"value4\");\n let mut expected_h: HashMap<&str, HashMap<&str, &str>> = HashMap::new();\n expected_h.insert(\"abcd\", expected_1);\n expected_h.insert(\"category\", expected_2);\n assert_eq!(res, Ok((ini_after_parser, expected_h)));\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "mp4.rs", "content": "#![allow(dead_code)]\n\nuse nom::{\n branch::alt,\n bytes::streaming::{tag, take},\n combinator::{map, map_res},\n error::ErrorKind,\n multi::many,\n number::streaming::{be_f32, be_u16, be_u32, be_u64},\n Err, IResult, Needed, Parser,\n};\n\nuse std::str;\n\nfn mp4_box(input: &[u8]) -> IResult<&[u8], &[u8]> {\n match be_u32(input) {\n Ok((i, offset)) => {\n let sz: usize = offset as usize;\n if i.len() >= sz - 4 {\n Ok((&i[(sz - 4)..], &i[0..(sz - 4)]))\n } else {\n Err(Err::Incomplete(Needed::new(offset as usize + 4)))\n }\n }\n Err(e) => Err(e),\n }\n}\n\n#[rustfmt::skip]\n#[derive(PartialEq,Eq,Debug)]\nstruct FileType<'a> {\n major_brand: &'a str,\n major_brand_version: &'a [u8],\n compatible_brands: Vec<&'a str>\n}\n\n#[rustfmt::skip]\n#[allow(non_snake_case)]\n#[derive(Debug,Clone)]\npub struct Mvhd32 {\n version_flags: u32, // actually:\n // version: u8,\n // flags: u24 // 3 bytes\n created_date: u32,\n modified_date: u32,\n scale: u32,\n duration: u32,\n speed: f32,\n volume: u16, // actually a 2 bytes decimal\n scaleA: f32,\n rotateB: f32,\n angleU: f32,\n rotateC: f32,\n scaleD: f32,\n angleV: f32,\n positionX: f32,\n positionY: f32,\n scaleW: f32,\n preview: u64,\n poster: u32,\n selection: u64,\n current_time: u32,\n track_id: u32\n}\n\n#[rustfmt::skip]\n#[allow(non_snake_case)]\n#[derive(Debug,Clone)]\npub struct Mvhd64 {\n version_flags: u32, // actually:\n // version: u8,\n // flags: u24 // 3 bytes\n created_date: u64,\n modified_date: u64,\n scale: u32,\n duration: u64,\n speed: f32,\n volume: u16, // actually a 2 bytes decimal\n scaleA: f32,\n rotateB: f32,\n angleU: f32,\n rotateC: f32,\n scaleD: f32,\n angleV: f32,\n positionX: f32,\n positionY: f32,\n scaleW: f32,\n preview: u64,\n poster: u32,\n selection: u64,\n current_time: u32,\n track_id: u32\n}\n\n#[rustfmt::skip]\nfn mvhd32(i: &[u8]) -> IResult<&[u8], MvhdBox> {\n let (i, version_flags) = be_u32(i)?;\n let (i, created_date) = be_u32(i)?;\n let (i, modified_date) = be_u32(i)?;\n let (i, scale) = be_u32(i)?;\n let (i, duration) = be_u32(i)?;\n let (i, speed) = be_f32(i)?;\n let (i, volume) = be_u16(i)?; // actually a 2 bytes decimal\n let (i, _) = take(10_usize)(i)?;\n let (i, scale_a) = be_f32(i)?;\n let (i, rotate_b) = be_f32(i)?;\n let (i, angle_u) = be_f32(i)?;\n let (i, rotate_c) = be_f32(i)?;\n let (i, scale_d) = be_f32(i)?;\n let (i, angle_v) = be_f32(i)?;\n let (i, position_x) = be_f32(i)?;\n let (i, position_y) = be_f32(i)?;\n let (i, scale_w) = be_f32(i)?;\n let (i, preview) = be_u64(i)?;\n let (i, poster) = be_u32(i)?;\n let (i, selection) = be_u64(i)?;\n let (i, current_time) = be_u32(i)?;\n let (i, track_id) = be_u32(i)?;\n\n let mvhd_box = MvhdBox::M32(Mvhd32 {\n version_flags,\n created_date,\n modified_date,\n scale,\n duration,\n speed,\n volume,\n scaleA: scale_a,\n rotateB: rotate_b,\n angleU: angle_u,\n rotateC: rotate_c,\n scaleD: scale_d,\n angleV: angle_v,\n positionX: position_x,\n positionY: position_y,\n scaleW: scale_w,\n preview,\n poster,\n selection,\n current_time,\n track_id,\n });\n\n Ok((i, mvhd_box))\n}\n\n#[rustfmt::skip]\nfn mvhd64(i: &[u8]) -> IResult<&[u8], MvhdBox> {\n let (i, version_flags) = be_u32(i)?;\n let (i, created_date) = be_u64(i)?;\n let (i, modified_date) = be_u64(i)?;\n let (i, scale) = be_u32(i)?;\n let (i, duration) = be_u64(i)?;\n let (i, speed) = be_f32(i)?;\n let (i, volume) = be_u16(i)?; // actually a 2 bytes decimal\n let (i, _) = take(10_usize)(i)?;\n let (i, scale_a) = be_f32(i)?;\n let (i, rotate_b) = be_f32(i)?;\n let (i, angle_u) = be_f32(i)?;\n let (i, rotate_c) = be_f32(i)?;\n let (i, scale_d) = be_f32(i)?;\n let (i, angle_v) = be_f32(i)?;\n let (i, position_x) = be_f32(i)?;\n let (i, position_y) = be_f32(i)?;\n let (i, scale_w) = be_f32(i)?;\n let (i, preview) = be_u64(i)?;\n let (i, poster) = be_u32(i)?;\n let (i, selection) = be_u64(i)?;\n let (i, current_time) = be_u32(i)?;\n let (i, track_id) = be_u32(i)?;\n\n let mvhd_box = MvhdBox::M64(Mvhd64 {\n version_flags,\n created_date,\n modified_date,\n scale,\n duration,\n speed,\n volume,\n scaleA: scale_a,\n rotateB: rotate_b,\n angleU: angle_u,\n rotateC: rotate_c,\n scaleD: scale_d,\n angleV: angle_v,\n positionX: position_x,\n positionY: position_y,\n scaleW: scale_w,\n preview,\n poster,\n selection,\n current_time,\n track_id,\n });\n\n Ok((i, mvhd_box))\n}\n\n#[derive(Debug, Clone)]\npub enum MvhdBox {\n M32(Mvhd32),\n M64(Mvhd64),\n}\n\n#[derive(Debug, Clone)]\npub enum MoovBox {\n Mdra,\n Dref,\n Cmov,\n Rmra,\n Iods,\n Mvhd(MvhdBox),\n Clip,\n Trak,\n Udta,\n}\n\n#[derive(Debug)]\nenum MP4BoxType {\n Ftyp,\n Moov,\n Mdat,\n Free,\n Skip,\n Wide,\n Mdra,\n Dref,\n Cmov,\n Rmra,\n Iods,\n Mvhd,\n Clip,\n Trak,\n Udta,\n Unknown,\n}\n\n#[derive(Debug)]\nstruct MP4BoxHeader {\n length: u32,\n tag: MP4BoxType,\n}\n\nfn brand_name(input: &[u8]) -> IResult<&[u8], &str> {\n map_res(take(4_usize), str::from_utf8).parse(input)\n}\n\nfn filetype_parser(input: &[u8]) -> IResult<&[u8], FileType<'_>> {\n let (i, name) = brand_name(input)?;\n let (i, version) = take(4_usize)(i)?;\n let (i, brands) = many(0.., brand_name).parse(i)?;\n\n let ft = FileType {\n major_brand: name,\n major_brand_version: version,\n compatible_brands: brands,\n };\n Ok((i, ft))\n}\n\nfn mvhd_box(input: &[u8]) -> IResult<&[u8], MvhdBox> {\n let res = if input.len() < 100 {\n Err(Err::Incomplete(Needed::new(100)))\n } else if input.len() == 100 {\n mvhd32(input)\n } else if input.len() == 112 {\n mvhd64(input)\n } else {\n Err(Err::Error(nom::error_position!(input, ErrorKind::TooLarge)))\n };\n println!(\"res: {:?}\", res);\n res\n}\n\nfn unknown_box_type(input: &[u8]) -> IResult<&[u8], MP4BoxType> {\n Ok((input, MP4BoxType::Unknown))\n}\n\nfn box_type(input: &[u8]) -> IResult<&[u8], MP4BoxType> {\n alt((\n map(tag(\"ftyp\"), |_| MP4BoxType::Ftyp),\n map(tag(\"moov\"), |_| MP4BoxType::Moov),\n map(tag(\"mdat\"), |_| MP4BoxType::Mdat),\n map(tag(\"free\"), |_| MP4BoxType::Free),\n map(tag(\"skip\"), |_| MP4BoxType::Skip),\n map(tag(\"wide\"), |_| MP4BoxType::Wide),\n unknown_box_type,\n ))\n .parse(input)\n}\n\n// warning, an alt combinator with 9 branches containing a tag combinator\n// can make the compilation very slow. Use functions as sub parsers,\n// or split into multiple alt parsers if it gets slow\nfn moov_type(input: &[u8]) -> IResult<&[u8], MP4BoxType> {\n alt((\n map(tag(\"mdra\"), |_| MP4BoxType::Mdra),\n map(tag(\"dref\"), |_| MP4BoxType::Dref),\n map(tag(\"cmov\"), |_| MP4BoxType::Cmov),\n map(tag(\"rmra\"), |_| MP4BoxType::Rmra),\n map(tag(\"iods\"), |_| MP4BoxType::Iods),\n map(tag(\"mvhd\"), |_| MP4BoxType::Mvhd),\n map(tag(\"clip\"), |_| MP4BoxType::Clip),\n map(tag(\"trak\"), |_| MP4BoxType::Trak),\n map(tag(\"udta\"), |_| MP4BoxType::Udta),\n ))\n .parse(input)\n}\n\nfn box_header(input: &[u8]) -> IResult<&[u8], MP4BoxHeader> {\n let (i, length) = be_u32(input)?;\n let (i, tag) = box_type(i)?;\n Ok((i, MP4BoxHeader { length, tag }))\n}\n\nfn moov_header(input: &[u8]) -> IResult<&[u8], MP4BoxHeader> {\n let (i, length) = be_u32(input)?;\n let (i, tag) = moov_type(i)?;\n Ok((i, MP4BoxHeader { length, tag }))\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "escaped.rs", "content": "use nom::bytes::complete::escaped;\nuse nom::character::complete::digit1;\nuse nom::character::complete::one_of;\nuse nom::{error::ErrorKind, Err, IResult};\n\nfn esc(s: &str) -> IResult<&str, &str, (&str, ErrorKind)> {\n escaped(digit1, '\\\\', one_of(\"\\\"n\\\\\"))(s)\n}\n\n#[cfg(feature = \"alloc\")]\nfn esc_trans(s: &str) -> IResult<&str, String, (&str, ErrorKind)> {\n use nom::bytes::complete::{escaped_transform, tag};\n escaped_transform(digit1, '\\\\', tag(\"n\"))(s)\n}\n\n#[test]\nfn test_escaped() {\n assert_eq!(esc(\"abcd\"), Err(Err::Error((\"abcd\", ErrorKind::Escaped))));\n}\n\n#[test]\n#[cfg(feature = \"alloc\")]\nfn test_escaped_transform() {\n assert_eq!(\n esc_trans(\"abcd\"),\n Err(Err::Error((\"abcd\", ErrorKind::EscapedTransform)))\n );\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "css.rs", "content": "use nom::bytes::complete::{tag, take_while_m_n};\nuse nom::combinator::map_res;\nuse nom::{IResult, Parser};\n\n#[derive(Debug, Eq, PartialEq)]\npub struct Color {\n pub red: u8,\n pub green: u8,\n pub blue: u8,\n}\n\nfn from_hex(input: &str) -> Result {\n u8::from_str_radix(input, 16)\n}\n\nfn is_hex_digit(c: char) -> bool {\n c.is_ascii_hexdigit()\n}\n\nfn hex_primary(input: &str) -> IResult<&str, u8> {\n map_res(take_while_m_n(2, 2, is_hex_digit), from_hex).parse(input)\n}\n\nfn hex_color(input: &str) -> IResult<&str, Color> {\n let (input, _) = tag(\"#\")(input)?;\n let (input, (red, green, blue)) = (hex_primary, hex_primary, hex_primary).parse(input)?;\n\n Ok((input, Color { red, green, blue }))\n}\n\n#[test]\nfn parse_color() {\n assert_eq!(\n hex_color(\"#2F14DF\"),\n Ok((\n \"\",\n Color {\n red: 47,\n green: 20,\n blue: 223,\n }\n ))\n );\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "multiline.rs", "content": "use nom::{\n character::complete::{alphanumeric1 as alphanumeric, line_ending as eol},\n multi::many,\n sequence::terminated,\n IResult, Parser,\n};\n\npub fn end_of_line(input: &str) -> IResult<&str, &str> {\n if input.is_empty() {\n Ok((input, input))\n } else {\n eol(input)\n }\n}\n\npub fn read_line(input: &str) -> IResult<&str, &str> {\n terminated(alphanumeric, end_of_line).parse(input)\n}\n\npub fn read_lines(input: &str) -> IResult<&str, Vec<&str>> {\n many(0.., read_line).parse(input)\n}\n\n#[cfg(feature = \"alloc\")]\n#[test]\nfn read_lines_test() {\n let res = Ok((\"\", vec![\"Duck\", \"Dog\", \"Cow\"]));\n\n assert_eq!(read_lines(\"Duck\\nDog\\nCow\\n\"), res);\n assert_eq!(read_lines(\"Duck\\nDog\\nCow\"), res);\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "fnmut.rs", "content": "use nom::{\n bytes::complete::tag,\n multi::{many, many0_count},\n Parser,\n};\n\n#[test]\nfn parse() {\n let mut counter = 0;\n\n let res = {\n let mut parser = many::<_, (), Vec<&str>, _, _>(0.., |i| {\n counter += 1;\n tag(\"abc\")(i)\n });\n\n parser.parse(\"abcabcabcabc\").unwrap()\n };\n\n println!(\"res: {:?}\", res);\n assert_eq!(counter, 5);\n}\n\n#[test]\nfn accumulate() {\n let mut v = Vec::new();\n\n let (_, count) = {\n let mut parser = many0_count::<_, (), _>(|i| {\n let (i, o) = tag(\"abc\")(i)?;\n v.push(o);\n Ok((i, ()))\n });\n parser.parse(\"abcabcabcabc\").unwrap()\n };\n\n println!(\"v: {:?}\", v);\n assert_eq!(count, 4);\n assert_eq!(v.len(), 4);\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "error.rs", "content": "use std::fmt;\n\nuse nom::{\n error::{ContextError, ErrorKind, FromExternalError, ParseError},\n ErrorConvert,\n};\n\n/// This error type accumulates errors and their position when backtracking\n/// through a parse tree. With some post processing,\n/// it can be used to display user friendly error messages\n#[derive(Clone, Debug, Eq, PartialEq)]\npub struct VerboseError {\n /// List of errors accumulated by `VerboseError`, containing the affected\n /// part of input data, and some context\n pub errors: Vec<(I, VerboseErrorKind)>,\n}\n\n#[derive(Clone, Debug, Eq, PartialEq)]\n/// Error context for `VerboseError`\npub enum VerboseErrorKind {\n /// Static string added by the `context` function\n Context(&'static str),\n /// Indicates which character was expected by the `char` function\n Char(char),\n /// Error kind given by various nom parsers\n Nom(ErrorKind),\n}\n\nimpl ParseError for VerboseError {\n fn from_error_kind(input: I, kind: ErrorKind) -> Self {\n VerboseError {\n errors: vec![(input, VerboseErrorKind::Nom(kind))],\n }\n }\n\n fn append(input: I, kind: ErrorKind, mut other: Self) -> Self {\n other.errors.push((input, VerboseErrorKind::Nom(kind)));\n other\n }\n\n fn from_char(input: I, c: char) -> Self {\n VerboseError {\n errors: vec![(input, VerboseErrorKind::Char(c))],\n }\n }\n}\n\nimpl ContextError for VerboseError {\n fn add_context(input: I, ctx: &'static str, mut other: Self) -> Self {\n other.errors.push((input, VerboseErrorKind::Context(ctx)));\n other\n }\n}\n\nimpl FromExternalError for VerboseError {\n /// Create a new error from an input position and an external error\n fn from_external_error(input: I, kind: ErrorKind, _e: E) -> Self {\n Self::from_error_kind(input, kind)\n }\n}\n\nimpl fmt::Display for VerboseError {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n writeln!(f, \"Parse error:\")?;\n for (input, error) in &self.errors {\n match error {\n VerboseErrorKind::Nom(e) => writeln!(f, \"{:?} at: {}\", e, input)?,\n VerboseErrorKind::Char(c) => writeln!(f, \"expected '{}' at: {}\", c, input)?,\n VerboseErrorKind::Context(s) => writeln!(f, \"in section '{}', at: {}\", s, input)?,\n }\n }\n\n Ok(())\n }\n}\n\nimpl std::error::Error for VerboseError {}\n\nimpl From> for VerboseError> {\n fn from(value: VerboseError<&[u8]>) -> Self {\n VerboseError {\n errors: value\n .errors\n .into_iter()\n .map(|(i, e)| (i.to_owned(), e))\n .collect(),\n }\n }\n}\n\nimpl From> for VerboseError {\n fn from(value: VerboseError<&str>) -> Self {\n VerboseError {\n errors: value\n .errors\n .into_iter()\n .map(|(i, e)| (i.to_owned(), e))\n .collect(),\n }\n }\n}\n\nimpl ErrorConvert> for VerboseError<(I, usize)> {\n fn convert(self) -> VerboseError {\n VerboseError {\n errors: self.errors.into_iter().map(|(i, e)| (i.0, e)).collect(),\n }\n }\n}\n\nimpl ErrorConvert> for VerboseError {\n fn convert(self) -> VerboseError<(I, usize)> {\n VerboseError {\n errors: self.errors.into_iter().map(|(i, e)| ((i, 0), e)).collect(),\n }\n }\n}\n\n/// Transforms a `VerboseError` into a trace with input position information\n///\n/// The errors contain references to input data that must come from `input`,\n/// because nom calculates byte offsets between them\npub fn convert_error>(input: I, e: VerboseError) -> String {\n use nom::Offset;\n use std::fmt::Write;\n\n let mut result = String::new();\n\n for (i, (substring, kind)) in e.errors.iter().enumerate() {\n let offset = input.offset(substring);\n\n if input.is_empty() {\n match kind {\n VerboseErrorKind::Char(c) => {\n write!(&mut result, \"{}: expected '{}', got empty input\\n\\n\", i, c)\n }\n VerboseErrorKind::Context(s) => write!(&mut result, \"{}: in {}, got empty input\\n\\n\", i, s),\n VerboseErrorKind::Nom(e) => write!(&mut result, \"{}: in {:?}, got empty input\\n\\n\", i, e),\n }\n } else {\n let prefix = &input.as_bytes()[..offset];\n\n // Count the number of newlines in the first `offset` bytes of input\n let line_number = prefix.iter().filter(|&&b| b == b'\\n').count() + 1;\n\n // Find the line that includes the subslice:\n // Find the *last* newline before the substring starts\n let line_begin = prefix\n .iter()\n .rev()\n .position(|&b| b == b'\\n')\n .map(|pos| offset - pos)\n .unwrap_or(0);\n\n // Find the full line after that newline\n let line = input[line_begin..]\n .lines()\n .next()\n .unwrap_or(&input[line_begin..])\n .trim_end();\n\n // The (1-indexed) column number is the offset of our substring into that line\n let column_number = line.offset(substring) + 1;\n\n match kind {\n VerboseErrorKind::Char(c) => {\n if let Some(actual) = substring.chars().next() {\n write!(\n &mut result,\n \"{i}: at line {line_number}:\\n\\\n {line}\\n\\\n {caret:>column$}\\n\\\n expected '{expected}', found {actual}\\n\\n\",\n i = i,\n line_number = line_number,\n line = line,\n caret = '^',\n column = column_number,\n expected = c,\n actual = actual,\n )\n } else {\n write!(\n &mut result,\n \"{i}: at line {line_number}:\\n\\\n {line}\\n\\\n {caret:>column$}\\n\\\n expected '{expected}', got end of input\\n\\n\",\n i = i,\n line_number = line_number,\n line = line,\n caret = '^',\n column = column_number,\n expected = c,\n )\n }\n }\n VerboseErrorKind::Context(s) => write!(\n &mut result,\n \"{i}: at line {line_number}, in {context}:\\n\\\n {line}\\n\\\n {caret:>column$}\\n\\n\",\n i = i,\n line_number = line_number,\n context = s,\n line = line,\n caret = '^',\n column = column_number,\n ),\n VerboseErrorKind::Nom(e) => write!(\n &mut result,\n \"{i}: at line {line_number}, in {nom_err:?}:\\n\\\n {line}\\n\\\n {caret:>column$}\\n\\n\",\n i = i,\n line_number = line_number,\n nom_err = e,\n line = line,\n caret = '^',\n column = column_number,\n ),\n }\n }\n // Because `write!` to a `String` is infallible, this `unwrap` is fine.\n .unwrap();\n }\n\n result\n}\n\n#[test]\nfn convert_error_panic() {\n use nom::character::complete::char;\n use nom::IResult;\n\n let input = \"\";\n\n let _result: IResult<_, _, VerboseError<&str>> = char('x')(input);\n}\n\n#[test]\nfn issue_1027_convert_error_panic_nonempty() {\n use nom::character::complete::char;\n use nom::sequence::pair;\n use nom::Err;\n use nom::IResult;\n use nom::Parser;\n\n let input = \"a\";\n\n let result: IResult<_, _, VerboseError<&str>> = pair(char('a'), char('b')).parse(input);\n let err = match result.unwrap_err() {\n Err::Error(e) => e,\n _ => unreachable!(),\n };\n\n let msg = convert_error(input, err);\n assert_eq!(\n msg,\n \"0: at line 1:\\na\\n ^\\nexpected \\'b\\', got end of input\\n\\n\"\n );\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "mod.rs", "content": "#[cfg(test)]\nmod tests;\n\nuse nom::error::{ErrorKind, FromExternalError, ParseError};\nuse nom::{Check, Err, IResult, Input, Mode, OutputM, OutputMode, Parser};\n\n/// An unary operator.\npub struct Unary {\n value: V,\n precedence: Q,\n}\n\n/// A binary operator.\npub struct Binary {\n value: V,\n precedence: Q,\n assoc: Assoc,\n}\n\n/// A single evaluation step.\npub enum Operation {\n /// A prefix operation.\n Prefix(P1, O),\n /// A postfix operation.\n Postfix(O, P2),\n /// A binary operation.\n Binary(O, P3, O),\n}\n\n/// Associativity for binary operators.\n#[derive(Copy, Clone, PartialEq, Eq)]\npub enum Assoc {\n /// Left associative.\n Left,\n /// Right associative.\n Right,\n}\n\n/// Element for operator stack.\nenum Operator {\n Prefix(P1, Q),\n Postfix(P2, Q),\n Binary(P3, Q, Assoc),\n}\n\nimpl Operator\nwhere\n Q: Ord + Copy,\n{\n fn precedence(&self) -> Q {\n match self {\n Operator::Prefix(_, p) => *p,\n Operator::Postfix(_, p) => *p,\n Operator::Binary(_, p, _) => *p,\n }\n }\n\n fn is_postfix(&self) -> bool {\n match self {\n Operator::Postfix(_, _) => true,\n _ => false,\n }\n }\n}\n\n/// Runs the inner parser and transforms the result into an unary operator with the given precedence.\n///\n/// Intended for use with [precedence].\n/// # Arguments\n/// * `precedence` The precedence of the operator.\n/// * `parser` The parser to apply.\npub fn unary_op(\n precedence: Q,\n mut parser: P,\n) -> impl FnMut(I) -> IResult, E>\nwhere\n P: Parser,\n Q: Ord + Copy,\n{\n move |input| match parser.parse(input) {\n Ok((i, value)) => Ok((i, Unary { value, precedence })),\n Err(e) => Err(e),\n }\n}\n\n/// Runs the inner parser and transforms the result into a binary operator with the given precedence and associativity.\n///\n/// Intended for use with [precedence].\n/// # Arguments\n/// * `precedence` The precedence of the operator.\n/// * `assoc` The associativity of the operator.\n/// * `parser` The parser to apply.\npub fn binary_op(\n precedence: Q,\n assoc: Assoc,\n mut parser: P,\n) -> impl FnMut(I) -> IResult, E>\nwhere\n P: Parser,\n Q: Ord + Copy,\n{\n move |input| match parser.parse(input) {\n Ok((i, value)) => Ok((\n i,\n Binary {\n value,\n precedence,\n assoc,\n },\n )),\n Err(e) => Err(e),\n }\n}\n\n/// Parses an expression with operator precedence.\n///\n/// Supports prefix, postfix and binary operators. Operators are applied in ascending precedence.\n///\n/// The parser will track its current position inside the expression and call the respective\n/// operand/operator parsers. The prefix and postfix parsers are called repeatedly until they fail before\n/// execution moves on to the operand or binary parser.\n///\n/// Expressions are folded as soon as possible. The result will be reused as another operand. After the\n/// expression has been read completely any remaining operations are folded and the resulting, single\n/// operand is returned as the result.\n///\n/// It will return `Err(Err:Error((_, ErrorKind::Precedence)))` if:\n/// * the `fold` function returns an `Err`.\n/// * more than one or no operands remain after the expression has been evaluated completely.\n/// * the input does not match the pattern: `prefix* operand postfix* (binary prefix* operand postfix*)*`\n///\n/// # Arguments\n/// * `prefix` Parser for prefix unary operators.\n/// * `postfix` Parser for postfix unary operators.\n/// * `binary` Parser for binary operators.\n/// * `operand` Parser for operands.\n/// * `fold` Function that evaluates a single operation and returns the result.\n///\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult};\n/// use nom_language::precedence::{precedence, unary_op, binary_op, Assoc, Operation};\n/// use nom::character::complete::digit1;\n/// use nom::combinator::{map_res, fail};\n/// use nom::sequence::delimited;\n/// use nom::bytes::complete::tag;\n/// use nom::branch::alt;\n///\n/// fn parser(i: &str) -> IResult<&str, i64> {\n/// precedence(\n/// unary_op(1, tag(\"-\")),\n/// fail(),\n/// alt((\n/// binary_op(2, Assoc::Left, tag(\"*\")),\n/// binary_op(2, Assoc::Left, tag(\"/\")),\n/// binary_op(3, Assoc::Left, tag(\"+\")),\n/// binary_op(3, Assoc::Left, tag(\"-\")),\n/// )),\n/// alt((\n/// map_res(digit1, |s: &str| s.parse::()),\n/// delimited(tag(\"(\"), parser, tag(\")\")),\n/// )),\n/// |op: Operation<&str, &str, &str, i64>| {\n/// use nom_language::precedence::Operation::*;\n/// match op {\n/// Prefix(\"-\", o) => Ok(-o),\n/// Binary(lhs, \"*\", rhs) => Ok(lhs * rhs),\n/// Binary(lhs, \"/\", rhs) => Ok(lhs / rhs),\n/// Binary(lhs, \"+\", rhs) => Ok(lhs + rhs),\n/// Binary(lhs, \"-\", rhs) => Ok(lhs - rhs),\n/// _ => Err(\"Invalid combination\"),\n/// }\n/// }\n/// )(i)\n/// }\n///\n/// assert_eq!(parser(\"8-2*2\"), Ok((\"\", 4)));\n/// assert_eq!(parser(\"4-(2+2)\"), Ok((\"\", 0)));\n/// assert_eq!(parser(\"3-(2*3)+7+2*2-(2*(2+4))\"), Ok((\"\", -4)));\n/// ```\n///\n/// # Evaluation order\n/// This parser reads expressions from left to right and folds operations as soon as possible. This\n/// behaviour is only important when using an operator grammar that allows for ambigious expressions.\n///\n/// For example, the expression `-a++**b` is ambigious with the following precedence.\n///\n/// | Operator | Position | Precedence | Associativity |\n/// |----------|----------|------------|---------------|\n/// | ** | Binary | 1 | Right |\n/// | - | Prefix | 2 | N/A |\n/// | ++ | Postfix | 3 | N/A |\n///\n/// The expression can be parsed in two ways: `-((a++)**b)` or `((-a)++)**b`. This parser will always\n/// parse it as the latter because of how it evaluates expressions:\n/// * It reads, left-to-right, the first two operators `-a++`.\n/// * Because the minus takes precedence over the increment it is evaluated immediately `(-a)++`.\n/// * It then reads the remaining input and evaluates the increment next in order to preserve its\n/// position in the expression \\\n/// `((-a)++)**b`.\npub fn precedence(\n mut prefix: H1,\n mut postfix: H2,\n mut binary: H3,\n mut operand: F,\n mut fold: G,\n) -> impl FnMut(I) -> IResult\nwhere\n I: Clone + PartialEq,\n E: ParseError + FromExternalError,\n F: Parser,\n G: FnMut(Operation) -> Result,\n H1: Parser, Error = E>,\n H2: Parser, Error = E>,\n H3: Parser, Error = E>,\n Q: Ord + Copy,\n{\n move |mut i| {\n let mut operands = Vec::new();\n let mut operators = Vec::new();\n let mut i1 = i.clone();\n\n 'main: loop {\n 'prefix: loop {\n match prefix.parse(i1.clone()) {\n Err(Err::Error(_)) => break 'prefix,\n Err(e) => return Err(e),\n Ok((i2, o)) => {\n // infinite loop check: the parser must always consume\n if i2 == i1 {\n return Err(Err::Error(E::from_error_kind(i1, ErrorKind::Precedence)));\n }\n i1 = i2;\n operators.push(Operator::Prefix(o.value, o.precedence));\n }\n }\n }\n\n let (i2, o) = match operand.parse(i1.clone()) {\n Ok((i, o)) => (i, o),\n Err(Err::Error(e)) => return Err(Err::Error(E::append(i, ErrorKind::Precedence, e))),\n Err(e) => return Err(e),\n };\n i1 = i2;\n operands.push(o);\n\n 'postfix: loop {\n match postfix.parse(i1.clone()) {\n Err(Err::Error(_)) => break 'postfix,\n Err(e) => return Err(e),\n Ok((i2, o)) => {\n // infinite loop check: the parser must always consume\n if i2 == i1 {\n return Err(Err::Error(E::from_error_kind(i1, ErrorKind::Precedence)));\n }\n\n while operators\n .last()\n .map(|op| op.precedence() <= o.precedence)\n .unwrap_or(false)\n {\n let value = operands.pop().unwrap();\n let operation = match operators.pop().unwrap() {\n Operator::Prefix(op, _) => Operation::Prefix(op, value),\n Operator::Postfix(op, _) => Operation::Postfix(value, op),\n Operator::Binary(op, _, _) => match operands.pop() {\n Some(lhs) => Operation::Binary(lhs, op, value),\n None => return Err(Err::Error(E::from_error_kind(i1, ErrorKind::Precedence))),\n },\n };\n let result = match fold(operation) {\n Err(e) => {\n return Err(Err::Error(E::from_external_error(\n i,\n ErrorKind::Precedence,\n e,\n )))\n }\n Ok(r) => r,\n };\n operands.push(result);\n }\n i1 = i2;\n operators.push(Operator::Postfix(o.value, o.precedence));\n }\n }\n }\n\n match binary.parse(i1.clone()) {\n Err(Err::Error(_)) => break 'main,\n Err(e) => return Err(e),\n Ok((i2, o)) => {\n while operators\n .last()\n .map(|op| {\n op.precedence() < o.precedence\n || (o.assoc == Assoc::Left && op.precedence() == o.precedence)\n || (op.is_postfix())\n })\n .unwrap_or(false)\n {\n let value = operands.pop().unwrap();\n let operation = match operators.pop().unwrap() {\n Operator::Prefix(op, _) => Operation::Prefix(op, value),\n Operator::Postfix(op, _) => Operation::Postfix(value, op),\n Operator::Binary(op, _, _) => match operands.pop() {\n Some(lhs) => Operation::Binary(lhs, op, value),\n None => return Err(Err::Error(E::from_error_kind(i1, ErrorKind::Precedence))),\n },\n };\n let result = match fold(operation) {\n Err(e) => {\n return Err(Err::Error(E::from_external_error(\n i,\n ErrorKind::Precedence,\n e,\n )))\n }\n Ok(r) => r,\n };\n operands.push(result);\n }\n operators.push(Operator::Binary(o.value, o.precedence, o.assoc));\n i1 = i2;\n }\n }\n\n // infinite loop check: either operand or operator must consume input\n if i == i1 {\n return Err(Err::Error(E::from_error_kind(i, ErrorKind::Precedence)));\n }\n i = i1.clone();\n }\n\n while operators.len() > 0 {\n let value = match operands.pop() {\n Some(o) => o,\n None => return Err(Err::Error(E::from_error_kind(i, ErrorKind::Precedence))),\n };\n let operation = match operators.pop().unwrap() {\n Operator::Prefix(op, _) => Operation::Prefix(op, value),\n Operator::Postfix(op, _) => Operation::Postfix(value, op),\n Operator::Binary(op, _, _) => match operands.pop() {\n Some(lhs) => Operation::Binary(lhs, op, value),\n None => return Err(Err::Error(E::from_error_kind(i, ErrorKind::Precedence))),\n },\n };\n let result = match fold(operation) {\n Ok(r) => r,\n Err(e) => {\n return Err(Err::Error(E::from_external_error(\n i,\n ErrorKind::Precedence,\n e,\n )))\n }\n };\n operands.push(result);\n }\n\n if operands.len() == 1 {\n return Ok((i1, operands.pop().unwrap()));\n } else {\n return Err(Err::Error(E::from_error_kind(i, ErrorKind::Precedence)));\n }\n }\n}\n\n/// Applies a parser multiple times separated by another parser.\n///\n/// It is similar to [`separated_list1`][nom::multi::separated_list1] but instead of collecting\n/// into a vector, you have a callback to build the output.\n///\n/// In a LALR grammar a left recursive operator is usually built with a rule syntax such as:\n/// * A := A op B | B\n///\n/// If you try to parse that wth [`alt`][nom::branch::alt] it will fail with a stack overflow\n/// because the recusion is unlimited. This function solves this problem by converting the recusion\n/// into an iteration.\n///\n/// Compare with a right recursive operator, that in LALR would be:\n/// * A := B op A | B\n/// Or equivalently:\n/// * A := B (op A)?\n///\n/// That can be written in `nom` trivially.\n///\n/// This stops when either parser returns an error and returns the last built value. to instead chain an error up, see\n/// [`cut`][nom::combinator::cut].\n///\n/// # Arguments\n/// * `child` The parser to apply.\n/// * `operator` Parses the operator between argument.\n/// * `init` A function returning the initial value.\n/// * `fold` The function that combines a result of `f` with\n/// the current accumulator.\n/// ```rust\n/// # #[macro_use] extern crate nom;\n/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};\n/// use nom_language::precedence::left_assoc;\n/// use nom::branch::alt;\n/// use nom::sequence::delimited;\n/// use nom::character::complete::{char, digit1};\n///\n/// fn add(i: &str) -> IResult<&str, String> {\n/// left_assoc(mult, char('+'), |a, o, b| format!(\"{o}{a}{b}\")).parse(i)\n/// }\n/// fn mult(i: &str) -> IResult<&str, String> {\n/// left_assoc(single, char('*'), |a, o, b| format!(\"{o}{a}{b}\")).parse(i)\n/// }\n/// fn single(i: &str) -> IResult<&str, String> {\n/// alt((\n/// digit1.map(|x: &str| x.to_string()),\n/// delimited(char('('), add, char(')'))\n/// )).parse(i)\n/// }\n///\n/// assert_eq!(single(\"(1+2*3)\"), Ok((\"\", String::from(\"+1*23\"))));\n/// assert_eq!(single(\"((1+2)*3)\"), Ok((\"\", String::from(\"*+123\"))));\n/// assert_eq!(single(\"(1*2+3)\"), Ok((\"\", String::from(\"+*123\"))));\n/// assert_eq!(single(\"((1+2*3)+4)\"), Ok((\"\", String::from(\"++1*234\"))));\n/// assert_eq!(single(\"(1+(2*3+4))\"), Ok((\"\", String::from(\"+1+*234\"))));\n/// ```\npub fn left_assoc(\n child: F,\n operator: G,\n builder: B,\n) -> impl Parser\nwhere\n I: Clone + Input,\n E: ParseError,\n F: Parser,\n G: Parser,\n B: FnMut(O, OP, O) -> O,\n{\n LeftAssoc {\n child,\n operator,\n builder,\n }\n}\n\n/// Parser implementation for the [`separated_list1`][nom::multi::separated_list1] combinator\npub struct LeftAssoc {\n child: F,\n operator: G,\n builder: B,\n}\n\nimpl Parser for LeftAssoc\nwhere\n I: Clone + Input,\n E: ParseError,\n F: Parser,\n G: Parser,\n B: FnMut(O, OP, O) -> O,\n{\n type Output = O;\n type Error = E;\n\n fn process(\n &mut self,\n mut i: I,\n ) -> nom::PResult {\n let (i1, mut res) = self.child.process::(i)?;\n i = i1;\n\n loop {\n let len = i.input_len();\n match self\n .operator\n .process::>(i.clone())\n {\n Err(Err::Error(_)) => return Ok((i, res)),\n Err(Err::Failure(e)) => return Err(Err::Failure(e)),\n Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),\n Ok((i1, op)) => {\n match self\n .child\n .process::>(i1.clone())\n {\n Err(Err::Error(_)) => return Ok((i, res)),\n Err(Err::Failure(e)) => return Err(Err::Failure(e)),\n Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),\n Ok((i2, rhs)) => {\n // infinite loop check: the parser must always consume\n if i2.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(i, ErrorKind::SeparatedList)\n })));\n }\n // there is no combine() with 3 arguments, fake it with a tuple and two calls\n let op_rhs = OM::Output::combine(op, rhs, |op, rhs| (op, rhs));\n res = OM::Output::combine(res, op_rhs, |lhs, (op, rhs)| (self.builder)(lhs, op, rhs));\n i = i2;\n }\n }\n }\n }\n }\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "json2.rs", "content": "//#[global_allocator]\n//static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;\n\nuse nom::{\n branch::alt,\n bytes::{tag, take},\n character::{anychar, char, multispace0, none_of},\n combinator::{map, map_opt, map_res, value, verify},\n error::{Error, ParseError},\n multi::{fold, separated_list0},\n number::double,\n sequence::{delimited, preceded, separated_pair},\n Complete, Emit, Mode, OutputM, Parser,\n};\n\nuse std::collections::HashMap;\n\n#[derive(Debug, PartialEq, Clone)]\npub enum JsonValue {\n Null,\n Bool(bool),\n Str(String),\n Num(f64),\n Array(Vec),\n Object(HashMap),\n}\n\nfn boolean<'a>() -> impl Parser<&'a str, Output = bool, Error = Error<&'a str>> {\n alt((value(false, tag(\"false\")), value(true, tag(\"true\"))))\n}\n\nfn u16_hex<'a>() -> impl Parser<&'a str, Output = u16, Error = Error<&'a str>> {\n map_res(take(4usize), |s| u16::from_str_radix(s, 16))\n}\n\nfn unicode_escape<'a>() -> impl Parser<&'a str, Output = char, Error = Error<&'a str>> {\n map_opt(\n alt((\n // Not a surrogate\n map(\n verify(u16_hex(), |cp| !(0xD800..0xE000).contains(cp)),\n |cp| cp as u32,\n ),\n // See https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF for details\n map(\n verify(\n separated_pair(u16_hex(), tag(\"\\\\u\"), u16_hex()),\n |(high, low)| (0xD800..0xDC00).contains(high) && (0xDC00..0xE000).contains(low),\n ),\n |(high, low)| {\n let high_ten = (high as u32) - 0xD800;\n let low_ten = (low as u32) - 0xDC00;\n (high_ten << 10) + low_ten + 0x10000\n },\n ),\n )),\n // Could probably be replaced with .unwrap() or _unchecked due to the verify checks\n std::char::from_u32,\n )\n}\n\nfn character<'a>() -> impl Parser<&'a str, Output = char, Error = Error<&'a str>> {\n Character\n if c == '\\\\' {\n alt((\n map_res(anychar, |c| {\n Ok(match c {\n '\"' | '\\\\' | '/' => c,\n 'b' => '\\x08',\n 'f' => '\\x0C',\n 'n' => '\\n',\n 'r' => '\\r',\n 't' => '\\t',\n _ => return Err(()),\n })\n }),\n preceded(char('u'), unicode_escape()),\n ))\n .parse(input)\n } else {\n Ok((input, c))\n }*/\n}\n\nstruct Character;\n\nimpl<'a> Parser<&'a str> for Character {\n type Output = char;\n\n type Error = Error<&'a str>;\n\n fn process(\n &mut self,\n input: &'a str,\n ) -> nom::PResult {\n let (input, c): (&str, char) =\n none_of(\"\\\"\").process::>(input)?;\n if c == '\\\\' {\n alt((\n map_res(anychar, |c| {\n Ok(match c {\n '\"' | '\\\\' | '/' => c,\n 'b' => '\\x08',\n 'f' => '\\x0C',\n 'n' => '\\n',\n 'r' => '\\r',\n 't' => '\\t',\n _ => return Err(()),\n })\n }),\n preceded(char('u'), unicode_escape()),\n ))\n .process::(input)\n } else {\n Ok((input, OM::Output::bind(|| c)))\n }\n }\n}\n\nfn string<'a>() -> impl Parser<&'a str, Output = String, Error = Error<&'a str>> {\n delimited(\n char('\"'),\n fold(0.., character(), String::new, |mut string, c| {\n string.push(c);\n string\n }),\n char('\"'),\n )\n}\n\nfn ws<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, Output = O, Error = E>>(\n f: F,\n) -> impl Parser<&'a str, Output = O, Error = E> {\n delimited(multispace0(), f, multispace0())\n}\n\nfn array<'a>() -> impl Parser<&'a str, Output = Vec, Error = Error<&'a str>> {\n delimited(\n char('['),\n ws(separated_list0(ws(char(',')), json_value())),\n char(']'),\n )\n}\n\nfn object<'a>() -> impl Parser<&'a str, Output = HashMap, Error = Error<&'a str>>\n{\n map(\n delimited(\n char('{'),\n ws(separated_list0(\n ws(char(',')),\n separated_pair(string(), ws(char(':')), json_value()),\n )),\n char('}'),\n ),\n |key_values| key_values.into_iter().collect(),\n )\n}\n\nfn json_value() -> JsonParser {\n JsonParser\n}\n\nstruct JsonParser;\n\n// the main Parser implementation is done explicitely on a real type,\n// because haaving json_value return `impl Parser` would result in\n// \"recursive opaque type\" errors\nimpl<'a> Parser<&'a str> for JsonParser {\n type Output = JsonValue;\n type Error = Error<&'a str>;\n\n fn process(\n &mut self,\n input: &'a str,\n ) -> nom::PResult {\n use JsonValue::*;\n\n let mut parser = alt((\n value(Null, tag(\"null\")),\n map(boolean(), Bool),\n map(string(), Str),\n map(double(), Num),\n map(array(), Array),\n map(object(), Object),\n ));\n\n parser.process::(input)\n }\n}\n\nfn json<'a>() -> impl Parser<&'a str, Output = JsonValue, Error = Error<&'a str>> {\n ws(json_value())\n}\n\nfn main() {\n let data = include_str!(\"../benchmarks/canada.json\");\n\n loop {\n let _a = json()\n .process::>(data)\n .unwrap();\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "custom_error.rs", "content": "extern crate nom;\n\nuse nom::error::ErrorKind;\nuse nom::error::ParseError;\nuse nom::Err::Error;\nuse nom::IResult;\n\n#[derive(Debug, PartialEq)]\npub enum CustomError {\n MyError,\n Nom(I, ErrorKind),\n}\n\nimpl ParseError for CustomError {\n fn from_error_kind(input: I, kind: ErrorKind) -> Self {\n CustomError::Nom(input, kind)\n }\n\n fn append(_: I, _: ErrorKind, other: Self) -> Self {\n other\n }\n}\n\npub fn parse(_input: &str) -> IResult<&str, &str, CustomError<&str>> {\n Err(Error(CustomError::MyError))\n}\n\nfn main() {}\n\n#[cfg(test)]\nmod tests {\n use super::parse;\n use super::CustomError;\n use nom::Err::Error;\n\n #[test]\n fn it_works() {\n let err = parse(\"\").unwrap_err();\n match err {\n Error(e) => assert_eq!(e, CustomError::MyError),\n _ => panic!(\"Unexpected error: {:?}\", err),\n }\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "json.rs", "content": "#![cfg(feature = \"alloc\")]\n\nuse nom::{\n branch::alt,\n bytes::complete::{escaped, tag, take_while},\n character::complete::{alphanumeric1 as alphanumeric, char, one_of},\n combinator::{cut, map, opt, value},\n error::{context, ContextError, ErrorKind, ParseError},\n multi::separated_list0,\n number::complete::double,\n sequence::{delimited, preceded, separated_pair, terminated},\n Err, IResult, Parser,\n};\nuse nom_language::error::{convert_error, VerboseError};\nuse std::collections::HashMap;\nuse std::str;\n\n#[derive(Debug, PartialEq)]\npub enum JsonValue {\n Null,\n Str(String),\n Boolean(bool),\n Num(f64),\n Array(Vec),\n Object(HashMap),\n}\n\n/// parser combinators are constructed from the bottom up:\n/// first we write parsers for the smallest elements (here a space character),\n/// then we'll combine them in larger parsers\nfn sp<'a, E: ParseError<&'a str>>(i: &'a str) -> IResult<&'a str, &'a str, E> {\n let chars = \" \\t\\r\\n\";\n\n // nom combinators like `take_while` return a function. That function is the\n // parser,to which we can pass the input\n take_while(move |c| chars.contains(c))(i)\n}\n\n/// A nom parser has the following signature:\n/// `Input -> IResult`, with `IResult` defined as:\n/// `type IResult = Result<(I, O), Err>;`\n///\n/// most of the times you can ignore the error type and use the default (but this\n/// examples shows custom error types later on!)\n///\n/// Here we use `&str` as input type, but nom parsers can be generic over\n/// the input type, and work directly with `&[u8]` or any other type that\n/// implements the required traits.\n///\n/// Finally, we can see here that the input and output type are both `&str`\n/// with the same lifetime tag. This means that the produced value is a subslice\n/// of the input data. and there is no allocation needed. This is the main idea\n/// behind nom's performance.\nfn parse_str<'a, E: ParseError<&'a str>>(i: &'a str) -> IResult<&'a str, &'a str, E> {\n escaped(alphanumeric, '\\\\', one_of(\"\\\"n\\\\\"))(i)\n}\n\n/// `tag(string)` generates a parser that recognizes the argument string.\n///\n/// we can combine it with other functions, like `value` that takes another\n/// parser, and if that parser returns without an error, returns a given\n/// constant value.\n///\n/// `alt` is another combinator that tries multiple parsers one by one, until\n/// one of them succeeds\nfn boolean<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, bool, E> {\n // This is a parser that returns `true` if it sees the string \"true\", and\n // an error otherwise\n let parse_true = value(true, tag(\"true\"));\n\n // This is a parser that returns `false` if it sees the string \"false\", and\n // an error otherwise\n let parse_false = value(false, tag(\"false\"));\n\n // `alt` combines the two parsers. It returns the result of the first\n // successful parser, or an error\n alt((parse_true, parse_false)).parse(input)\n}\n\nfn null<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, (), E> {\n value((), tag(\"null\")).parse(input)\n}\n\n/// this parser combines the previous `parse_str` parser, that recognizes the\n/// interior of a string, with a parse to recognize the double quote character,\n/// before the string (using `preceded`) and after the string (using `terminated`).\n///\n/// `context` and `cut` are related to error management:\n/// - `cut` transforms an `Err::Error(e)` in `Err::Failure(e)`, signaling to\n/// combinators like `alt` that they should not try other parsers. We were in the\n/// right branch (since we found the `\"` character) but encountered an error when\n/// parsing the string\n/// - `context` lets you add a static string to provide more information in the\n/// error chain (to indicate which parser had an error)\nfn string<'a, E: ParseError<&'a str> + ContextError<&'a str>>(\n i: &'a str,\n) -> IResult<&'a str, &'a str, E> {\n context(\n \"string\",\n preceded(char('\\\"'), cut(terminated(parse_str, char('\\\"')))),\n )\n .parse(i)\n}\n\n/// some combinators, like `separated_list0` or `many0`, will call a parser repeatedly,\n/// accumulating results in a `Vec`, until it encounters an error.\n/// If you want more control on the parser application, check out the `iterator`\n/// combinator (cf `examples/iterator.rs`)\nfn array<'a, E: ParseError<&'a str> + ContextError<&'a str>>(\n i: &'a str,\n) -> IResult<&'a str, Vec, E> {\n context(\n \"array\",\n preceded(\n char('['),\n cut(terminated(\n separated_list0(preceded(sp, char(',')), json_value),\n preceded(sp, char(']')),\n )),\n ),\n )\n .parse(i)\n}\n\nfn key_value<'a, E: ParseError<&'a str> + ContextError<&'a str>>(\n i: &'a str,\n) -> IResult<&'a str, (&'a str, JsonValue), E> {\n separated_pair(\n preceded(sp, string),\n cut(preceded(sp, char(':'))),\n json_value,\n )\n .parse(i)\n}\n\nfn hash<'a, E: ParseError<&'a str> + ContextError<&'a str>>(\n i: &'a str,\n) -> IResult<&'a str, HashMap, E> {\n context(\n \"map\",\n preceded(\n char('{'),\n cut(terminated(\n map(\n separated_list0(preceded(sp, char(',')), key_value),\n |tuple_vec| {\n tuple_vec\n .into_iter()\n .map(|(k, v)| (String::from(k), v))\n .collect()\n },\n ),\n preceded(sp, char('}')),\n )),\n ),\n )\n .parse(i)\n}\n\n/// here, we apply the space parser before trying to parse a value\nfn json_value<'a, E: ParseError<&'a str> + ContextError<&'a str>>(\n i: &'a str,\n) -> IResult<&'a str, JsonValue, E> {\n preceded(\n sp,\n alt((\n map(hash, JsonValue::Object),\n map(array, JsonValue::Array),\n map(string, |s| JsonValue::Str(String::from(s))),\n map(double, JsonValue::Num),\n map(boolean, JsonValue::Boolean),\n map(null, |_| JsonValue::Null),\n )),\n )\n .parse(i)\n}\n\n/// the root element of a JSON parser is either an object or an array\nfn root<'a, E: ParseError<&'a str> + ContextError<&'a str>>(\n i: &'a str,\n) -> IResult<&'a str, JsonValue, E> {\n delimited(\n sp,\n alt((\n map(hash, JsonValue::Object),\n map(array, JsonValue::Array),\n map(null, |_| JsonValue::Null),\n )),\n opt(sp),\n )\n .parse(i)\n}\n\nfn main() {\n let data = \" { \\\"a\\\"\\t: 42,\n \\\"b\\\": [ \\\"x\\\", \\\"y\\\", 12 ] ,\n \\\"c\\\": { \\\"hello\\\" : \\\"world\\\"\n }\n } \";\n\n println!(\n \"will try to parse valid JSON data:\\n\\n**********\\n{}\\n**********\\n\",\n data\n );\n\n // this will print:\n // Ok(\n // (\n // \"\",\n // Object(\n // {\n // \"b\": Array(\n // [\n // Str(\n // \"x\",\n // ),\n // Str(\n // \"y\",\n // ),\n // Num(\n // 12.0,\n // ),\n // ],\n // ),\n // \"c\": Object(\n // {\n // \"hello\": Str(\n // \"world\",\n // ),\n // },\n // ),\n // \"a\": Num(\n // 42.0,\n // ),\n // },\n // ),\n // ),\n // )\n println!(\n \"parsing a valid file:\\n{:#?}\\n\",\n root::<(&str, ErrorKind)>(data)\n );\n\n let data = \" { \\\"a\\\"\\t: 42,\n \\\"b\\\": [ \\\"x\\\", \\\"y\\\", 12 ] ,\n \\\"c\\\": { 1\\\"hello\\\" : \\\"world\\\"\n }\n } \";\n\n println!(\n \"will try to parse invalid JSON data:\\n\\n**********\\n{}\\n**********\\n\",\n data\n );\n\n // here we use `(Input, ErrorKind)` as error type, which is used by default\n // if you don't specify it. It contains the position of the error and some\n // info on which parser encountered it.\n // It is fast and small, but does not provide much context.\n //\n // This will print:\n // basic errors - `root::<(&str, ErrorKind)>(data)`:\n // Err(\n // Failure(\n // (\n // \"1\\\"hello\\\" : \\\"world\\\"\\n }\\n } \",\n // Char,\n // ),\n // ),\n // )\n println!(\n \"basic errors - `root::<(&str, ErrorKind)>(data)`:\\n{:#?}\\n\",\n root::<(&str, ErrorKind)>(data)\n );\n\n // nom also provides `the `VerboseError` type, which will generate a sort\n // of backtrace of the path through the parser, accumulating info on input positions\n // and affected parsers.\n //\n // This will print:\n //\n // parsed verbose: Err(\n // Failure(\n // VerboseError {\n // errors: [\n // (\n // \"1\\\"hello\\\" : \\\"world\\\"\\n }\\n } \",\n // Char(\n // '}',\n // ),\n // ),\n // (\n // \"{ 1\\\"hello\\\" : \\\"world\\\"\\n }\\n } \",\n // Context(\n // \"map\",\n // ),\n // ),\n // (\n // \"{ \\\"a\\\"\\t: 42,\\n \\\"b\\\": [ \\\"x\\\", \\\"y\\\", 12 ] ,\\n \\\"c\\\": { 1\\\"hello\\\" : \\\"world\\\"\\n }\\n } \",\n // Context(\n // \"map\",\n // ),\n // ),\n // ],\n // },\n // ),\n // )\n println!(\"parsed verbose: {:#?}\", root::>(data));\n\n match root::>(data) {\n Err(Err::Error(e)) | Err(Err::Failure(e)) => {\n // here we use the `convert_error` function, to transform a `VerboseError<&str>`\n // into a printable trace.\n //\n // This will print:\n // verbose errors - `root::(data)`:\n // 0: at line 2:\n // \"c\": { 1\"hello\" : \"world\"\n // ^\n // expected '}', found 1\n //\n // 1: at line 2, in map:\n // \"c\": { 1\"hello\" : \"world\"\n // ^\n //\n // 2: at line 0, in map:\n // { \"a\" : 42,\n // ^\n println!(\n \"verbose errors - `root::(data)`:\\n{}\",\n convert_error(data, e)\n );\n }\n _ => {}\n }\n\n assert!(root::<(&str, ErrorKind)>(\"null\").is_ok());\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "string.rs", "content": "#![cfg(feature = \"alloc\")]\n\nuse nom::branch::alt;\nuse nom::bytes::streaming::{is_not, take_while_m_n};\nuse nom::character::streaming::{char, multispace1};\nuse nom::combinator::{map, map_opt, map_res, value, verify};\nuse nom::error::{FromExternalError, ParseError};\nuse nom::multi::fold;\nuse nom::sequence::{delimited, preceded};\nuse nom::{IResult, Parser};\n\n// parser combinators are constructed from the bottom up:\n// first we write parsers for the smallest elements (escaped characters),\n// then combine them into larger parsers.\n\n/// Parse a unicode sequence, of the form u{XXXX}, where XXXX is 1 to 6\n/// hexadecimal numerals. We will combine this later with parse_escaped_char\n/// to parse sequences like \\u{00AC}.\nfn parse_unicode<'a, E>(input: &'a str) -> IResult<&'a str, char, E>\nwhere\n E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,\n{\n // `take_while_m_n` parses between `m` and `n` bytes (inclusive) that match\n // a predicate. `parse_hex` here parses between 1 and 6 hexadecimal numerals.\n let parse_hex = take_while_m_n(1, 6, |c: char| c.is_ascii_hexdigit());\n\n // `preceded` takes a prefix parser, and if it succeeds, returns the result\n // of the body parser. In this case, it parses u{XXXX}.\n let parse_delimited_hex = preceded(\n char('u'),\n // `delimited` is like `preceded`, but it parses both a prefix and a suffix.\n // It returns the result of the middle parser. In this case, it parses\n // {XXXX}, where XXXX is 1 to 6 hex numerals, and returns XXXX\n delimited(char('{'), parse_hex, char('}')),\n );\n\n // `map_res` takes the result of a parser and applies a function that returns\n // a Result. In this case we take the hex bytes from parse_hex and attempt to\n // convert them to a u32.\n let parse_u32 = map_res(parse_delimited_hex, move |hex| u32::from_str_radix(hex, 16));\n\n // map_opt is like map_res, but it takes an Option instead of a Result. If\n // the function returns None, map_opt returns an error. In this case, because\n // not all u32 values are valid unicode code points, we have to fallibly\n // convert to char with from_u32.\n map_opt(parse_u32, std::char::from_u32).parse(input)\n}\n\n/// Parse an escaped character: \\n, \\t, \\r, \\u{00AC}, etc.\nfn parse_escaped_char<'a, E>(input: &'a str) -> IResult<&'a str, char, E>\nwhere\n E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,\n{\n preceded(\n char('\\\\'),\n // `alt` tries each parser in sequence, returning the result of\n // the first successful match\n alt((\n parse_unicode,\n // The `value` parser returns a fixed value (the first argument) if its\n // parser (the second argument) succeeds. In these cases, it looks for\n // the marker characters (n, r, t, etc) and returns the matching\n // character (\\n, \\r, \\t, etc).\n value('\\n', char('n')),\n value('\\r', char('r')),\n value('\\t', char('t')),\n value('\\u{08}', char('b')),\n value('\\u{0C}', char('f')),\n value('\\\\', char('\\\\')),\n value('/', char('/')),\n value('\"', char('\"')),\n )),\n )\n .parse(input)\n}\n\n/// Parse a backslash, followed by any amount of whitespace. This is used later\n/// to discard any escaped whitespace.\nfn parse_escaped_whitespace<'a, E: ParseError<&'a str>>(\n input: &'a str,\n) -> IResult<&'a str, &'a str, E> {\n preceded(char('\\\\'), multispace1).parse(input)\n}\n\n/// Parse a non-empty block of text that doesn't include \\ or \"\nfn parse_literal<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, &'a str, E> {\n // `is_not` parses a string of 0 or more characters that aren't one of the\n // given characters.\n let not_quote_slash = is_not(\"\\\"\\\\\");\n\n // `verify` runs a parser, then runs a verification function on the output of\n // the parser. The verification function accepts out output only if it\n // returns true. In this case, we want to ensure that the output of is_not\n // is non-empty.\n verify(not_quote_slash, |s: &str| !s.is_empty()).parse(input)\n}\n\n/// A string fragment contains a fragment of a string being parsed: either\n/// a non-empty Literal (a series of non-escaped characters), a single\n/// parsed escaped character, or a block of escaped whitespace.\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\nenum StringFragment<'a> {\n Literal(&'a str),\n EscapedChar(char),\n EscapedWS,\n}\n\n/// Combine parse_literal, parse_escaped_whitespace, and parse_escaped_char\n/// into a StringFragment.\nfn parse_fragment<'a, E>(input: &'a str) -> IResult<&'a str, StringFragment<'a>, E>\nwhere\n E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,\n{\n alt((\n // The `map` combinator runs a parser, then applies a function to the output\n // of that parser.\n map(parse_literal, StringFragment::Literal),\n map(parse_escaped_char, StringFragment::EscapedChar),\n value(StringFragment::EscapedWS, parse_escaped_whitespace),\n ))\n .parse(input)\n}\n\n/// Parse a string. Use a loop of parse_fragment and push all of the fragments\n/// into an output string.\nfn parse_string<'a, E>(input: &'a str) -> IResult<&'a str, String, E>\nwhere\n E: ParseError<&'a str> + FromExternalError<&'a str, std::num::ParseIntError>,\n{\n // fold is the equivalent of iterator::fold. It runs a parser in a loop,\n // and for each output value, calls a folding function on each output value.\n let build_string = fold(\n 0..,\n // Our parser function \u2013 parses a single string fragment\n parse_fragment,\n // Our init value, an empty string\n String::new,\n // Our folding function. For each fragment, append the fragment to the\n // string.\n |mut string, fragment| {\n match fragment {\n StringFragment::Literal(s) => string.push_str(s),\n StringFragment::EscapedChar(c) => string.push(c),\n StringFragment::EscapedWS => {}\n }\n string\n },\n );\n\n // Finally, parse the string. Note that, if `build_string` could accept a raw\n // \" character, the closing delimiter \" would never match. When using\n // `delimited` with a looping parser (like fold), be sure that the\n // loop won't accidentally match your closing delimiter!\n delimited(char('\"'), build_string, char('\"')).parse(input)\n}\n\nfn main() {\n let data = \"\\\"abc\\\"\";\n println!(\"EXAMPLE 1:\\nParsing a simple input string: {}\", data);\n let result = parse_string::<()>(data);\n assert_eq!(result, Ok((\"\", String::from(\"abc\"))));\n println!(\"Result: {}\\n\\n\", result.unwrap().1);\n\n let data = \"\\\"tab:\\\\tafter tab, newline:\\\\nnew line, quote: \\\\\\\", emoji: \\\\u{1F602}, newline:\\\\nescaped whitespace: \\\\ abc\\\"\";\n println!(\n \"EXAMPLE 2:\\nParsing a string with escape sequences, newline literal, and escaped whitespace:\\n\\n{}\\n\",\n data\n );\n let result = parse_string::<()>(data);\n assert_eq!(\n result,\n Ok((\n \"\",\n String::from(\"tab:\\tafter tab, newline:\\nnew line, quote: \\\", emoji: \ud83d\ude02, newline:\\nescaped whitespace: abc\")\n ))\n );\n println!(\"Result:\\n\\n{}\", result.unwrap().1);\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "s_expression.rs", "content": "#![cfg(feature = \"alloc\")]\n\nuse nom::{\n branch::alt,\n bytes::complete::tag,\n character::complete::{alpha1, char, digit1, multispace0, multispace1, one_of},\n combinator::{cut, map, map_res, opt},\n error::context,\n multi::many,\n sequence::{delimited, preceded, terminated},\n IResult, Parser,\n};\nuse nom_language::error::VerboseError;\n\n/// We start by defining the types that define the shape of data that we want.\n/// In this case, we want something tree-like\n\n/// Starting from the most basic, we define some built-in functions that our lisp has\n#[derive(Debug, Eq, PartialEq, Clone, Copy)]\npub enum BuiltIn {\n Plus,\n Minus,\n Times,\n Divide,\n Equal,\n Not,\n}\n\n/// We now wrap this type and a few other primitives into our Atom type.\n/// Remember from before that Atoms form one half of our language.\n\n#[derive(Debug, Eq, PartialEq, Clone)]\npub enum Atom {\n Num(i32),\n Keyword(String),\n Boolean(bool),\n BuiltIn(BuiltIn),\n}\n\n/// The remaining half is Lists. We implement these as recursive Expressions.\n/// For a list of numbers, we have `'(1 2 3)`, which we'll parse to:\n/// ```\n/// Expr::Quote(vec![Expr::Constant(Atom::Num(1)),\n/// Expr::Constant(Atom::Num(2)),\n/// Expr::Constant(Atom::Num(3))])\n/// Quote takes an S-expression and prevents evaluation of it, making it a data\n/// structure that we can deal with programmatically. Thus any valid expression\n/// is also a valid data structure in Lisp itself.\n\n#[derive(Debug, Eq, PartialEq, Clone)]\npub enum Expr {\n Constant(Atom),\n /// (func-name arg1 arg2)\n Application(Box, Vec),\n /// (if predicate do-this)\n If(Box, Box),\n /// (if predicate do-this otherwise-do-this)\n IfElse(Box, Box, Box),\n /// '(3 (if (+ 3 3) 4 5) 7)\n Quote(Vec),\n}\n\n/// Continuing the trend of starting from the simplest piece and building up,\n/// we start by creating a parser for the built-in operator functions.\nfn parse_builtin_op(i: &str) -> IResult<&str, BuiltIn, VerboseError<&str>> {\n // one_of matches one of the characters we give it\n let (i, t) = one_of(\"+-*/=\")(i)?;\n\n // because we are matching single character tokens, we can do the matching logic\n // on the returned value\n Ok((\n i,\n match t {\n '+' => BuiltIn::Plus,\n '-' => BuiltIn::Minus,\n '*' => BuiltIn::Times,\n '/' => BuiltIn::Divide,\n '=' => BuiltIn::Equal,\n _ => unreachable!(),\n },\n ))\n}\n\nfn parse_builtin(i: &str) -> IResult<&str, BuiltIn, VerboseError<&str>> {\n // alt gives us the result of first parser that succeeds, of the series of\n // parsers we give it\n alt((\n parse_builtin_op,\n // map lets us process the parsed output, in this case we know what we parsed,\n // so we ignore the input and return the BuiltIn directly\n map(tag(\"not\"), |_| BuiltIn::Not),\n ))\n .parse(i)\n}\n\n/// Our boolean values are also constant, so we can do it the same way\nfn parse_bool(i: &str) -> IResult<&str, Atom, VerboseError<&str>> {\n alt((\n map(tag(\"#t\"), |_| Atom::Boolean(true)),\n map(tag(\"#f\"), |_| Atom::Boolean(false)),\n ))\n .parse(i)\n}\n\n/// The next easiest thing to parse are keywords.\n/// We introduce some error handling combinators: `context` for human readable errors\n/// and `cut` to prevent back-tracking.\n///\n/// Put plainly: `preceded(tag(\":\"), cut(alpha1))` means that once we see the `:`\n/// character, we have to see one or more alphabetic characters or the input is invalid.\nfn parse_keyword(i: &str) -> IResult<&str, Atom, VerboseError<&str>> {\n map(\n context(\"keyword\", preceded(tag(\":\"), cut(alpha1))),\n |sym_str: &str| Atom::Keyword(sym_str.to_string()),\n )\n .parse(i)\n}\n\n/// Next up is number parsing. We're keeping it simple here by accepting any number (> 1)\n/// of digits but ending the program if it doesn't fit into an i32.\nfn parse_num(i: &str) -> IResult<&str, Atom, VerboseError<&str>> {\n alt((\n map_res(digit1, |digit_str: &str| {\n digit_str.parse::().map(Atom::Num)\n }),\n map(preceded(tag(\"-\"), digit1), |digit_str: &str| {\n Atom::Num(-digit_str.parse::().unwrap())\n }),\n ))\n .parse(i)\n}\n\n/// Now we take all these simple parsers and connect them.\n/// We can now parse half of our language!\nfn parse_atom(i: &str) -> IResult<&str, Atom, VerboseError<&str>> {\n alt((\n parse_num,\n parse_bool,\n map(parse_builtin, Atom::BuiltIn),\n parse_keyword,\n ))\n .parse(i)\n}\n\n/// We then add the Expr layer on top\nfn parse_constant(i: &str) -> IResult<&str, Expr, VerboseError<&str>> {\n map(parse_atom, Expr::Constant).parse(i)\n}\n\n/// Before continuing, we need a helper function to parse lists.\n/// A list starts with `(` and ends with a matching `)`.\n/// By putting whitespace and newline parsing here, we can avoid having to worry about it\n/// in much of the rest of the parser.\n///\n/// Unlike the previous functions, this function doesn't take or consume input, instead it\n/// takes a parsing function and returns a new parsing function.\nfn s_exp<'a, O1, F>(inner: F) -> impl Parser<&'a str, Output = O1, Error = VerboseError<&'a str>>\nwhere\n F: Parser<&'a str, Output = O1, Error = VerboseError<&'a str>>,\n{\n delimited(\n char('('),\n preceded(multispace0, inner),\n context(\"closing paren\", cut(preceded(multispace0, char(')')))),\n )\n}\n\n/// We can now use our new combinator to define the rest of the `Expr`s.\n///\n/// Starting with function application, we can see how the parser mirrors our data\n/// definitions: our definition is `Application(Box, Vec)`, so we know\n/// that we need to parse an expression and then parse 0 or more expressions, all\n/// wrapped in an S-expression.\n///\n/// We can sequence parsers together by grouping them in a tuple, forming a new\n/// parser returning a tuple containing the result of each parser in the same order,\n/// and then map over it to transform the output into an `Expr::Application`\nfn parse_application(i: &str) -> IResult<&str, Expr, VerboseError<&str>> {\n let application_inner = map((parse_expr, many(0.., parse_expr)), |(head, tail)| {\n Expr::Application(Box::new(head), tail)\n });\n // finally, we wrap it in an s-expression\n s_exp(application_inner).parse(i)\n}\n\n/// Because `Expr::If` and `Expr::IfElse` are so similar (we easily could have\n/// defined `Expr::If` to have an `Option` for the else block), we parse both\n/// in a single function.\n///\n/// In fact, we define our parser as if `Expr::If` was defined with an Option in it,\n/// we have the `opt` combinator which fits very nicely here.\nfn parse_if(i: &str) -> IResult<&str, Expr, VerboseError<&str>> {\n let if_inner = context(\n \"if expression\",\n map(\n preceded(\n // here to avoid ambiguity with other names starting with `if`, if we added\n // variables to our language, we say that if must be terminated by at least\n // one whitespace character\n terminated(tag(\"if\"), multispace1),\n cut((parse_expr, parse_expr, opt(parse_expr))),\n ),\n |(pred, true_branch, maybe_false_branch)| {\n if let Some(false_branch) = maybe_false_branch {\n Expr::IfElse(\n Box::new(pred),\n Box::new(true_branch),\n Box::new(false_branch),\n )\n } else {\n Expr::If(Box::new(pred), Box::new(true_branch))\n }\n },\n ),\n );\n s_exp(if_inner).parse(i)\n}\n\n/// A quoted S-expression is list data structure.\n///\n/// This example doesn't have the symbol atom, but by adding variables and changing\n/// the definition of quote to not always be around an S-expression, we'd get them\n/// naturally.\nfn parse_quote(i: &str) -> IResult<&str, Expr, VerboseError<&str>> {\n // this should look very straight-forward after all we've done:\n // we find the `'` (quote) character, use cut to say that we're unambiguously\n // looking for an s-expression of 0 or more expressions, and then parse them\n map(\n context(\n \"quote\",\n preceded(tag(\"'\"), cut(s_exp(many(0.., parse_expr)))),\n ),\n Expr::Quote,\n )\n .parse(i)\n}\n\n/// We tie them all together again, making a top-level expression parser!\n\nfn parse_expr(i: &str) -> IResult<&str, Expr, VerboseError<&str>> {\n preceded(\n multispace0,\n alt((parse_constant, parse_application, parse_if, parse_quote)),\n )\n .parse(i)\n}\n\n/// And that's it!\n/// We can now parse our entire lisp language.\n///\n/// But in order to make it a little more interesting, we can hack together\n/// a little interpreter to take an Expr, which is really an\n/// [Abstract Syntax Tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree) (AST),\n/// and give us something back\n\n/// To start we define a couple of helper functions\nfn get_num_from_expr(e: Expr) -> Option {\n if let Expr::Constant(Atom::Num(n)) = e {\n Some(n)\n } else {\n None\n }\n}\n\nfn get_bool_from_expr(e: Expr) -> Option {\n if let Expr::Constant(Atom::Boolean(b)) = e {\n Some(b)\n } else {\n None\n }\n}\n\n/// This function tries to reduce the AST.\n/// This has to return an Expression rather than an Atom because quoted s_expressions\n/// can't be reduced\nfn eval_expression(e: Expr) -> Option {\n match e {\n // Constants and quoted s-expressions are our base-case\n Expr::Constant(_) | Expr::Quote(_) => Some(e),\n // we then recursively `eval_expression` in the context of our special forms\n // and built-in operators\n Expr::If(pred, true_branch) => {\n let reduce_pred = eval_expression(*pred)?;\n if get_bool_from_expr(reduce_pred)? {\n eval_expression(*true_branch)\n } else {\n None\n }\n }\n Expr::IfElse(pred, true_branch, false_branch) => {\n let reduce_pred = eval_expression(*pred)?;\n if get_bool_from_expr(reduce_pred)? {\n eval_expression(*true_branch)\n } else {\n eval_expression(*false_branch)\n }\n }\n Expr::Application(head, tail) => {\n let reduced_head = eval_expression(*head)?;\n let reduced_tail = tail\n .into_iter()\n .map(eval_expression)\n .collect::>>()?;\n if let Expr::Constant(Atom::BuiltIn(bi)) = reduced_head {\n Some(Expr::Constant(match bi {\n BuiltIn::Plus => Atom::Num(\n reduced_tail\n .into_iter()\n .map(get_num_from_expr)\n .collect::>>()?\n .into_iter()\n .sum(),\n ),\n BuiltIn::Times => Atom::Num(\n reduced_tail\n .into_iter()\n .map(get_num_from_expr)\n .collect::>>()?\n .into_iter()\n .product(),\n ),\n BuiltIn::Equal => Atom::Boolean(\n reduced_tail\n .iter()\n .zip(reduced_tail.iter().skip(1))\n .all(|(a, b)| a == b),\n ),\n BuiltIn::Not => {\n if reduced_tail.len() != 1 {\n return None;\n } else {\n Atom::Boolean(!get_bool_from_expr(reduced_tail.first().cloned().unwrap())?)\n }\n }\n BuiltIn::Minus => Atom::Num(if let Some(first_elem) = reduced_tail.first().cloned() {\n let fe = get_num_from_expr(first_elem)?;\n reduced_tail\n .into_iter()\n .map(get_num_from_expr)\n .collect::>>()?\n .into_iter()\n .skip(1)\n .fold(fe, |a, b| a - b)\n } else {\n Default::default()\n }),\n BuiltIn::Divide => Atom::Num(if let Some(first_elem) = reduced_tail.first().cloned() {\n let fe = get_num_from_expr(first_elem)?;\n reduced_tail\n .into_iter()\n .map(get_num_from_expr)\n .collect::>>()?\n .into_iter()\n .skip(1)\n .fold(fe, |a, b| a / b)\n } else {\n Default::default()\n }),\n }))\n } else {\n None\n }\n }\n }\n}\n\n/// And we add one more top-level function to tie everything together, letting\n/// us call eval on a string directly\nfn eval_from_str(src: &str) -> Result {\n parse_expr(src)\n .map_err(|e: nom::Err>| format!(\"{:#?}\", e))\n .and_then(|(_, exp)| eval_expression(exp).ok_or_else(|| \"Eval failed\".to_string()))\n}\n\nfn main() {\n let expression_1 = \"((if (= (+ 3 (/ 9 3))\n (* 2 3))\n /)\n 456 123)\";\n println!(\n \"\\\"{}\\\"\\nevaled gives us: {:?}\",\n expression_1,\n eval_from_str(expression_1)\n );\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "iterator.rs", "content": "use std::collections::HashMap;\nuse std::iter::Iterator;\n\nuse nom::bytes::complete::tag;\nuse nom::character::complete::alphanumeric1;\nuse nom::combinator::iterator;\nuse nom::sequence::{separated_pair, terminated};\nuse nom::IResult;\n\nfn main() {\n let mut data = \"abcabcabcabc\";\n\n fn parser(i: &str) -> IResult<&str, &str> {\n tag(\"abc\")(i)\n }\n\n // `from_fn` (available from Rust 1.34) can create an iterator\n // from a closure\n let it = std::iter::from_fn(move || {\n match parser(data) {\n // when successful, a nom parser returns a tuple of\n // the remaining input and the output value.\n // So we replace the captured input data with the\n // remaining input, to be parsed on the next call\n Ok((i, o)) => {\n data = i;\n Some(o)\n }\n _ => None,\n }\n });\n\n for value in it {\n println!(\"parser returned: {}\", value);\n }\n\n println!(\"\\n********************\\n\");\n\n let data = \"abcabcabcabc\";\n\n // if `from_fn` is not available, it is possible to fold\n // over an iterator of functions\n let res =\n std::iter::repeat(parser)\n .take(3)\n .try_fold((data, Vec::new()), |(data, mut acc), parser| {\n parser(data).map(|(i, o)| {\n acc.push(o);\n (i, acc)\n })\n });\n\n // will print \"parser iterator returned: Ok((\"abc\", [\"abc\", \"abc\", \"abc\"]))\"\n println!(\"\\nparser iterator returned: {:?}\", res);\n\n println!(\"\\n********************\\n\");\n\n let data = \"key1:value1,key2:value2,key3:value3,;\";\n\n // `nom::combinator::iterator` will return an iterator\n // producing the parsed values. Compared to the previous\n // solutions:\n // - we can work with a normal iterator like `from_fn`\n // - we can get the remaining input afterwards, like with the `try_fold` trick\n let mut nom_it = iterator(\n data,\n terminated(\n separated_pair(alphanumeric1, tag(\":\"), alphanumeric1),\n tag(\",\"),\n ),\n );\n\n let res = nom_it\n .by_ref()\n .map(|(k, v)| (k.to_uppercase(), v))\n .collect::>();\n\n let parser_result: IResult<_, _> = nom_it.finish();\n let (remaining_input, ()) = parser_result.unwrap();\n\n // will print \"iterator returned {\"key1\": \"value1\", \"key3\": \"value3\", \"key2\": \"value2\"}, remaining input is ';'\"\n println!(\n \"iterator returned {:?}, remaining input is '{}'\",\n res, remaining_input\n );\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "json_iterator.rs", "content": "#![cfg(feature = \"alloc\")]\n\nuse nom::{\n branch::alt,\n bytes::complete::{escaped, tag, take_while},\n character::complete::{alphanumeric1 as alphanumeric, char, one_of},\n combinator::{cut, map},\n error::{context, ParseError},\n multi::separated_list0,\n number::complete::double,\n sequence::{preceded, separated_pair, terminated},\n IResult, Parser,\n};\nuse std::collections::HashMap;\n\nuse std::cell::Cell;\nuse std::str;\n\n#[derive(Clone, Debug)]\npub struct JsonValue<'a, 'b> {\n input: &'a str,\n pub offset: &'b Cell,\n}\n\nimpl<'a, 'b: 'a> JsonValue<'a, 'b> {\n pub fn new(input: &'a str, offset: &'b Cell) -> JsonValue<'a, 'b> {\n JsonValue { input, offset }\n }\n\n pub fn offset(&self, input: &'a str) {\n let offset = input.as_ptr() as usize - self.input.as_ptr() as usize;\n self.offset.set(offset);\n }\n\n pub fn data(&self) -> &'a str {\n &self.input[self.offset.get()..]\n }\n\n pub fn string(&self) -> Option<&'a str> {\n println!(\"string()\");\n match string(self.data()) {\n Ok((i, s)) => {\n self.offset(i);\n println!(\"-> {}\", s);\n Some(s)\n }\n _ => None,\n }\n }\n\n pub fn boolean(&self) -> Option {\n println!(\"boolean()\");\n match boolean(self.data()) {\n Ok((i, o)) => {\n self.offset(i);\n println!(\"-> {}\", o);\n Some(o)\n }\n _ => None,\n }\n }\n\n pub fn number(&self) -> Option {\n println!(\"number()\");\n match double::<_, ()>(self.data()) {\n Ok((i, o)) => {\n self.offset(i);\n println!(\"-> {}\", o);\n Some(o)\n }\n _ => None,\n }\n }\n\n pub fn array(&self) -> Option>> {\n println!(\"array()\");\n\n match tag::<_, _, ()>(\"[\")(self.data()) {\n Err(_) => None,\n Ok((i, _)) => {\n println!(\"[\");\n self.offset(i);\n let mut first = true;\n let mut done = false;\n let mut previous = std::usize::MAX;\n\n let v = self.clone();\n\n Some(std::iter::from_fn(move || {\n if done {\n return None;\n }\n\n // if we ignored one of the items, skip over the value\n if v.offset.get() == previous {\n println!(\"skipping value\");\n if let Ok((i, _)) = value(v.data()) {\n v.offset(i);\n }\n }\n\n if let Ok((i, _)) = tag::<_, _, ()>(\"]\")(v.data()) {\n println!(\"]\");\n v.offset(i);\n done = true;\n return None;\n };\n\n if first {\n first = false;\n } else {\n match tag::<_, _, ()>(\",\")(v.data()) {\n Ok((i, _)) => {\n println!(\",\");\n v.offset(i);\n }\n Err(_) => {\n done = true;\n return None;\n }\n }\n }\n\n println!(\"-> {}\", v.data());\n previous = v.offset.get();\n Some(v.clone())\n }))\n }\n }\n }\n\n pub fn object(&self) -> Option)>> {\n println!(\"object()\");\n match tag::<_, _, ()>(\"{\")(self.data()) {\n Err(_) => None,\n Ok((i, _)) => {\n self.offset(i);\n\n println!(\"{{\");\n\n let mut first = true;\n let mut done = false;\n let mut previous = std::usize::MAX;\n\n let v = self.clone();\n\n Some(std::iter::from_fn(move || {\n if done {\n return None;\n }\n\n // if we ignored one of the items, skip over the value\n if v.offset.get() == previous {\n println!(\"skipping value\");\n if let Ok((i, _)) = value(v.data()) {\n v.offset(i);\n }\n }\n\n if let Ok((i, _)) = tag::<_, _, ()>(\"}\")(v.data()) {\n println!(\"}}\");\n v.offset(i);\n done = true;\n return None;\n };\n\n if first {\n first = false;\n } else {\n match tag::<_, _, ()>(\",\")(v.data()) {\n Ok((i, _)) => {\n println!(\",\");\n v.offset(i);\n }\n Err(_) => {\n done = true;\n return None;\n }\n }\n }\n\n match string(v.data()) {\n Ok((i, key)) => {\n v.offset(i);\n\n match tag::<_, _, ()>(\":\")(v.data()) {\n Err(_) => None,\n Ok((i, _)) => {\n v.offset(i);\n\n previous = v.offset.get();\n\n println!(\"-> {} => {}\", key, v.data());\n Some((key, v.clone()))\n }\n }\n }\n _ => None,\n }\n }))\n }\n }\n }\n}\n\nfn sp<'a, E: ParseError<&'a str>>(i: &'a str) -> IResult<&'a str, &'a str, E> {\n let chars = \" \\t\\r\\n\";\n\n take_while(move |c| chars.contains(c))(i)\n}\n\nfn parse_str<'a, E: ParseError<&'a str>>(i: &'a str) -> IResult<&'a str, &'a str, E> {\n escaped(alphanumeric, '\\\\', one_of(\"\\\"n\\\\\"))(i)\n}\n\nfn string(i: &str) -> IResult<&str, &str> {\n context(\n \"string\",\n preceded(char('\\\"'), cut(terminated(parse_str, char('\\\"')))),\n )\n .parse(i)\n}\n\nfn boolean(input: &str) -> IResult<&str, bool> {\n alt((map(tag(\"false\"), |_| false), map(tag(\"true\"), |_| true))).parse(input)\n}\n\nfn array(i: &str) -> IResult<&str, ()> {\n context(\n \"array\",\n preceded(\n char('['),\n cut(terminated(\n map(separated_list0(preceded(sp, char(',')), value), |_| ()),\n preceded(sp, char(']')),\n )),\n ),\n )\n .parse(i)\n}\n\nfn key_value(i: &str) -> IResult<&str, (&str, ())> {\n separated_pair(preceded(sp, string), cut(preceded(sp, char(':'))), value).parse(i)\n}\n\nfn hash(i: &str) -> IResult<&str, ()> {\n context(\n \"map\",\n preceded(\n char('{'),\n cut(terminated(\n map(separated_list0(preceded(sp, char(',')), key_value), |_| ()),\n preceded(sp, char('}')),\n )),\n ),\n )\n .parse(i)\n}\n\nfn value(i: &str) -> IResult<&str, ()> {\n preceded(\n sp,\n alt((\n hash,\n array,\n map(string, |_| ()),\n map(double, |_| ()),\n map(boolean, |_| ()),\n )),\n )\n .parse(i)\n}\n\n/// object(input) -> iterator over (key, JsonValue)\n/// array(input) -> iterator over JsonValue\n///\n/// JsonValue.string -> iterator over String (returns None after first successful call)\n///\n/// object(input).filter(|(k, _)| k == \"users\").flatten(|(_, v)| v.object()).filter(|(k, _)| k == \"city\").flatten(|(_,v)| v.string())\nfn main() {\n \\\"users\\\": {\n \\\"user1\\\" : { \\\"city\\\": \\\"Nantes\\\", \\\"country\\\": \\\"France\\\" },\n \\\"user2\\\" : { \\\"city\\\": \\\"Bruxelles\\\", \\\"country\\\": \\\"Belgium\\\" },\n \\\"user3\\\": { \\\"city\\\": \\\"Paris\\\", \\\"country\\\": \\\"France\\\", \\\"age\\\": 30 }\n },\n \\\"countries\\\": [\\\"France\\\", \\\"Belgium\\\"]\n }\";\n let data = \"{\\\"users\\\":{\\\"user1\\\":{\\\"city\\\":\\\"Nantes\\\",\\\"country\\\":\\\"France\\\"},\\\"user2\\\":{\\\"city\\\":\\\"Bruxelles\\\",\\\"country\\\":\\\"Belgium\\\"},\\\"user3\\\":{\\\"city\\\":\\\"Paris\\\",\\\"country\\\":\\\"France\\\",\\\"age\\\":30}},\\\"countries\\\":[\\\"France\\\",\\\"Belgium\\\"]}\";\n\n let offset = Cell::new(0);\n {\n let parser = JsonValue::new(data, &offset);\n\n if let Some(o) = parser.object() {\n let s: HashMap<&str, &str> = o\n .filter(|(k, _)| *k == \"users\")\n .filter_map(|(_, v)| v.object())\n .flatten()\n .filter_map(|(user, v)| v.object().map(|o| (user, o)))\n .flat_map(|(user, o)| {\n o.filter(|(k, _)| *k == \"city\")\n .filter_map(move |(_, v)| v.string().map(|s| (user, s)))\n })\n .collect();\n\n println!(\"res = {:?}\", s);\n }\n };\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "number.rs", "content": "#[global_allocator]\nstatic ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;\n\nuse codspeed_criterion_compat::*;\nuse nom::number::complete;\n\nfn parser(i: &[u8]) -> nom::IResult<&[u8], u64> {\n complete::be_u64(i)\n}\n\nfn number(c: &mut Criterion) {\n let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];\n\n parser(&data[..]).expect(\"should parse correctly\");\n c.bench_function(\"number\", move |b| {\n b.iter(|| parser(&data[..]).unwrap());\n });\n}\n\ncriterion_group!(benches, number);\ncriterion_main!(benches);"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "ini_str.rs", "content": "#[global_allocator]\nstatic ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;\n\nuse codspeed_criterion_compat::*;\n\nuse nom::{\n bytes::complete::{is_a, tag, take_till, take_while},\n character::complete::{alphanumeric1 as alphanumeric, char, not_line_ending, space0 as space},\n combinator::opt,\n multi::many,\n sequence::{delimited, pair, terminated, tuple},\n IResult, Parser,\n};\n\nuse std::collections::HashMap;\n\nfn is_line_ending_or_comment(chr: char) -> bool {\n chr == ';' || chr == '\\n'\n}\n\nfn space_or_line_ending(i: &str) -> IResult<&str, &str> {\n is_a(\" \\r\\n\")(i)\n}\n\nfn category(i: &str) -> IResult<&str, &str> {\n terminated(\n delimited(char('['), take_while(|c| c != ']'), char(']')),\n opt(is_a(\" \\r\\n\")),\n )\n .parse(i)\n}\n\nfn key_value(i: &str) -> IResult<&str, (&str, &str)> {\n let (i, key) = alphanumeric(i)?;\n let (i, _) = tuple((opt(space), tag(\"=\"), opt(space)))(i)?;\n let (i, val) = take_till(is_line_ending_or_comment)(i)?;\n let (i, _) = opt(space).parse_complete(i)?;\n let (i, _) = opt(pair(tag(\";\"), not_line_ending)).parse_complete(i)?;\n let (i, _) = opt(space_or_line_ending).parse_complete(i)?;\n Ok((i, (key, val)))\n}\n\nfn keys_and_values(input: &str) -> IResult<&str, HashMap<&str, &str>> {\n many(0.., key_value).parse_complete(input)\n}\n\nfn category_and_keys(i: &str) -> IResult<&str, (&str, HashMap<&str, &str>)> {\n pair(category, keys_and_values).parse_complete(i)\n}\n\nfn categories(input: &str) -> IResult<&str, HashMap<&str, HashMap<&str, &str>>> {\n many(0.., category_and_keys).parse_complete(input)\n}\n\nfn bench_ini_str(c: &mut Criterion) {\n let s = \"[owner]\nname=John Doe\norganization=Acme Widgets Inc.\n\n[database]\nserver=192.0.2.62\nport=143\nfile=payroll.dat\n\";\n\n let mut group = c.benchmark_group(\"ini str\");\n group.throughput(Throughput::Bytes(s.len() as u64));\n group.bench_function(BenchmarkId::new(\"parse\", s.len()), |b| {\n b.iter(|| categories(s).unwrap())\n });\n}\n\ncriterion_group!(benches, bench_ini_str);\ncriterion_main!(benches);"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "arithmetic.rs", "content": "#[global_allocator]\nstatic ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;\n\nuse codspeed_criterion_compat::{criterion_group, criterion_main, Criterion};\nuse nom::{\n branch::alt,\n character::complete::{char, digit1, one_of, space0},\n combinator::map_res,\n multi::fold,\n sequence::{delimited, pair},\n IResult, Parser,\n};\n\n// Parser definition\n\n// We transform an integer string into a i64, ignoring surrounding whitespaces\n// We look for a digit suite, and try to convert it.\n// If there are no digits, we look for a parenthesized expression.\nfn factor(input: &[u8]) -> IResult<&[u8], i64> {\n delimited(\n space0,\n alt((\n map_res(digit1, |digits| {\n unsafe { std::str::from_utf8_unchecked(digits) }.parse()\n }),\n delimited(char('('), expr, char(')')),\n )),\n space0,\n )\n .parse(input)\n}\n\n// We read an initial factor and for each time we find\n// a * or / operator followed by another factor, we do\n// the math by folding everything\nfn term(input: &[u8]) -> IResult<&[u8], i64> {\n let (input, init) = factor(input)?;\n fold(\n 0..,\n pair(one_of(\"*/\"), factor),\n move || init,\n |acc, (op, val)| {\n if op == '*' {\n acc * val\n } else {\n acc / val\n }\n },\n )\n .parse_complete(input)\n}\n\nfn expr(input: &[u8]) -> IResult<&[u8], i64> {\n let (input, init) = term(input)?;\n fold(\n 0..,\n pair(one_of(\"+-\"), term),\n move || init,\n |acc, (op, val)| {\n if op == '+' {\n acc + val\n } else {\n acc - val\n }\n },\n )\n .parse_complete(input)\n}\n\n#[allow(clippy::eq_op, clippy::erasing_op)]\nfn arithmetic(c: &mut Criterion) {\n let data = b\" 2*2 / ( 5 - 1) + 3 / 4 * (2 - 7 + 567 *12 /2) + 3*(1+2*( 45 /2));\";\n\n assert_eq!(\n expr(data),\n Ok((\n &b\";\"[..],\n 2 * 2 / (5 - 1) + 3 / 4 * (2 - 7 + 567 * 12 / 2) + 3 * (1 + 2 * (45 / 2)),\n ))\n );\n c.bench_function(\"arithmetic\", |b| {\n b.iter(|| expr(data).unwrap());\n });\n}\n\ncriterion_group!(benches, arithmetic);\ncriterion_main!(benches);"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "json.rs", "content": "#[global_allocator]\nstatic ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;\n\nuse codspeed_criterion_compat::*;\nuse nom::{\n branch::alt,\n bytes::{tag, take},\n character::{anychar, char, multispace0, none_of},\n combinator::{map, map_opt, map_res, value, verify},\n error::{Error, ErrorKind, FromExternalError, ParseError},\n multi::{fold, separated_list0},\n number::double,\n number::recognize_float,\n sequence::{delimited, preceded, separated_pair},\n Check, Complete, Emit, IResult, Mode, OutputM, Parser,\n};\nuse nom_language::error::VerboseError;\n\nuse std::{collections::HashMap, marker::PhantomData, num::ParseIntError};\n\n#[derive(Debug, PartialEq, Clone)]\npub enum JsonValue {\n Null,\n Bool(bool),\n Str(String),\n Num(f64),\n Array(Vec),\n Object(HashMap),\n}\n\nfn boolean<'a, E: ParseError<&'a str>>() -> impl Parser<&'a str, Output = bool, Error = E> {\n alt((value(false, tag(\"false\")), value(true, tag(\"true\"))))\n}\n\nfn u16_hex<'a, E: ParseError<&'a str> + FromExternalError<&'a str, ParseIntError>>(\n) -> impl Parser<&'a str, Output = u16, Error = E> {\n map_res(take(4usize), |s| u16::from_str_radix(s, 16))\n}\n\nfn unicode_escape<'a, E: ParseError<&'a str> + FromExternalError<&'a str, ParseIntError>>(\n) -> impl Parser<&'a str, Output = char, Error = E> {\n map_opt(\n alt((\n // Not a surrogate\n map(\n verify(u16_hex(), |cp| !(0xD800..0xE000).contains(cp)),\n |cp| cp as u32,\n ),\n // See https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF for details\n map(\n verify(\n separated_pair(u16_hex(), tag(\"\\\\u\"), u16_hex()),\n |(high, low)| (0xD800..0xDC00).contains(high) && (0xDC00..0xE000).contains(low),\n ),\n |(high, low)| {\n let high_ten = (high as u32) - 0xD800;\n let low_ten = (low as u32) - 0xDC00;\n (high_ten << 10) + low_ten + 0x10000\n },\n ),\n )),\n // Could probably be replaced with .unwrap() or _unchecked due to the verify checks\n std::char::from_u32,\n )\n}\n\nfn character<\n 'a,\n E: ParseError<&'a str> + FromExternalError<&'a str, ParseIntError> + FromExternalError<&'a str, ()>,\n>() -> impl Parser<&'a str, Output = char, Error = E> {\n Character { e: PhantomData }\n if c == '\\\\' {\n alt((\n map_res(anychar, |c| {\n Ok(match c {\n '\"' | '\\\\' | '/' => c,\n 'b' => '\\x08',\n 'f' => '\\x0C',\n 'n' => '\\n',\n 'r' => '\\r',\n 't' => '\\t',\n _ => return Err(()),\n })\n }),\n preceded(char('u'), unicode_escape()),\n ))\n .parse(input)\n } else {\n Ok((input, c))\n }*/\n}\n\nstruct Character {\n e: PhantomData,\n}\n\nimpl<'a, E> Parser<&'a str> for Character\nwhere\n E: ParseError<&'a str>\n + FromExternalError<&'a str, ParseIntError>\n + FromExternalError<&'a str, ()>,\n{\n type Output = char;\n\n type Error = E;\n\n fn process(\n &mut self,\n input: &'a str,\n ) -> nom::PResult {\n let (input, c): (&str, char) =\n none_of(\"\\\"\").process::>(input)?;\n if c == '\\\\' {\n alt((\n map_res(anychar, |c| {\n Ok(match c {\n '\"' | '\\\\' | '/' => c,\n 'b' => '\\x08',\n 'f' => '\\x0C',\n 'n' => '\\n',\n 'r' => '\\r',\n 't' => '\\t',\n _ => return Err(()),\n })\n }),\n preceded(char('u'), unicode_escape()),\n ))\n .process::(input)\n } else {\n Ok((input, OM::Output::bind(|| c)))\n }\n }\n}\n\nfn string<\n 'a,\n E: ParseError<&'a str> + FromExternalError<&'a str, ParseIntError> + FromExternalError<&'a str, ()>,\n>() -> impl Parser<&'a str, Output = String, Error = E> {\n delimited(\n char('\"'),\n fold(0.., character(), String::new, |mut string, c| {\n string.push(c);\n string\n }),\n char('\"'),\n )\n}\n\nfn ws<\n 'a,\n O,\n E: ParseError<&'a str> + FromExternalError<&'a str, ParseIntError> + FromExternalError<&'a str, ()>,\n F: Parser<&'a str, Output = O, Error = E>,\n>(\n f: F,\n) -> impl Parser<&'a str, Output = O, Error = E> {\n delimited(multispace0(), f, multispace0())\n}\n\nfn array<\n 'a,\n E: ParseError<&'a str> + FromExternalError<&'a str, ParseIntError> + FromExternalError<&'a str, ()>,\n>() -> impl Parser<&'a str, Output = Vec, Error = E> {\n delimited(\n char('['),\n ws(separated_list0(ws(char(',')), json_value())),\n char(']'),\n )\n}\n\nfn object<\n 'a,\n E: ParseError<&'a str> + FromExternalError<&'a str, ParseIntError> + FromExternalError<&'a str, ()>,\n>() -> impl Parser<&'a str, Output = HashMap, Error = E> {\n map(\n delimited(\n char('{'),\n ws(separated_list0(\n ws(char(',')),\n separated_pair(string(), ws(char(':')), json_value()),\n )),\n char('}'),\n ),\n |key_values| key_values.into_iter().collect(),\n )\n}\n\nfn json_value<'a, E: ParseError<&'a str> + FromExternalError<&'a str, ParseIntError> + FromExternalError<&'a str, ()>,\n>() -> Box> {\n use JsonValue::*;\n\n Box::new(alt((\n value(Null, tag(\"null\")),\n map(boolean(), Bool),\n map(string(), Str),\n map(double, Num),\n map(array(), Array),\n map(object(), Object),\n )))\n}\n\nfn json_value<\n 'a,\n E: ParseError<&'a str> + FromExternalError<&'a str, ParseIntError> + FromExternalError<&'a str, ()>,\n>() -> JsonParser {\n JsonParser { e: PhantomData }\n}\n\nstruct JsonParser {\n e: PhantomData,\n}\n\n// the main Parser implementation is done explicitely on a real type,\n// because haaving json_value return `impl Parser` would result in\n// \"recursive opaque type\" errors\nimpl<'a, E> Parser<&'a str> for JsonParser\nwhere\n E: ParseError<&'a str>\n + FromExternalError<&'a str, ParseIntError>\n + FromExternalError<&'a str, ()>,\n{\n type Output = JsonValue;\n type Error = E;\n\n fn process(\n &mut self,\n input: &'a str,\n ) -> nom::PResult {\n use JsonValue::*;\n\n alt((\n value(Null, tag(\"null\")),\n map(boolean(), Bool),\n map(string(), Str),\n map(double(), Num),\n map(array(), Array),\n map(object(), Object),\n ))\n .process::(input)\n }\n}\n\nfn json<\n 'a,\n E: ParseError<&'a str> + FromExternalError<&'a str, ParseIntError> + FromExternalError<&'a str, ()>,\n>() -> impl Parser<&'a str, Output = JsonValue, Error = E> {\n ws(json_value())\n}\n\nfn json_bench(c: &mut Criterion) {\n let data = \" { \\\"a\\\"\\t: 42,\n \\\"b\\\": [ \\\"x\\\", \\\"y\\\", 12 ,\\\"\\\\u2014\\\", \\\"\\\\uD83D\\\\uDE10\\\"] ,\n \\\"c\\\": { \\\"hello\\\" : \\\"world\\\"\n }\n } \";\n\n // test once to make sure it parses correctly\n json::>()\n .process::>(data)\n .unwrap();\n\n // println!(\"data:\\n{:?}\", json(data));\n c.bench_function(\"json\", |b| {\n b.iter(|| {\n json::>()\n .process::>(data)\n .unwrap()\n });\n });\n}\n\nfn json_bench_error_check(c: &mut Criterion) {\n let data = \" { \\\"a\\\"\\t: 42,\n \\\"b\\\": [ \\\"x\\\", \\\"y\\\", 12 ,\\\"\\\\u2014\\\", \\\"\\\\uD83D\\\\uDE10\\\"] ,\n \\\"c\\\": { \\\"hello\\\" : \\\"world\\\"\n }\n } \";\n\n // test once to make sure it parses correctly\n json::>()\n .process::>(data)\n .unwrap();\n\n // println!(\"data:\\n{:?}\", json(data));\n c.bench_function(\"json\", |b| {\n b.iter(|| {\n json::>()\n .process::>(data)\n .unwrap()\n });\n });\n}\n\nstatic CANADA: &str = include_str!(\"../canada.json\");\nfn canada_json(c: &mut Criterion) {\n // test once to make sure it parses correctly\n json::>()\n .process::>(CANADA)\n .unwrap();\n\n // println!(\"data:\\n{:?}\", json(data));\n c.bench_function(\"json canada\", |b| {\n b.iter(|| {\n json::>()\n .process::>(CANADA)\n .unwrap()\n });\n });\n}\n\nfn verbose_json(c: &mut Criterion) {\n let data = \" { \\\"a\\\"\\t: 42,\n \\\"b\\\": [ \\\"x\\\", \\\"y\\\", 12 ,\\\"\\\\u2014\\\", \\\"\\\\uD83D\\\\uDE10\\\"] ,\n \\\"c\\\": { \\\"hello\\\" : \\\"world\\\"\n }\n } \";\n\n // test once to make sure it parses correctly\n json::>()\n .process::>(data)\n .unwrap();\n\n // println!(\"data:\\n{:?}\", json(data));\n c.bench_function(\"json verbose\", |b| {\n b.iter(|| {\n json::>()\n .process::>(data)\n .unwrap()\n });\n });\n}\n\nfn verbose_canada_json(c: &mut Criterion) {\n // test once to make sure it parses correctly\n json::>()\n .process::>(CANADA)\n .unwrap();\n\n // println!(\"data:\\n{:?}\", json(data));\n c.bench_function(\"json canada verbose\", |b| {\n b.iter(|| {\n json::>()\n .process::>(CANADA)\n .unwrap()\n });\n });\n}\n\nfn recognize_float_bytes(c: &mut Criterion) {\n println!(\n \"recognize_float_bytes result: {:?}\",\n recognize_float::<_, (_, ErrorKind)>()\n .process::>(&b\"-1.234E-12\"[..])\n );\n c.bench_function(\"recognize float bytes\", |b| {\n b.iter(|| {\n recognize_float::<_, (_, ErrorKind)>()\n .process::>(&b\"-1.234E-12\"[..])\n });\n });\n}\n\nfn recognize_float_str(c: &mut Criterion) {\n println!(\n \"recognize_float_str result: {:?}\",\n recognize_float::<_, (_, ErrorKind)>().process::>(\"-1.234E-12\")\n );\n c.bench_function(\"recognize float str\", |b| {\n b.iter(|| {\n recognize_float::<_, (_, ErrorKind)>().process::>(\"-1.234E-12\")\n });\n });\n}\n\nfn float_bytes(c: &mut Criterion) {\n println!(\n \"float_bytes result: {:?}\",\n double::<_, (_, ErrorKind)>().process::>(&b\"-1.234E-12\"[..])\n );\n c.bench_function(\"float bytes\", |b| {\n b.iter(|| {\n double::<_, (_, ErrorKind)>().process::>(&b\"-1.234E-12\"[..])\n });\n });\n}\n\nfn float_str(c: &mut Criterion) {\n println!(\n \"float_str result: {:?}\",\n double::<_, (_, ErrorKind)>().process::>(\"-1.234E-12\")\n );\n c.bench_function(\"float str\", |b| {\n b.iter(|| double::<_, (_, ErrorKind)>().process::>(\"-1.234E-12\"));\n });\n}\n\nuse nom::Err;\nuse nom::ParseTo;\nfn std_float(input: &[u8]) -> IResult<&[u8], f64, (&[u8], ErrorKind)> {\n match recognize_float().process::>(input) {\n Err(e) => Err(e),\n Ok((i, s)) => match s.parse_to() {\n Some(n) => Ok((i, n)),\n None => Err(Err::Error((i, ErrorKind::Float))),\n },\n }\n}\n\nfn std_float_bytes(c: &mut Criterion) {\n println!(\n \"std_float_bytes result: {:?}\",\n std_float(&b\"-1.234E-12\"[..])\n );\n c.bench_function(\"std_float bytes\", |b| {\n b.iter(|| std_float(&b\"-1.234E-12\"[..]));\n });\n}\n\ncriterion_group!(\n benches,\n json_bench,\n json_bench_error_check,\n verbose_json,\n canada_json,\n verbose_canada_json,\n recognize_float_bytes,\n recognize_float_str,\n float_bytes,\n std_float_bytes,\n float_str\n);\ncriterion_main!(benches);"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "ini.rs", "content": "#[global_allocator]\nstatic ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;\n\nuse codspeed_criterion_compat::*;\n\nuse nom::{\n bytes::complete::take_while,\n character::complete::{\n alphanumeric1 as alphanumeric, char, multispace1 as multispace, space1 as space,\n },\n combinator::{map_res, opt},\n multi::many,\n sequence::{delimited, pair, separated_pair, terminated, tuple},\n IResult, Parser,\n};\nuse std::collections::HashMap;\nuse std::str;\n\nfn category(i: &[u8]) -> IResult<&[u8], &str> {\n map_res(\n delimited(char('['), take_while(|c| c != b']'), char(']')),\n str::from_utf8,\n )\n .parse_complete(i)\n}\n\nfn key_value(i: &[u8]) -> IResult<&[u8], (&str, &str)> {\n let (i, key) = map_res(alphanumeric, str::from_utf8).parse_complete(i)?;\n let (i, _) = tuple((opt(space), char('='), opt(space))).parse_complete(i)?;\n let (i, val) =\n map_res(take_while(|c| c != b'\\n' && c != b';'), str::from_utf8).parse_complete(i)?;\n let (i, _) = opt(pair(char(';'), take_while(|c| c != b'\\n'))).parse_complete(i)?;\n Ok((i, (key, val)))\n}\n\nfn categories(i: &[u8]) -> IResult<&[u8], HashMap<&str, HashMap<&str, &str>>> {\n many(\n 0..,\n separated_pair(\n category,\n opt(multispace),\n many(0.., terminated(key_value, opt(multispace))),\n ),\n )\n .parse_complete(i)\n}\n\nfn bench_ini(c: &mut Criterion) {\n let str = \"[owner]\nname=John Doe\norganization=Acme Widgets Inc.\n\n[database]\nserver=192.0.2.62\nport=143\nfile=payroll.dat\n\\0\";\n\n let mut group = c.benchmark_group(\"ini\");\n group.throughput(Throughput::Bytes(str.len() as u64));\n group.bench_function(BenchmarkId::new(\"parse\", str.len()), |b| {\n b.iter(|| categories(str.as_bytes()).unwrap())\n });\n}\n\nfn bench_ini_keys_and_values(c: &mut Criterion) {\n let str = \"server=192.0.2.62\nport=143\nfile=payroll.dat\n\\0\";\n\n fn acc(i: &[u8]) -> IResult<&[u8], Vec<(&str, &str)>> {\n many(0.., key_value).parse_complete(i)\n }\n\n let mut group = c.benchmark_group(\"ini keys and values\");\n group.throughput(Throughput::Bytes(str.len() as u64));\n group.bench_function(BenchmarkId::new(\"parse\", str.len()), |b| {\n b.iter(|| acc(str.as_bytes()).unwrap())\n });\n}\n\nfn bench_ini_key_value(c: &mut Criterion) {\n let str = \"server=192.0.2.62\\n\";\n\n let mut group = c.benchmark_group(\"ini key value\");\n group.throughput(Throughput::Bytes(str.len() as u64));\n group.bench_function(BenchmarkId::new(\"parse\", str.len()), |b| {\n b.iter(|| key_value(str.as_bytes()).unwrap())\n });\n}\n\ncriterion_group!(\n benches,\n bench_ini,\n bench_ini_keys_and_values,\n bench_ini_key_value\n);\ncriterion_main!(benches);"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "http.rs", "content": "#![cfg_attr(rustfmt, rustfmt_skip)]\n\n#[global_allocator]\nstatic ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;\n\nuse codspeed_criterion_compat::*;\nuse nom::{IResult, bytes::{tag, take_while1}, character:: char, multi::many, OutputMode, Parser, PResult, error::Error, Mode, sequence::{preceded, delimited, separated_pair, terminated, pair}, OutputM, Emit, Complete};\n\n#[cfg_attr(rustfmt, rustfmt_skip)]\n#[derive(Debug)]\nstruct Request<'a> {\n method: &'a [u8],\n uri: &'a [u8],\n version: &'a [u8],\n}\n\n#[derive(Debug)]\nstruct Header<'a> {\n name: &'a [u8],\n value: Vec<&'a [u8]>,\n}\n\n#[cfg_attr(rustfmt, rustfmt_skip)]\n#[cfg_attr(feature = \"cargo-clippy\", allow(match_same_arms))]\nfn is_token(c: u8) -> bool {\n match c {\n 128..=255 => false,\n 0..=31 => false,\n b'(' => false,\n b')' => false,\n b'<' => false,\n b'>' => false,\n b'@' => false,\n b',' => false,\n b';' => false,\n b':' => false,\n b'\\\\' => false,\n b'\"' => false,\n b'/' => false,\n b'[' => false,\n b']' => false,\n b'?' => false,\n b'=' => false,\n b'{' => false,\n b'}' => false,\n b' ' => false,\n _ => true,\n }\n}\n\nfn not_line_ending(c: u8) -> bool {\n c != b'\\r' && c != b'\\n'\n}\n\nfn is_space(c: u8) -> bool {\n c == b' '\n}\n\nfn is_not_space(c: u8) -> bool {\n c != b' '\n}\nfn is_horizontal_space(c: u8) -> bool {\n c == b' ' || c == b'\\t'\n}\n\nfn is_version(c: u8) -> bool {\n c >= b'0' && c <= b'9' || c == b'.'\n}\n\nfn line_ending<'a>()-> impl Parser<&'a[u8], Output=&'a[u8], Error=Error<&'a[u8]>> {\n tag(\"\\n\").or(tag(\"\\r\\n\"))\n}\n\nfn request_line<'a>()-> impl Parser<&'a[u8], Output=Request<'a>, Error=Error<&'a[u8]>> {\n (take_while1(is_token), preceded(take_while1(is_space), take_while1(is_not_space)), delimited(take_while1(is_space), http_version(), line_ending()))\n .map(|(method, uri, version)| Request {method, uri, version})\n}\n\nfn http_version<'a>() -> impl Parser<&'a[u8], Output=&'a[u8], Error=Error<&'a[u8]>> {\n\n preceded(tag(\"HTTP/\"), take_while1(is_version))\n}\n\nfn message_header_value<'a>() -> impl Parser<&'a[u8], Output=&'a[u8], Error=Error<&'a[u8]>> {\n\n delimited(take_while1(is_horizontal_space), take_while1(not_line_ending), line_ending())\n}\n\nfn message_header<'a>() -> impl Parser<&'a[u8], Output=Header<'a>, Error=Error<&'a[u8]> >{\n separated_pair(take_while1(is_token), char(':'), many(1.., message_header_value()))\n .map(|(name, value)|Header{ name, value })\n}\n\nfn request<'a>() -> impl Parser<&'a[u8], Output=(Request<'a>, Vec>), Error=Error<&'a[u8]> > {\n pair(request_line(), terminated(many(1.., message_header()), line_ending()))\n}\n\n\nfn parse(data: &[u8]) -> Option, Vec>)>> {\n let mut buf = &data[..];\n let mut v = Vec::new();\n loop {\n match request().process::>(buf) {\n Ok((b, r)) => {\n buf = b;\n v.push(r);\n\n if b.is_empty() {\n\n //println!(\"{}\", i);\n break;\n }\n }\n Err(e) => {\n println!(\"error: {:?}\", e);\n return None;\n },\n }\n }\n\n Some(v)\n}\n\n#[bench]\nfn small_test(b: &mut Bencher) {\n let data = include_bytes!(\"../../http-requests.txt\");\n b.iter(||{\n parse(data)\n });\n}\n\n#[bench]\nfn bigger_test(b: &mut Bencher) {\n let data = include_bytes!(\"../../bigger.txt\");\n b.iter(||{\n parse(data)\n });\n}\n\nfn one_test(c: &mut Criterion) {\n let data = &b\"GET / HTTP/1.1\nHost: www.reddit.com\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\nAccept-Language: en-us,en;q=0.5\nAccept-Encoding: gzip, deflate\nConnection: keep-alive\n\n\"[..];\n\n let mut http_group = c.benchmark_group(\"http\");\n http_group.throughput(Throughput::Bytes(data.len() as u64));\n http_group.bench_with_input(\n BenchmarkId::new(\"parse\", data.len()),\n data,\n |b, data| {\n b.iter(|| parse(data).unwrap());\n });\n\n http_group.finish();\n}\n\nfn main() {\n let mut contents: Vec = Vec::new();\n\n {\n use std::io::Read;\n\n let mut file = File::open(env::args().nth(1).expect(\"File to read\")).expect(\"Failed to open file\");\n\n let _ = file.read_to_end(&mut contents).unwrap();\n }\n\n let buf = &contents[..];\n loop {\n parse(buf);\n }\n}\n\ncriterion_group!(http, one_test);\ncriterion_main!(http);"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "fuzz_arithmetic.rs", "content": "#![no_main]\nuse libfuzzer_sys::fuzz_target;\nuse std::str;\n\nextern crate nom;\n\nuse nom::{\n branch::alt,\n bytes::complete::tag,\n character::complete::char,\n character::complete::{digit1 as digit, space0 as space},\n combinator::{map, map_res, verify},\n multi::fold_many0,\n sequence::{delimited, pair, terminated},\n IResult, Parser\n};\n\nuse std::cell::RefCell;\nuse std::str::FromStr;\n\nthread_local! {\n pub static LEVEL: RefCell = RefCell::new(0);\n}\n\nfn reset() {\n LEVEL.with(|l| {\n });\n}\n\nfn incr(i: &str) -> IResult<&str, ()> {\n LEVEL.with(|l| {\n\n // limit the number of recursions, the fuzzer keeps running into them\n if *l.borrow() >= 8192 {\n return Err(nom::Err::Failure(nom::error::Error::new(\n i,\n nom::error::ErrorKind::Count,\n )));\n } else {\n Ok((i, ()))\n }\n })\n}\n\nfn decr() {\n LEVEL.with(|l| {\n });\n}\n\nfn parens(i: &str) -> IResult<&str, i64> {\n delimited(\n space,\n delimited(terminated(tag(\"(\"), incr), expr, map(tag(\")\"), |_| decr())),\n space,\n ).parse(i)\n}\n\nfn factor(i: &str) -> IResult<&str, i64> {\n alt((\n map_res(delimited(space, digit, space), FromStr::from_str),\n parens,\n )).parse(i)\n}\n\nfn term(i: &str) -> IResult<&str, i64> {\n incr(i)?;\n let (i, init) = factor(i).map_err(|e| {\n decr();\n e\n })?;\n\n let res = fold_many0(\n alt((\n pair(char('*'), factor),\n pair(char('/'), verify(factor, |i| *i != 0)),\n )),\n || init,\n |acc, (op, val): (char, i64)| {\n if op == '*' {\n acc.saturating_mul(val)\n } else {\n match acc.checked_div(val) {\n Some(v) => v,\n // we get a division with overflow because we can get acc = i64::MIN and val = -1\n // the division by zero is already checked earlier by verify\n None => i64::MAX,\n }\n }\n },\n ).parse(i);\n\n decr();\n res\n}\n\nfn expr(i: &str) -> IResult<&str, i64> {\n incr(i)?;\n let (i, init) = term(i).map_err(|e| {\n decr();\n e\n })?;\n\n let res = fold_many0(\n pair(alt((char('+'), char('-'))), term),\n || init,\n |acc, (op, val): (char, i64)| {\n if op == '+' {\n acc.saturating_add(val)\n } else {\n acc.saturating_sub(val)\n }\n },\n ).parse(i);\n\n decr();\n res\n}\n\nfuzz_target!(|data: &[u8]| {\n reset();\n // fuzzed code goes here\n let _ = match str::from_utf8(data) {\n Ok(v) => {\n //println!(\"v: {}\", v);\n factor(v)\n }\n Err(_) => factor(\"2\"),\n };\n});"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "error.rs", "content": "use crate::internal::{Err, Mode, OutputMode, PResult, Parser};\nuse crate::lib::std::fmt;\n\n#[cfg(feature = \"alloc\")]\nuse crate::alloc::borrow::ToOwned;\n\n#[cfg(feature = \"std\")]\nuse crate::internal::IResult;\n\n/// This trait must be implemented by the error type of a nom parser.\n///\n/// There are already implementations of it for `(Input, ErrorKind)`\n/// and `Error`.\n///\n/// It provides methods to create an error from some combinators,\n/// and combine existing errors in combinators like `alt`.\npub trait ParseError: Sized {\n /// Creates an error from the input position and an [ErrorKind]\n fn from_error_kind(input: I, kind: ErrorKind) -> Self;\n\n /// Combines an existing error with a new one created from the input\n /// position and an [ErrorKind]. This is useful when backtracking\n /// through a parse tree, accumulating error context on the way\n fn append(input: I, kind: ErrorKind, other: Self) -> Self;\n\n /// Creates an error from an input position and an expected character\n fn from_char(input: I, _: char) -> Self {\n Self::from_error_kind(input, ErrorKind::Char)\n }\n\n /// Combines two existing errors. This function is used to compare errors\n /// generated in various branches of `alt`.\n fn or(self, other: Self) -> Self {\n other\n }\n}\n\n/// This trait is required by the `context` combinator to add a static string\n/// to an existing error\npub trait ContextError: Sized {\n /// Creates a new error from an input position, a static string and an existing error.\n /// This is used mainly in the [context] combinator, to add user friendly information\n /// to errors when backtracking through a parse tree\n fn add_context(_input: I, _ctx: &'static str, other: Self) -> Self {\n other\n }\n}\n\n/// This trait is required by the `map_res` combinator to integrate\n/// error types from external functions, like [std::str::FromStr]\npub trait FromExternalError {\n /// Creates a new error from an input position, an [ErrorKind] indicating the\n /// wrapping parser, and an external error\n fn from_external_error(input: I, kind: ErrorKind, e: E) -> Self;\n}\n\n/// default error type, only contains the error's location and code\n#[derive(Clone, Debug, Eq, PartialEq)]\npub struct Error {\n /// position of the error in the input data\n pub input: I,\n /// nom error code\n pub code: ErrorKind,\n}\n\nimpl Error {\n /// creates a new basic error\n pub fn new(input: I, code: ErrorKind) -> Error {\n Error { input, code }\n }\n}\n\nimpl ParseError for Error {\n fn from_error_kind(input: I, kind: ErrorKind) -> Self {\n Error { input, code: kind }\n }\n\n fn append(_: I, _: ErrorKind, other: Self) -> Self {\n other\n }\n}\n\nimpl ContextError for Error {}\n\nimpl FromExternalError for Error {\n /// Create a new error from an input position and an external error\n fn from_external_error(input: I, kind: ErrorKind, _e: E) -> Self {\n Error { input, code: kind }\n }\n}\n\n/// The Display implementation allows the std::error::Error implementation\nimpl fmt::Display for Error {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"error {:?} at: {}\", self.code, self.input)\n }\n}\n\n#[cfg(feature = \"alloc\")]\nimpl Error<&I> {\n /// Converts `Error<&I>` into `Error` by cloning.\n pub fn cloned(self) -> Error {\n Error {\n input: self.input.to_owned(),\n code: self.code,\n }\n }\n}\n\n#[cfg(feature = \"alloc\")]\nimpl Error<&mut I> {\n /// Converts `Error<&mut I>` into `Error` by cloning.\n pub fn cloned(self) -> Error {\n Error {\n input: self.input.to_owned(),\n code: self.code,\n }\n }\n}\n\nimpl Error<&I> {\n /// Converts `Error<&I>` into `Error` by copying.\n pub fn copied(self) -> Error {\n Error {\n input: *self.input,\n code: self.code,\n }\n }\n}\n\nimpl Error<&mut I> {\n /// Converts `Error<&mut I>` into `Error` by copying.\n pub fn copied(self) -> Error {\n Error {\n input: *self.input,\n code: self.code,\n }\n }\n}\n\n#[cfg(feature = \"std\")]\nimpl std::error::Error for Error {}\n\n#[cfg(feature = \"alloc\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\nimpl From> for Error> {\n fn from(value: Error<&[u8]>) -> Self {\n Error {\n input: value.input.to_owned(),\n code: value.code,\n }\n }\n}\n\n#[cfg(feature = \"alloc\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\nimpl From> for Error {\n fn from(value: Error<&str>) -> Self {\n Error {\n input: value.input.to_owned(),\n code: value.code,\n }\n }\n}\n\n// for backward compatibility, keep those trait implementations\n// for the previously used error type\nimpl ParseError for (I, ErrorKind) {\n fn from_error_kind(input: I, kind: ErrorKind) -> Self {\n (input, kind)\n }\n\n fn append(_: I, _: ErrorKind, other: Self) -> Self {\n other\n }\n}\n\nimpl ContextError for (I, ErrorKind) {}\n\nimpl FromExternalError for (I, ErrorKind) {\n fn from_external_error(input: I, kind: ErrorKind, _e: E) -> Self {\n (input, kind)\n }\n}\n\nimpl ParseError for () {\n fn from_error_kind(_: I, _: ErrorKind) -> Self {}\n\n fn append(_: I, _: ErrorKind, _: Self) -> Self {}\n}\n\nimpl ContextError for () {}\n\nimpl FromExternalError for () {\n fn from_external_error(_input: I, _kind: ErrorKind, _e: E) -> Self {}\n}\n\n/// Creates an error from the input position and an [ErrorKind]\npub fn make_error>(input: I, kind: ErrorKind) -> E {\n E::from_error_kind(input, kind)\n}\n\n/// Combines an existing error with a new one created from the input\n/// position and an [ErrorKind]. This is useful when backtracking\n/// through a parse tree, accumulating error context on the way\npub fn append_error>(input: I, kind: ErrorKind, other: E) -> E {\n E::append(input, kind, other)\n}\n\n/// Create a new error from an input position, a static string and an existing error.\n/// This is used mainly in the [context] combinator, to add user friendly information\n/// to errors when backtracking through a parse tree\npub fn context(context: &'static str, parser: F) -> Context {\n Context { context, parser }\n}\n\n/// Parser implementation for [context]\npub struct Context {\n context: &'static str,\n parser: F,\n}\n\nimpl Parser for Context\nwhere\n I: Clone,\n F: Parser,\n >::Error: ContextError,\n{\n type Output = >::Output;\n type Error = >::Error;\n\n fn process(&mut self, input: I) -> PResult {\n match self.parser.process::(input.clone()) {\n Err(Err::Error(e)) => Err(Err::Error(OM::Error::map(e, |e| {\n >::Error::add_context(input, self.context, e)\n }))),\n Err(Err::Failure(e)) => Err(Err::Failure(>::Error::add_context(\n input,\n self.context,\n e,\n ))),\n x => x,\n }\n }\n}\n\n/// Indicates which parser returned an error\n#[rustfmt::skip]\n#[derive(Debug,PartialEq,Eq,Hash,Clone,Copy)]\n#[allow(deprecated,missing_docs)]\npub enum ErrorKind {\n Tag,\n MapRes,\n MapOpt,\n Alt,\n IsNot,\n IsA,\n SeparatedList,\n SeparatedNonEmptyList,\n Many0,\n Many1,\n ManyTill,\n Count,\n TakeUntil,\n LengthValue,\n TagClosure,\n Alpha,\n Digit,\n HexDigit,\n OctDigit,\n BinDigit,\n AlphaNumeric,\n Space,\n MultiSpace,\n LengthValueFn,\n Eof,\n Switch,\n TagBits,\n OneOf,\n NoneOf,\n Char,\n CrLf,\n RegexpMatch,\n RegexpMatches,\n RegexpFind,\n RegexpCapture,\n RegexpCaptures,\n TakeWhile1,\n Complete,\n Fix,\n Escaped,\n EscapedTransform,\n NonEmpty,\n ManyMN,\n Not,\n Permutation,\n Verify,\n TakeTill1,\n TakeWhileMN,\n TooLarge,\n Many0Count,\n Many1Count,\n Float,\n Satisfy,\n Fail,\n Many,\n Fold,\n Precedence,\n}\n\n#[rustfmt::skip]\n#[allow(deprecated)]\n/// Converts an ErrorKind to a number\npub fn error_to_u32(e: &ErrorKind) -> u32 {\n match *e {\n ErrorKind::Tag => 1,\n ErrorKind::MapRes => 2,\n ErrorKind::MapOpt => 3,\n ErrorKind::Alt => 4,\n ErrorKind::IsNot => 5,\n ErrorKind::IsA => 6,\n ErrorKind::SeparatedList => 7,\n ErrorKind::SeparatedNonEmptyList => 8,\n ErrorKind::Many1 => 9,\n ErrorKind::Count => 10,\n ErrorKind::TakeUntil => 12,\n ErrorKind::LengthValue => 15,\n ErrorKind::TagClosure => 16,\n ErrorKind::Alpha => 17,\n ErrorKind::Digit => 18,\n ErrorKind::AlphaNumeric => 19,\n ErrorKind::Space => 20,\n ErrorKind::MultiSpace => 21,\n ErrorKind::LengthValueFn => 22,\n ErrorKind::Eof => 23,\n ErrorKind::Switch => 27,\n ErrorKind::TagBits => 28,\n ErrorKind::OneOf => 29,\n ErrorKind::NoneOf => 30,\n ErrorKind::Char => 40,\n ErrorKind::CrLf => 41,\n ErrorKind::RegexpMatch => 42,\n ErrorKind::RegexpMatches => 43,\n ErrorKind::RegexpFind => 44,\n ErrorKind::RegexpCapture => 45,\n ErrorKind::RegexpCaptures => 46,\n ErrorKind::TakeWhile1 => 47,\n ErrorKind::Complete => 48,\n ErrorKind::Fix => 49,\n ErrorKind::Escaped => 50,\n ErrorKind::EscapedTransform => 51,\n ErrorKind::NonEmpty => 56,\n ErrorKind::ManyMN => 57,\n ErrorKind::HexDigit => 59,\n ErrorKind::OctDigit => 61,\n ErrorKind::Many0 => 62,\n ErrorKind::Not => 63,\n ErrorKind::Permutation => 64,\n ErrorKind::ManyTill => 65,\n ErrorKind::Verify => 66,\n ErrorKind::TakeTill1 => 67,\n ErrorKind::TakeWhileMN => 69,\n ErrorKind::TooLarge => 70,\n ErrorKind::Many0Count => 71,\n ErrorKind::Many1Count => 72,\n ErrorKind::Float => 73,\n ErrorKind::Satisfy => 74,\n ErrorKind::Fail => 75,\n ErrorKind::Many => 76,\n ErrorKind::Fold => 77,\n ErrorKind::BinDigit => 78,\n ErrorKind::Precedence => 79,\n }\n}\n\nimpl ErrorKind {\n #[rustfmt::skip]\n #[allow(deprecated)]\n /// Converts an ErrorKind to a text description\n pub fn description(&self) -> &str {\n match *self {\n ErrorKind::Tag => \"Tag\",\n ErrorKind::MapRes => \"Map on Result\",\n ErrorKind::MapOpt => \"Map on Option\",\n ErrorKind::Alt => \"Alternative\",\n ErrorKind::IsNot => \"IsNot\",\n ErrorKind::IsA => \"IsA\",\n ErrorKind::SeparatedList => \"Separated list\",\n ErrorKind::SeparatedNonEmptyList => \"Separated non empty list\",\n ErrorKind::Many0 => \"Many0\",\n ErrorKind::Many1 => \"Many1\",\n ErrorKind::Count => \"Count\",\n ErrorKind::TakeUntil => \"Take until\",\n ErrorKind::LengthValue => \"Length followed by value\",\n ErrorKind::TagClosure => \"Tag closure\",\n ErrorKind::Alpha => \"Alphabetic\",\n ErrorKind::Digit => \"Digit\",\n ErrorKind::AlphaNumeric => \"AlphaNumeric\",\n ErrorKind::Space => \"Space\",\n ErrorKind::MultiSpace => \"Multiple spaces\",\n ErrorKind::LengthValueFn => \"LengthValueFn\",\n ErrorKind::Eof => \"End of file\",\n ErrorKind::Switch => \"Switch\",\n ErrorKind::TagBits => \"Tag on bitstream\",\n ErrorKind::OneOf => \"OneOf\",\n ErrorKind::NoneOf => \"NoneOf\",\n ErrorKind::Char => \"Char\",\n ErrorKind::CrLf => \"CrLf\",\n ErrorKind::RegexpMatch => \"RegexpMatch\",\n ErrorKind::RegexpMatches => \"RegexpMatches\",\n ErrorKind::RegexpFind => \"RegexpFind\",\n ErrorKind::RegexpCapture => \"RegexpCapture\",\n ErrorKind::RegexpCaptures => \"RegexpCaptures\",\n ErrorKind::TakeWhile1 => \"TakeWhile1\",\n ErrorKind::Complete => \"Complete\",\n ErrorKind::Fix => \"Fix\",\n ErrorKind::Escaped => \"Escaped\",\n ErrorKind::EscapedTransform => \"EscapedTransform\",\n ErrorKind::NonEmpty => \"NonEmpty\",\n ErrorKind::ManyMN => \"Many(m, n)\",\n ErrorKind::HexDigit => \"Hexadecimal Digit\",\n ErrorKind::OctDigit => \"Octal digit\",\n ErrorKind::BinDigit => \"Binary digit\",\n ErrorKind::Not => \"Negation\",\n ErrorKind::Permutation => \"Permutation\",\n ErrorKind::ManyTill => \"ManyTill\",\n ErrorKind::Verify => \"predicate verification\",\n ErrorKind::TakeTill1 => \"TakeTill1\",\n ErrorKind::TakeWhileMN => \"TakeWhileMN\",\n ErrorKind::TooLarge => \"Needed data size is too large\",\n ErrorKind::Many0Count => \"Count occurrence of >=0 patterns\",\n ErrorKind::Many1Count => \"Count occurrence of >=1 patterns\",\n ErrorKind::Float => \"Float\",\n ErrorKind::Satisfy => \"Satisfy\",\n ErrorKind::Fail => \"Fail\",\n ErrorKind::Many => \"Many\",\n ErrorKind::Fold => \"Fold\",\n ErrorKind::Precedence => \"Precedence\",\n }\n }\n}\n\n/// Creates a parse error from a `nom::ErrorKind`\n/// and the position in the input\n#[allow(unused_variables)]\n#[macro_export(local_inner_macros)]\nmacro_rules! error_position(\n ($input:expr, $code:expr $(,)?) => ({\n $crate::error::make_error($input, $code)\n });\n);\n\n/// Creates a parse error from a `nom::ErrorKind`,\n/// the position in the input and the next error in\n/// the parsing tree\n#[allow(unused_variables)]\n#[macro_export(local_inner_macros)]\nmacro_rules! error_node_position(\n ($input:expr, $code:expr, $next:expr $(,)?) => ({\n $crate::error::append_error($input, $code, $next)\n });\n);\n\n/// Prints a message and the input if the parser fails.\n///\n/// The message prints the `Error` or `Incomplete`\n/// and the parser's calling code.\n///\n/// It also displays the input in hexdump format\n///\n/// ```rust\n/// use nom::{IResult, error::dbg_dmp, bytes::complete::tag};\n///\n/// fn f(i: &[u8]) -> IResult<&[u8], &[u8]> {\n/// dbg_dmp(tag(\"abcd\"), \"tag\")(i)\n/// }\n///\n/// let a = &b\"efghijkl\"[..];\n///\n/// // Will print the following message:\n/// // Error(Position(0, [101, 102, 103, 104, 105, 106, 107, 108])) at l.5 by ' tag ! ( \"abcd\" ) '\n/// // 00000000 65 66 67 68 69 6a 6b 6c efghijkl\n/// f(a);\n/// ```\n#[cfg(feature = \"std\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"std\")))]\npub fn dbg_dmp<'a, F, O, E: std::fmt::Debug>(\n f: F,\n context: &'static str,\n) -> impl Fn(&'a [u8]) -> IResult<&'a [u8], O, E>\nwhere\n F: Fn(&'a [u8]) -> IResult<&'a [u8], O, E>,\n{\n use crate::HexDisplay;\n move |i: &'a [u8]| match f(i) {\n Err(e) => {\n println!(\"{}: Error({:?}) at:\\n{}\", context, e, i.to_hex(8));\n Err(e)\n }\n a => a,\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn context_test() {\n use crate::{character::char, combinator::cut, internal::Needed};\n\n #[derive(Debug, PartialEq)]\n struct Error {\n input: I,\n ctx: Option<&'static str>,\n }\n\n impl ParseError for Error {\n fn from_error_kind(input: I, _kind: ErrorKind) -> Self {\n Self { input, ctx: None }\n }\n\n fn append(input: I, _kind: ErrorKind, other: Self) -> Self {\n Self {\n input,\n ctx: other.ctx,\n }\n }\n }\n\n impl ContextError for Error {\n fn add_context(input: I, ctx: &'static str, _other: Self) -> Self {\n Self {\n input,\n ctx: Some(ctx),\n }\n }\n }\n\n assert_eq!(\n context(\"ctx\", char::<_, Error<_>>('a')).parse(\"abcd\"),\n Ok((\"bcd\", 'a'))\n );\n assert_eq!(\n context(\"ctx\", char::<_, Error<_>>('a')).parse(\"\"),\n Err(Err::Incomplete(Needed::new(1)))\n );\n assert_eq!(\n context(\"ctx\", char::<_, Error<_>>('a')).parse_complete(\"\"),\n Err(Err::Error(Error {\n input: \"\",\n ctx: Some(\"ctx\")\n }))\n );\n assert_eq!(\n context(\"ctx\", cut(char::<_, Error<_>>('a'))).parse(\"bcd\"),\n Err(Err::Failure(Error {\n input: \"bcd\",\n ctx: Some(\"ctx\")\n }))\n );\n }\n\n #[cfg(feature = \"alloc\")]\n #[test]\n fn clone_error() {\n use crate::lib::std::string::String;\n let err = Error {\n code: ErrorKind::Eof,\n input: \"test\",\n };\n\n let _err: Error = err.cloned();\n }\n\n #[test]\n fn copy_error() {\n let err = Error {\n code: ErrorKind::Eof,\n input: &0_u8,\n };\n\n let _err: Error = err.copied();\n }\n}\n\n#[cfg(feature = \"alloc\")]\nuse lib::std::{vec::Vec, collections::HashMap};\n\n#[cfg(feature = \"std\")]\nuse lib::std::hash::Hash;\n\n#[cfg(feature = \"std\")]\npub fn add_error_pattern<'a, I: Clone + Hash + Eq, O, E: Clone + Hash + Eq>(\n h: &mut HashMap, &'a str>,\n e: VerboseError,\n message: &'a str,\n) -> bool {\n h.insert(e, message);\n true\n}\n\npub fn slice_to_offsets(input: &[u8], s: &[u8]) -> (usize, usize) {\n let start = input.as_ptr();\n let off1 = s.as_ptr() as usize - start as usize;\n let off2 = off1 + s.len();\n (off1, off2)\n}\n\n#[cfg(feature = \"std\")]\npub fn prepare_errors(input: &[u8], e: VerboseError<&[u8]>) -> Option> {\n let mut v: Vec<(ErrorKind, usize, usize)> = Vec::new();\n\n for (p, kind) in e.errors.drain(..) {\n let (o1, o2) = slice_to_offsets(input, p);\n v.push((kind, o1, o2));\n }\n\n v.reverse();\n Some(v)\n}\n\n#[cfg(feature = \"std\")]\npub fn print_error(input: &[u8], res: VerboseError<&[u8]>) {\n if let Some(v) = prepare_errors(input, res) {\n let colors = generate_colors(&v);\n println!(\"parser codes: {}\", print_codes(&colors, &HashMap::new()));\n println!(\"{}\", print_offsets(input, 0, &v));\n } else {\n println!(\"not an error\");\n }\n}\n\n#[cfg(feature = \"std\")]\npub fn generate_colors(v: &[(ErrorKind, usize, usize)]) -> HashMap {\n let mut h: HashMap = HashMap::new();\n let mut color = 0;\n\n for &(ref c, _, _) in v.iter() {\n h.insert(error_to_u32(c), color + 31);\n color = color + 1 % 7;\n }\n\n h\n}\n\npub fn code_from_offset(v: &[(ErrorKind, usize, usize)], offset: usize) -> Option {\n let mut acc: Option<(u32, usize, usize)> = None;\n for &(ref ek, s, e) in v.iter() {\n let c = error_to_u32(ek);\n if s <= offset && offset <= e {\n if let Some((_, start, end)) = acc {\n if start <= s && e <= end {\n acc = Some((c, s, e));\n }\n } else {\n acc = Some((c, s, e));\n }\n }\n }\n if let Some((code, _, _)) = acc {\n return Some(code);\n } else {\n return None;\n }\n}\n\n#[cfg(feature = \"alloc\")]\npub fn reset_color(v: &mut Vec) {\n v.push(0x1B);\n v.push(b'[');\n v.push(0);\n v.push(b'm');\n}\n\n#[cfg(feature = \"alloc\")]\npub fn write_color(v: &mut Vec, color: u8) {\n v.push(0x1B);\n v.push(b'[');\n v.push(1);\n v.push(b';');\n let s = color.to_string();\n let bytes = s.as_bytes();\n v.extend(bytes.iter().cloned());\n v.push(b'm');\n}\n\n#[cfg(feature = \"std\")]\n#[cfg_attr(feature = \"cargo-clippy\", allow(implicit_hasher))]\npub fn print_codes(colors: &HashMap, names: &HashMap) -> String {\n let mut v = Vec::new();\n for (code, &color) in colors {\n if let Some(&s) = names.get(code) {\n let bytes = s.as_bytes();\n write_color(&mut v, color);\n v.extend(bytes.iter().cloned());\n } else {\n let s = code.to_string();\n let bytes = s.as_bytes();\n write_color(&mut v, color);\n v.extend(bytes.iter().cloned());\n }\n reset_color(&mut v);\n v.push(b' ');\n }\n reset_color(&mut v);\n\n String::from_utf8_lossy(&v[..]).into_owned()\n}\n\n#[cfg(feature = \"std\")]\npub fn print_offsets(input: &[u8], from: usize, offsets: &[(ErrorKind, usize, usize)]) -> String {\n let mut v = Vec::with_capacity(input.len() * 3);\n let mut i = from;\n let chunk_size = 8;\n let mut current_code: Option = None;\n let mut current_code2: Option = None;\n\n let colors = generate_colors(&offsets);\n\n for chunk in input.chunks(chunk_size) {\n let s = format!(\"{:08x}\", i);\n for &ch in s.as_bytes().iter() {\n v.push(ch);\n }\n v.push(b'\\t');\n\n let mut k = i;\n let mut l = i;\n for &byte in chunk {\n if let Some(code) = code_from_offset(&offsets, k) {\n if let Some(current) = current_code {\n if current != code {\n reset_color(&mut v);\n current_code = Some(code);\n if let Some(&color) = colors.get(&code) {\n write_color(&mut v, color);\n }\n }\n } else {\n current_code = Some(code);\n if let Some(&color) = colors.get(&code) {\n write_color(&mut v, color);\n }\n }\n }\n v.push(CHARS[(byte >> 4) as usize]);\n v.push(CHARS[(byte & 0xf) as usize]);\n v.push(b' ');\n k = k + 1;\n }\n\n reset_color(&mut v);\n\n if chunk_size > chunk.len() {\n for _ in 0..(chunk_size - chunk.len()) {\n v.push(b' ');\n v.push(b' ');\n v.push(b' ');\n }\n }\n v.push(b'\\t');\n\n for &byte in chunk {\n if let Some(code) = code_from_offset(&offsets, l) {\n if let Some(current) = current_code2 {\n if current != code {\n reset_color(&mut v);\n current_code2 = Some(code);\n if let Some(&color) = colors.get(&code) {\n write_color(&mut v, color);\n }\n }\n } else {\n current_code2 = Some(code);\n if let Some(&color) = colors.get(&code) {\n write_color(&mut v, color);\n }\n }\n }\n if (byte >= 32 && byte <= 126) || byte >= 128 {\n v.push(byte);\n } else {\n v.push(b'.');\n }\n l = l + 1;\n }\n reset_color(&mut v);\n\n v.push(b'\\n');\n i = i + chunk_size;\n }\n\n String::from_utf8_lossy(&v[..]).into_owned()\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "lib.rs", "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n#![cfg_attr(feature = \"docsrs\", feature(doc_cfg))]\n#![allow(clippy::doc_markdown)]\n#![deny(missing_docs)]\n#[cfg(feature = \"alloc\")]\n#[macro_use]\nextern crate alloc;\n#[cfg(doctest)]\nextern crate doc_comment;\n\n#[cfg(doctest)]\ndoc_comment::doctest!(\"../README.md\");\n\n/// Lib module to re-export everything needed from `std` or `core`/`alloc`. This is how `serde` does\n/// it, albeit there it is not public.\npub mod lib {\n /// `std` facade allowing `std`/`core` to be interchangeable. Reexports `alloc` crate optionally,\n /// as well as `core` or `std`\n #[cfg(not(feature = \"std\"))]\n /// internal std exports for no_std compatibility\n pub mod std {\n #[doc(hidden)]\n #[cfg(not(feature = \"alloc\"))]\n pub use core::borrow;\n\n #[cfg(feature = \"alloc\")]\n #[doc(hidden)]\n pub use alloc::{borrow, boxed, string, vec};\n\n #[doc(hidden)]\n pub use core::{cmp, convert, fmt, iter, mem, num, ops, option, result, slice, str};\n\n /// internal reproduction of std prelude\n #[doc(hidden)]\n pub mod prelude {\n pub use core::prelude as v1;\n }\n }\n\n #[cfg(feature = \"std\")]\n /// internal std exports for no_std compatibility\n pub mod std {\n #[doc(hidden)]\n pub use std::{\n alloc, borrow, boxed, cmp, collections, convert, fmt, hash, iter, mem, num, ops, option,\n result, slice, str, string, vec,\n };\n\n /// internal reproduction of std prelude\n #[doc(hidden)]\n pub mod prelude {\n pub use std::prelude as v1;\n }\n }\n}\n\npub use self::internal::*;\npub use self::traits::*;\n\n#[macro_use]\nmod macros;\n#[macro_use]\npub mod error;\n\npub mod branch;\npub mod combinator;\nmod internal;\npub mod multi;\npub mod sequence;\nmod traits;\n\npub mod bits;\npub mod bytes;\n\npub mod character;\n\nmod str;\n\npub mod number;\n\n#[cfg(all(feature = \"std\", any(doc, doctest, feature = \"docsrs\")))]\n#[cfg_attr(any(doc, doctest, feature = \"docsrs\"), doc = include_str!(\"../doc/nom_recipes.md\"))]\npub mod recipes {}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "str.rs", "content": "#[cfg(test)]\nmod test {\n #[cfg(feature = \"alloc\")]\n use crate::{branch::alt, bytes::complete::tag_no_case, combinator::recognize, multi::many};\n use crate::{\n bytes::complete::{is_a, is_not, tag, take, take_till, take_until},\n error::{self, ErrorKind},\n Err, IResult,\n };\n\n #[test]\n fn tagtr_succeed() {\n const INPUT: &str = \"Hello World!\";\n const TAG: &str = \"Hello\";\n fn test(input: &str) -> IResult<&str, &str> {\n tag(TAG)(input)\n }\n\n match test(INPUT) {\n Ok((extra, output)) => {\n assert!(extra == \" World!\", \"Parser `tag` consumed leftover input.\");\n assert!(\n output == TAG,\n \"Parser `tag` doesn't return the tag it matched on success. \\\n Expected `{}`, got `{}`.\",\n TAG,\n output\n );\n }\n other => panic!(\n \"Parser `tag` didn't succeed when it should have. \\\n Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n fn tagtr_incomplete() {\n use crate::bytes::streaming::tag;\n\n const INPUT: &str = \"Hello\";\n const TAG: &str = \"Hello World!\";\n\n let res: IResult<_, _, error::Error<_>> = tag(TAG)(INPUT);\n match res {\n Err(Err::Incomplete(_)) => (),\n other => {\n panic!(\n \"Parser `tag` didn't require more input when it should have. \\\n Got `{:?}`.\",\n other\n );\n }\n };\n }\n\n #[test]\n fn tagtr_error() {\n const INPUT: &str = \"Hello World!\";\n const TAG: &str = \"Random\"; // TAG must be closer than INPUT.\n\n let res: IResult<_, _, error::Error<_>> = tag(TAG)(INPUT);\n match res {\n Err(Err::Error(_)) => (),\n other => {\n panic!(\n \"Parser `tag` didn't fail when it should have. Got `{:?}`.`\",\n other\n );\n }\n };\n }\n\n #[test]\n fn take_s_succeed() {\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n const CONSUMED: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\";\n const LEFTOVER: &str = \"\u00e1\u0192\u01ad\u00e8\u0159\";\n\n let res: IResult<_, _, error::Error<_>> = take(9_usize)(INPUT);\n match res {\n Ok((extra, output)) => {\n assert!(\n extra == LEFTOVER,\n \"Parser `take_s` consumed leftover input. Leftover `{}`.\",\n extra\n );\n assert!(\n output == CONSUMED,\n \"Parser `take_s` doesn't return the string it consumed on success. Expected `{}`, got `{}`.\",\n CONSUMED,\n output\n );\n }\n other => panic!(\n \"Parser `take_s` didn't succeed when it should have. \\\n Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n fn take_until_succeed() {\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u2202\u00e1\u0192\u01ad\u00e8\u0159\";\n const FIND: &str = \"\u00c2\u00df\u00c7\u2202\";\n const CONSUMED: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\";\n const LEFTOVER: &str = \"\u00c2\u00df\u00c7\u2202\u00e1\u0192\u01ad\u00e8\u0159\";\n\n let res: IResult<_, _, (_, ErrorKind)> = take_until(FIND)(INPUT);\n match res {\n Ok((extra, output)) => {\n assert!(\n extra == LEFTOVER,\n \"Parser `take_until`\\\n consumed leftover input. Leftover `{}`.\",\n extra\n );\n assert!(\n output == CONSUMED,\n \"Parser `take_until`\\\n doesn't return the string it consumed on success. Expected `{}`, got `{}`.\",\n CONSUMED,\n output\n );\n }\n other => panic!(\n \"Parser `take_until` didn't succeed when it should have. \\\n Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n fn take_s_incomplete() {\n use crate::bytes::streaming::take;\n\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u00e1\";\n\n let res: IResult<_, _, (_, ErrorKind)> = take(13_usize)(INPUT);\n match res {\n Err(Err::Incomplete(_)) => (),\n other => panic!(\n \"Parser `take` didn't require more input when it should have. \\\n Got `{:?}`.\",\n other\n ),\n }\n }\n\n use crate::internal::Needed;\n\n fn is_alphabetic(c: char) -> bool {\n (c as u8 >= 0x41 && c as u8 <= 0x5A) || (c as u8 >= 0x61 && c as u8 <= 0x7A)\n }\n\n #[test]\n fn take_while() {\n use crate::bytes::streaming::take_while;\n\n fn f(i: &str) -> IResult<&str, &str> {\n take_while(is_alphabetic)(i)\n }\n let a = \"\";\n let b = \"abcd\";\n let c = \"abcd123\";\n let d = \"123\";\n\n assert_eq!(f(a), Err(Err::Incomplete(Needed::new(1))));\n assert_eq!(f(b), Err(Err::Incomplete(Needed::new(1))));\n assert_eq!(f(c), Ok((d, b)));\n assert_eq!(f(d), Ok((d, a)));\n }\n\n #[test]\n fn take_while1() {\n use crate::bytes::streaming::take_while1;\n\n fn f(i: &str) -> IResult<&str, &str> {\n take_while1(is_alphabetic)(i)\n }\n let a = \"\";\n let b = \"abcd\";\n let c = \"abcd123\";\n let d = \"123\";\n\n assert_eq!(f(a), Err(Err::Incomplete(Needed::new(1))));\n assert_eq!(f(b), Err(Err::Incomplete(Needed::new(1))));\n assert_eq!(f(c), Ok((\"123\", b)));\n assert_eq!(\n f(d),\n Err(Err::Error(error_position!(d, ErrorKind::TakeWhile1)))\n );\n }\n\n #[test]\n fn take_till_s_succeed() {\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n const CONSUMED: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\";\n const LEFTOVER: &str = \"\u00e1\u0192\u01ad\u00e8\u0159\";\n fn till_s(c: char) -> bool {\n c == '\u00e1'\n }\n fn test(input: &str) -> IResult<&str, &str> {\n take_till(till_s)(input)\n }\n match test(INPUT) {\n Ok((extra, output)) => {\n assert!(\n extra == LEFTOVER,\n \"Parser `take_till` consumed leftover input.\"\n );\n assert!(\n output == CONSUMED,\n \"Parser `take_till` doesn't return the string it consumed on success. \\\n Expected `{}`, got `{}`.\",\n CONSUMED,\n output\n );\n }\n other => panic!(\n \"Parser `take_till` didn't succeed when it should have. \\\n Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n fn take_while_succeed_none() {\n use crate::bytes::complete::take_while;\n\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n const CONSUMED: &str = \"\";\n const LEFTOVER: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n fn while_s(c: char) -> bool {\n c == '9'\n }\n fn test(input: &str) -> IResult<&str, &str> {\n take_while(while_s)(input)\n }\n match test(INPUT) {\n Ok((extra, output)) => {\n assert!(\n extra == LEFTOVER,\n \"Parser `take_while` consumed leftover input.\"\n );\n assert!(\n output == CONSUMED,\n \"Parser `take_while` doesn't return the string it consumed on success. \\\n Expected `{}`, got `{}`.\",\n CONSUMED,\n output\n );\n }\n other => panic!(\n \"Parser `take_while` didn't succeed when it should have. \\\n Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n fn is_not_succeed() {\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n const AVOID: &str = \"\u00a3\u00fa\u00e7\u0199\u00a5\u00e1\";\n const CONSUMED: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\";\n const LEFTOVER: &str = \"\u00e1\u0192\u01ad\u00e8\u0159\";\n fn test(input: &str) -> IResult<&str, &str> {\n is_not(AVOID)(input)\n }\n match test(INPUT) {\n Ok((extra, output)) => {\n assert!(\n extra == LEFTOVER,\n \"Parser `is_not` consumed leftover input. Leftover `{}`.\",\n extra\n );\n assert!(\n output == CONSUMED,\n \"Parser `is_not` doesn't return the string it consumed on success. Expected `{}`, got `{}`.\",\n CONSUMED,\n output\n );\n }\n other => panic!(\n \"Parser `is_not` didn't succeed when it should have. \\\n Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n fn take_while_succeed_some() {\n use crate::bytes::complete::take_while;\n\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n const CONSUMED: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\";\n const LEFTOVER: &str = \"\u00e1\u0192\u01ad\u00e8\u0159\";\n fn while_s(c: char) -> bool {\n matches!(c, '\u03b2' | '\u00e8' | '\u0192' | '\u00f4' | '\u0159' | '\u00c2' | '\u00df' | '\u00c7')\n }\n fn test(input: &str) -> IResult<&str, &str> {\n take_while(while_s)(input)\n }\n match test(INPUT) {\n Ok((extra, output)) => {\n assert!(\n extra == LEFTOVER,\n \"Parser `take_while` consumed leftover input.\"\n );\n assert!(\n output == CONSUMED,\n \"Parser `take_while` doesn't return the string it consumed on success. \\\n Expected `{}`, got `{}`.\",\n CONSUMED,\n output\n );\n }\n other => panic!(\n \"Parser `take_while` didn't succeed when it should have. \\\n Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n fn is_not_fail() {\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n const AVOID: &str = \"\u03b2\u00fa\u00e7\u0199\u00a5\";\n fn test(input: &str) -> IResult<&str, &str> {\n is_not(AVOID)(input)\n }\n match test(INPUT) {\n Err(Err::Error(_)) => (),\n other => panic!(\n \"Parser `is_not` didn't fail when it should have. Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n fn take_while1_succeed() {\n use crate::bytes::complete::take_while1;\n\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n const CONSUMED: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\";\n const LEFTOVER: &str = \"\u00e1\u0192\u01ad\u00e8\u0159\";\n fn while1_s(c: char) -> bool {\n matches!(c, '\u03b2' | '\u00e8' | '\u0192' | '\u00f4' | '\u0159' | '\u00c2' | '\u00df' | '\u00c7')\n }\n fn test(input: &str) -> IResult<&str, &str> {\n take_while1(while1_s)(input)\n }\n match test(INPUT) {\n Ok((extra, output)) => {\n assert!(\n extra == LEFTOVER,\n \"Parser `take_while1` consumed leftover input.\"\n );\n assert!(\n output == CONSUMED,\n \"Parser `take_while1` doesn't return the string it consumed on success. \\\n Expected `{}`, got `{}`.\",\n CONSUMED,\n output\n );\n }\n other => panic!(\n \"Parser `take_while1` didn't succeed when it should have. \\\n Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n fn take_until_incomplete() {\n use crate::bytes::streaming::take_until;\n\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\";\n const FIND: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\";\n\n let res: IResult<_, _, (_, ErrorKind)> = take_until(FIND)(INPUT);\n match res {\n Err(Err::Incomplete(_)) => (),\n other => panic!(\n \"Parser `take_until` didn't require more input when it should have. \\\n Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n fn is_a_succeed() {\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n const MATCH: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\";\n const CONSUMED: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\";\n const LEFTOVER: &str = \"\u00e1\u0192\u01ad\u00e8\u0159\";\n fn test(input: &str) -> IResult<&str, &str> {\n is_a(MATCH)(input)\n }\n match test(INPUT) {\n Ok((extra, output)) => {\n assert!(\n extra == LEFTOVER,\n \"Parser `is_a` consumed leftover input. Leftover `{}`.\",\n extra\n );\n assert!(\n output == CONSUMED,\n \"Parser `is_a` doesn't return the string it consumed on success. Expected `{}`, got `{}`.\",\n CONSUMED,\n output\n );\n }\n other => panic!(\n \"Parser `is_a` didn't succeed when it should have. \\\n Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n fn take_while1_fail() {\n use crate::bytes::complete::take_while1;\n\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n fn while1_s(c: char) -> bool {\n c == '9'\n }\n fn test(input: &str) -> IResult<&str, &str> {\n take_while1(while1_s)(input)\n }\n match test(INPUT) {\n Err(Err::Error(_)) => (),\n other => panic!(\n \"Parser `take_while1` didn't fail when it should have. \\\n Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n fn is_a_fail() {\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n const MATCH: &str = \"\u00db\u00f1\u2113\u00fa\u00e7\u0199\u00a5\";\n fn test(input: &str) -> IResult<&str, &str> {\n is_a(MATCH)(input)\n }\n match test(INPUT) {\n Err(Err::Error(_)) => (),\n other => panic!(\n \"Parser `is_a` didn't fail when it should have. Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n fn take_until_error() {\n use crate::bytes::streaming::take_until;\n\n const INPUT: &str = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n const FIND: &str = \"R\u00e1\u00f1\u03b4\u00f4\u20a5\";\n\n let res: IResult<_, _, (_, ErrorKind)> = take_until(FIND)(INPUT);\n match res {\n Err(Err::Incomplete(_)) => (),\n other => panic!(\n \"Parser `take_until` didn't fail when it should have. \\\n Got `{:?}`.\",\n other\n ),\n };\n }\n\n #[test]\n #[cfg(feature = \"alloc\")]\n fn recognize_is_a() {\n use crate::{lib::std::vec::Vec, Parser};\n\n let a = \"aabbab\";\n let b = \"ababcd\";\n\n fn f(i: &str) -> IResult<&str, &str> {\n recognize(many::<_, _, Vec<&str>, _, _>(\n 1..,\n alt((tag(\"a\"), tag(\"b\"))),\n ))\n .parse(i)\n }\n\n assert_eq!(f(a), Ok((&a[6..], a)));\n assert_eq!(f(b), Ok((&b[4..], &b[..4])));\n }\n\n #[test]\n fn utf8_indexing() {\n fn dot(i: &str) -> IResult<&str, &str> {\n tag(\".\")(i)\n }\n\n let _ = dot(\"\u9ede\");\n }\n\n #[cfg(feature = \"alloc\")]\n #[test]\n fn case_insensitive() {\n fn test(i: &str) -> IResult<&str, &str> {\n tag_no_case(\"ABcd\")(i)\n }\n assert_eq!(test(\"aBCdefgh\"), Ok((\"efgh\", \"aBCd\")));\n assert_eq!(test(\"abcdefgh\"), Ok((\"efgh\", \"abcd\")));\n assert_eq!(test(\"ABCDefgh\"), Ok((\"efgh\", \"ABCD\")));\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "internal.rs", "content": "use self::Needed::*;\nuse crate::error::{self, ErrorKind, FromExternalError, ParseError};\nuse crate::lib::std::fmt;\nuse core::marker::PhantomData;\nuse core::num::NonZeroUsize;\n\n/// Holds the result of parsing functions\n///\n/// It depends on the input type `I`, the output type `O`, and the error type `E`\n/// (by default `(I, nom::ErrorKind)`)\n///\n/// The `Ok` side is a pair containing the remainder of the input (the part of the data that\n/// was not parsed) and the produced value. The `Err` side contains an instance of `nom::Err`.\n///\n/// Outside of the parsing code, you can use the [Finish::finish] method to convert\n/// it to a more common result type\npub type IResult> = Result<(I, O), Err>;\n\n/// Helper trait to convert a parser's result to a more manageable type\npub trait Finish {\n /// converts the parser's result to a type that is more consumable by error\n /// management libraries. It keeps the same `Ok` branch, and merges `Err::Error`\n /// and `Err::Failure` into the `Err` side.\n ///\n /// *warning*: if the result is `Err(Err::Incomplete(_))`, this method will panic.\n /// - \"complete\" parsers: It will not be an issue, `Incomplete` is never used\n /// - \"streaming\" parsers: `Incomplete` will be returned if there's not enough data\n /// for the parser to decide, and you should gather more data before parsing again.\n /// Once the parser returns either `Ok(_)`, `Err(Err::Error(_))` or `Err(Err::Failure(_))`,\n /// you can get out of the parsing loop and call `finish()` on the parser's result\n fn finish(self) -> Result<(I, O), E>;\n}\n\nimpl Finish for IResult {\n fn finish(self) -> Result<(I, O), E> {\n match self {\n Ok(res) => Ok(res),\n Err(Err::Error(e)) | Err(Err::Failure(e)) => Err(e),\n Err(Err::Incomplete(_)) => {\n panic!(\"Cannot call `finish()` on `Err(Err::Incomplete(_))`: this result means that the parser does not have enough data to decide, you should gather more data and try to reapply the parser instead\")\n }\n }\n }\n}\n\n/// Contains information on needed data if a parser returned `Incomplete`\n#[derive(Debug, PartialEq, Eq, Clone, Copy)]\npub enum Needed {\n /// Needs more data, but we do not know how much\n Unknown,\n /// Contains the required data size in bytes\n Size(NonZeroUsize),\n}\n\nimpl Needed {\n /// Creates `Needed` instance, returns `Needed::Unknown` if the argument is zero\n pub fn new(s: usize) -> Self {\n match NonZeroUsize::new(s) {\n Some(sz) => Needed::Size(sz),\n None => Needed::Unknown,\n }\n }\n\n /// Indicates if we know how many bytes we need\n pub fn is_known(&self) -> bool {\n }\n\n /// Maps a `Needed` to `Needed` by applying a function to a contained `Size` value.\n #[inline]\n pub fn map usize>(self, f: F) -> Needed {\n match self {\n Unknown => Unknown,\n Size(n) => Needed::new(f(n)),\n }\n }\n}\n\n/// The `Err` enum indicates the parser was not successful\n///\n/// It has three cases:\n///\n/// * `Incomplete` indicates that more data is needed to decide. The `Needed` enum\n/// can contain how many additional bytes are necessary. If you are sure your parser\n/// is working on full data, you can wrap your parser with the `complete` combinator\n/// to transform that case in `Error`\n/// * `Error` means some parser did not succeed, but another one might (as an example,\n/// when testing different branches of an `alt` combinator)\n/// * `Failure` indicates an unrecoverable error. For example, when a prefix has been\n/// recognised and the next parser has been confirmed, if that parser fails, then the\n/// entire process fails; there are no more parsers to try.\n///\n/// Distinguishing `Failure` this from `Error` is only relevant inside the parser's code. For\n/// external consumers, both mean that parsing failed.\n///\n/// See also: [`Finish`].\n///\n#[derive(Debug, Clone, PartialEq)]\npub enum Err {\n /// There was not enough data\n Incomplete(Needed),\n /// The parser had an error (recoverable)\n Error(Error),\n /// The parser had an unrecoverable error: we got to the right\n /// branch and we know other branches won't work, so backtrack\n /// as fast as possible\n Failure(Failure),\n}\n\nimpl Err {\n /// Tests if the result is Incomplete\n pub fn is_incomplete(&self) -> bool {\n matches!(self, Err::Incomplete(..))\n }\n\n /// Applies the given function to the inner error\n pub fn map(self, f: F) -> Err\n where\n F: FnOnce(E) -> E2,\n {\n match self {\n Err::Incomplete(n) => Err::Incomplete(n),\n Err::Failure(t) => Err::Failure(f(t)),\n Err::Error(t) => Err::Error(f(t)),\n }\n }\n\n /// Automatically converts between errors if the underlying type supports it\n pub fn convert(e: Err) -> Self\n where\n E: From,\n {\n e.map(crate::lib::std::convert::Into::into)\n }\n}\n\nimpl Err<(T, ErrorKind)> {\n /// Maps `Err<(T, ErrorKind)>` to `Err<(U, ErrorKind)>` with the given `F: T -> U`\n pub fn map_input(self, f: F) -> Err<(U, ErrorKind)>\n where\n F: FnOnce(T) -> U,\n {\n match self {\n Err::Incomplete(n) => Err::Incomplete(n),\n Err::Failure((input, k)) => Err::Failure((f(input), k)),\n Err::Error((input, k)) => Err::Error((f(input), k)),\n }\n }\n}\n\nimpl Err> {\n /// Maps `Err>` to `Err>` with the given `F: T -> U`\n pub fn map_input(self, f: F) -> Err>\n where\n F: FnOnce(T) -> U,\n {\n match self {\n Err::Incomplete(n) => Err::Incomplete(n),\n Err::Failure(error::Error { input, code }) => Err::Failure(error::Error {\n input: f(input),\n code,\n }),\n Err::Error(error::Error { input, code }) => Err::Error(error::Error {\n input: f(input),\n code,\n }),\n }\n }\n}\n\n#[cfg(feature = \"alloc\")]\nuse crate::lib::std::{borrow::ToOwned, string::String, vec::Vec};\n#[cfg(feature = \"alloc\")]\nimpl Err<(&[u8], ErrorKind)> {\n /// Obtaining ownership\n #[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\n pub fn to_owned(self) -> Err<(Vec, ErrorKind)> {\n self.map_input(ToOwned::to_owned)\n }\n}\n\n#[cfg(feature = \"alloc\")]\nimpl Err<(&str, ErrorKind)> {\n /// Obtaining ownership\n #[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\n pub fn to_owned(self) -> Err<(String, ErrorKind)> {\n self.map_input(ToOwned::to_owned)\n }\n}\n\n#[cfg(feature = \"alloc\")]\nimpl Err> {\n /// Obtaining ownership\n #[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\n pub fn to_owned(self) -> Err>> {\n self.map_input(ToOwned::to_owned)\n }\n}\n\n#[cfg(feature = \"alloc\")]\nimpl Err> {\n /// Obtaining ownership\n #[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\n pub fn to_owned(self) -> Err> {\n self.map_input(ToOwned::to_owned)\n }\n}\n\nimpl Eq for Err {}\n\nimpl fmt::Display for Err\nwhere\n E: fmt::Debug,\n{\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Err::Incomplete(Needed::Size(u)) => write!(f, \"Parsing requires {} bytes/chars\", u),\n Err::Incomplete(Needed::Unknown) => write!(f, \"Parsing requires more data\"),\n Err::Failure(c) => write!(f, \"Parsing Failure: {:?}\", c),\n Err::Error(c) => write!(f, \"Parsing Error: {:?}\", c),\n }\n }\n}\n\n#[cfg(feature = \"std\")]\nuse std::error::Error;\n\n#[cfg(feature = \"std\")]\nimpl Error for Err\nwhere\n E: fmt::Debug,\n{\n fn source(&self) -> Option<&(dyn Error + 'static)> {\n None // no underlying error\n }\n}\n\n/// Parser mode: influences how combinators build values\n///\n/// the [Parser] trait is generic over types implementing [Mode]. Its method are\n/// called to produce and manipulate output values or errors.\n///\n/// The main implementations of this trait are:\n/// * [Emit]: produce a value\n/// * [Check]: apply the parser but do not generate a value\npub trait Mode {\n /// The output type that may be generated\n type Output;\n\n /// Produces a value\n fn bind T>(f: F) -> Self::Output;\n\n /// Applies a function over the produced value\n fn map U>(x: Self::Output, f: F) -> Self::Output;\n\n /// Combines two values generated by previous parsers\n fn combine V>(\n x: Self::Output,\n y: Self::Output,\n f: F,\n ) -> Self::Output;\n}\n\n/// Produces a value. This is the default behaviour for parsers\npub struct Emit;\nimpl Mode for Emit {\n type Output = T;\n\n #[inline(always)]\n fn bind T>(f: F) -> Self::Output {\n f()\n }\n\n #[inline(always)]\n fn map U>(x: Self::Output, f: F) -> Self::Output {\n f(x)\n }\n\n #[inline(always)]\n fn combine V>(\n x: Self::Output,\n y: Self::Output,\n f: F,\n ) -> Self::Output {\n f(x, y)\n }\n}\n\n/// Applies the parser, but do not a produce a value\n///\n/// This has the effect of greatly reducing the amount of code generated and the\n/// parser memory usage. Some combinators check for an error in a child parser but\n/// discard the error, and for those, using [Check] makes sure the error is not\n/// even generated, only the fact that an error happened remains\npub struct Check;\nimpl Mode for Check {\n type Output = ();\n\n #[inline(always)]\n fn bind T>(_: F) -> Self::Output {}\n\n #[inline(always)]\n fn map U>(_: Self::Output, _: F) -> Self::Output {}\n\n #[inline(always)]\n fn combine V>(\n _: Self::Output,\n _: Self::Output,\n _: F,\n ) -> Self::Output {\n }\n}\n\n/// Parser result type\n///\n/// * `Ok` branch: a tuple of the remaining input data, and the output value.\n/// The output value is of the `O` type if the output mode was [Emit], and `()`\n/// if the mode was [Check]\n/// * `Err` branch: an error of the `E` type if the erroor mode was [Emit], and `()`\n/// if the mode was [Check]\npub type PResult = Result<\n (I, <::Output as Mode>::Output),\n Err::Error as Mode>::Output>,\n>;\n\n/// Trait Defining the parser's execution\n///\n/// The same parser implementation can vary in behaviour according to the chosen\n/// output mode\npub trait OutputMode {\n /// Defines the [Mode] for the output type. [Emit] will generate the value, [Check] will\n /// apply the parser but will only generate `()` if successful. This can be used when\n /// verifying that the input data conforms to the format without having to generate any\n /// output data\n type Output: Mode;\n /// Defines the [Mode] for the output type. [Emit] will generate the value, [Check] will\n /// apply the parser but will only generate `()` if an error happened. [Emit] should be\n /// used when we want to handle the error and extract useful information from it. [Check]\n /// is used when we just want to know if parsing failed and reject the data quickly.\n type Error: Mode;\n /// Indicates whether the input data is \"complete\", ie we already have the entire data in the\n /// buffer, or if it is \"streaming\", where more data can be added later in the buffer. In\n /// streaming mode, the parser will understand that a failure may mean that we are missing\n /// data, and will return a specific error branch, [Err::Incomplete] to signal it. In complete\n /// mode, the parser will generate a normal error\n type Incomplete: IsStreaming;\n}\n\n/// Specifies the behaviour when a parser encounters an error that could be due to partial ata\npub trait IsStreaming {\n /// called by parsers on partial data errors\n /// * `needed` can hold the amount of additional data the parser would need to decide\n /// * `err_f`: produces the error when in \"complete\" mode\n fn incomplete E>(needed: Needed, err_f: F) -> Err;\n /// Indicates whether the data is in streaming mode or not\n fn is_streaming() -> bool;\n}\n\n/// Indicates that the input data is streaming: more data may be available later\npub struct Streaming;\n\nimpl IsStreaming for Streaming {\n fn incomplete E>(needed: Needed, _err_f: F) -> Err {\n Err::Incomplete(needed)\n }\n\n #[inline]\n fn is_streaming() -> bool {\n true\n }\n}\n\n/// Indicates that the input data is complete: no more data may be added later\npub struct Complete;\n\nimpl IsStreaming for Complete {\n fn incomplete E>(_needed: Needed, err_f: F) -> Err {\n Err::Error(err_f())\n }\n\n #[inline]\n fn is_streaming() -> bool {\n false\n }\n}\n\n/// Holds the parser execution modifiers: output [Mode], error [Mode] and\n/// streaming behaviour for input data\npub struct OutputM {\n m: PhantomData,\n em: PhantomData,\n s: PhantomData,\n}\n\nimpl OutputMode for OutputM {\n type Output = M;\n type Error = EM;\n type Incomplete = S;\n}\n/// All nom parsers implement this trait\npub trait Parser {\n /// Type of the produced value\n type Output;\n /// Error type of this parser\n type Error: ParseError;\n\n /// A parser takes in input type, and returns a `Result` containing\n /// either the remaining input and the output value, or an error\n #[inline]\n fn parse(&mut self, input: Input) -> IResult {\n self.process::>(input)\n }\n\n /// A parser takes in input type, and returns a `Result` containing\n /// either the remaining input and the output value, or an error\n #[inline]\n fn parse_complete(&mut self, input: Input) -> IResult {\n self.process::>(input)\n }\n\n /// A parser takes in input type, and returns a `Result` containing\n /// either the remaining input and the output value, or an error\n fn process(\n &mut self,\n input: Input,\n ) -> PResult;\n\n /// Maps a function over the result of a parser\n fn map(self, g: G) -> Map\n where\n G: FnMut(Self::Output) -> O2,\n Self: core::marker::Sized,\n {\n Map { f: self, g }\n }\n\n /// Applies a function returning a `Result` over the result of a parser.\n fn map_res(self, g: G) -> MapRes\n where\n G: FnMut(Self::Output) -> Result,\n Self::Error: FromExternalError,\n Self: core::marker::Sized,\n {\n MapRes { f: self, g }\n }\n\n /// Applies a function returning an `Option` over the result of a parser.\n fn map_opt(self, g: G) -> MapOpt\n where\n G: FnMut(Self::Output) -> Option,\n Self: core::marker::Sized,\n {\n MapOpt { f: self, g }\n }\n\n /// Creates a second parser from the output of the first one, then apply over the rest of the input\n fn flat_map(self, g: G) -> FlatMap\n where\n G: FnMut(Self::Output) -> H,\n H: Parser,\n Self: core::marker::Sized,\n {\n FlatMap { f: self, g }\n }\n\n /// Applies a second parser over the output of the first one\n fn and_then(self, g: G) -> AndThen\n where\n G: Parser,\n Self: core::marker::Sized,\n {\n AndThen { f: self, g }\n }\n\n /// Applies a second parser after the first one, return their results as a tuple\n fn and(self, g: G) -> And\n where\n G: Parser,\n Self: core::marker::Sized,\n {\n And { f: self, g }\n }\n\n /// Applies a second parser over the input if the first one failed\n fn or(self, g: G) -> Or\n where\n G: Parser,\n Self: core::marker::Sized,\n {\n Or { f: self, g }\n }\n\n /// automatically converts the parser's output and error values to another type, as long as they\n /// implement the `From` trait\n fn into, E2: From>(self) -> Into\n where\n Self: core::marker::Sized,\n {\n Into {\n f: self,\n phantom_out2: core::marker::PhantomData,\n phantom_err2: core::marker::PhantomData,\n }\n }\n}\n\nimpl, F> Parser for F\nwhere\n F: FnMut(I) -> IResult,\n{\n type Output = O;\n type Error = E;\n\n fn process(&mut self, i: I) -> PResult {\n let (i, o) = self(i).map_err(|e| match e {\n Err::Incomplete(i) => Err::Incomplete(i),\n Err::Error(e) => Err::Error(OM::Error::bind(|| e)),\n Err::Failure(e) => Err::Failure(e),\n })?;\n Ok((i, OM::Output::bind(|| o)))\n }\n}\n\nmacro_rules! impl_parser_for_tuple {\n ($($parser:ident $output:ident),+) => (\n #[allow(non_snake_case)]\n impl, $($parser),+> Parser for ($($parser),+,)\n where\n $($parser: Parser),+\n {\n type Output = ($($output),+,);\n type Error = E;\n\n #[inline(always)]\n fn process(&mut self, i: I) -> PResult {\n let ($(ref mut $parser),+,) = *self;\n\n // FIXME: is there a way to avoid producing the output values?\n $(let(i, $output) = $parser.process::>(i)?;)+\n\n // ???\n Ok((i, OM::Output::bind(|| ($($output),+,))))\n }\n }\n )\n}\n\nmacro_rules! impl_parser_for_tuples {\n ($parser1:ident $output1:ident, $($parser:ident $output:ident),+) => {\n impl_parser_for_tuples!(__impl $parser1 $output1; $($parser $output),+);\n };\n (__impl $($parser:ident $output:ident),+; $parser1:ident $output1:ident $(,$parser2:ident $output2:ident)*) => {\n impl_parser_for_tuple!($($parser $output),+);\n impl_parser_for_tuples!(__impl $($parser $output),+, $parser1 $output1; $($parser2 $output2),*);\n };\n (__impl $($parser:ident $output:ident),+;) => {\n impl_parser_for_tuple!($($parser $output),+);\n }\n}\n\nimpl_parser_for_tuples!(P1 O1, P2 O2, P3 O3, P4 O4, P5 O5, P6 O6, P7 O7, P8 O8, P9 O9, P10 O10, P11 O11, P12 O12, P13 O13, P14 O14, P15 O15, P16 O16, P17 O17, P18 O18, P19 O19, P20 O20, P21 O21);\n\n#[cfg(feature = \"alloc\")]\nuse alloc::boxed::Box;\n\n#[cfg(feature = \"alloc\")]\nimpl> Parser for Box> {\n type Output = O;\n type Error = E;\n\n fn process(&mut self, input: I) -> PResult {\n (**self).process(input)\n }\n}\n/// Implementation of `Parser::map`\npub struct Map {\n f: F,\n g: G,\n}\n\nimpl, F: Parser, G: FnMut(>::Output) -> O2>\n Parser for Map\n{\n type Output = O2;\n type Error = E;\n\n #[inline(always)]\n fn process(&mut self, i: I) -> PResult {\n match self.f.process::(i) {\n Err(e) => Err(e),\n Ok((i, o)) => Ok((i, OM::Output::map(o, |o| (self.g)(o)))),\n }\n }\n}\n\n/// Implementation of `Parser::map_res`\npub struct MapRes {\n f: F,\n g: G,\n}\n\nimpl Parser for MapRes\nwhere\n I: Clone,\n >::Error: FromExternalError,\n F: Parser,\n G: FnMut(>::Output) -> Result,\n{\n type Output = O2;\n type Error = >::Error;\n\n fn process(&mut self, i: I) -> PResult {\n let (input, o1) = self\n .f\n .process::>(i.clone())?;\n\n match (self.g)(o1) {\n Ok(o2) => Ok((input, OM::Output::bind(|| o2))),\n Err(e) => Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_external_error(i, ErrorKind::MapRes, e)\n }))),\n }\n }\n}\n\n/// Implementation of `Parser::map_opt`\npub struct MapOpt {\n f: F,\n g: G,\n}\n\nimpl Parser for MapOpt\nwhere\n I: Clone,\n F: Parser,\n G: FnMut(>::Output) -> Option,\n{\n type Output = O2;\n type Error = >::Error;\n\n fn process(&mut self, i: I) -> PResult {\n let (input, o1) = self\n .f\n .process::>(i.clone())?;\n\n match (self.g)(o1) {\n Some(o2) => Ok((input, OM::Output::bind(|| o2))),\n None => Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(i, ErrorKind::MapOpt)\n }))),\n }\n }\n}\n\n/// Implementation of `Parser::flat_map`\npub struct FlatMap {\n f: F,\n g: G,\n}\n\nimpl<\n I,\n E: ParseError,\n F: Parser,\n G: FnMut(>::Output) -> H,\n H: Parser,\n > Parser for FlatMap\n{\n type Output = >::Output;\n type Error = E;\n\n fn process(&mut self, i: I) -> PResult {\n let (input, o1) = self\n .f\n .process::>(i)?;\n\n (self.g)(o1).process::(input)\n }\n}\n\n/// Implementation of `Parser::and_then`\npub struct AndThen {\n f: F,\n g: G,\n}\n\nimpl, G: Parser<>::Output, Error = >::Error>>\n Parser for AndThen\n{\n type Output = >::Output>>::Output;\n type Error = >::Error;\n\n fn process(&mut self, i: I) -> PResult {\n let (input, o1) = self\n .f\n .process::>(i)?;\n\n let (_, o2) = self.g.process::(o1)?;\n Ok((input, o2))\n }\n}\n\n/// Implementation of `Parser::and`\npub struct And {\n f: F,\n g: G,\n}\n\nimpl, F: Parser, G: Parser> Parser\n for And\n{\n type Output = (>::Output, >::Output);\n type Error = E;\n\n #[inline(always)]\n fn process(&mut self, i: I) -> PResult {\n let (i, o1) = self.f.process::(i)?;\n let (i, o2) = self.g.process::(i)?;\n\n Ok((i, OM::Output::combine(o1, o2, |o1, o2| (o1, o2))))\n }\n}\n\n/// Implementation of `Parser::or`\npub struct Or {\n f: F,\n g: G,\n}\n\nimpl<\n I: Clone,\n O,\n E: ParseError,\n F: Parser,\n G: Parser,\n > Parser for Or\n{\n type Output = >::Output;\n type Error = >::Error;\n\n fn process(&mut self, i: I) -> PResult {\n match self.f.process::(i.clone()) {\n Err(Err::Error(e1)) => match self.g.process::(i) {\n Err(Err::Error(e2)) => Err(Err::Error(OM::Error::combine(e1, e2, |e1, e2| e1.or(e2)))),\n res => res,\n },\n res => res,\n }\n }\n}\n\n/// Implementation of `Parser::into`\npub struct Into {\n f: F,\n phantom_out2: core::marker::PhantomData,\n phantom_err2: core::marker::PhantomData,\n}\n\nimpl<\n I,\n O2: From<>::Output>,\n E2: crate::error::ParseError + From<>::Error>,\n F: Parser,\n > Parser for Into\n{\n type Output = O2;\n type Error = E2;\n\n fn process(&mut self, i: I) -> PResult {\n match self.f.process::(i) {\n Ok((i, o)) => Ok((i, OM::Output::map(o, |o| o.into()))),\n Err(Err::Error(e)) => Err(Err::Error(OM::Error::map(e, |e| e.into()))),\n Err(Err::Failure(e)) => Err(Err::Failure(e.into())),\n Err(Err::Incomplete(e)) => Err(Err::Incomplete(e)),\n }\n }\n}\n\n/// Alternate between two Parser implementations with the same result type.\npub(crate) enum Either {\n Left(F),\n Right(G),\n}\n\nimpl<\n I,\n F: Parser,\n G: Parser>::Output, Error = >::Error>,\n > Parser for Either\n{\n type Output = >::Output;\n type Error = >::Error;\n\n #[inline]\n fn process(&mut self, i: I) -> PResult {\n match self {\n Either::Left(f) => f.process::(i),\n Either::Right(g) => g.process::(i),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use crate::error::ErrorKind;\n\n use crate::bytes::streaming::{tag, take};\n use crate::number::streaming::be_u16;\n use crate::sequence::terminated;\n\n #[doc(hidden)]\n #[macro_export]\n macro_rules! assert_size (\n ($t:ty, $sz:expr) => (\n assert_eq!($crate::lib::std::mem::size_of::<$t>(), $sz);\n );\n );\n\n #[test]\n #[cfg(target_pointer_width = \"64\")]\n fn size_test() {\n assert_size!(IResult<&[u8], &[u8], (&[u8], u32)>, 40);\n //FIXME: since rust 1.65, this is now 32 bytes, likely thanks to https://github.com/rust-lang/rust/pull/94075\n // deactivating that test for now because it'll have different values depending on the rust version\n // assert_size!(IResult<&str, &str, u32>, 40);\n assert_size!(Needed, 8);\n assert_size!(Err, 16);\n assert_size!(ErrorKind, 1);\n }\n\n #[test]\n fn err_map_test() {\n let e = Err::Error(1);\n assert_eq!(e.map(|v| v + 1), Err::Error(2));\n }\n\n #[test]\n fn native_tuple_test() {\n fn tuple_3(i: &[u8]) -> IResult<&[u8], (u16, &[u8])> {\n terminated((be_u16, take(3u8)), tag(\"fg\")).parse(i)\n }\n\n assert_eq!(\n tuple_3(&b\"abcdefgh\"[..]),\n Ok((&b\"h\"[..], (0x6162u16, &b\"cde\"[..])))\n );\n assert_eq!(tuple_3(&b\"abcd\"[..]), Err(Err::Incomplete(Needed::new(1))));\n assert_eq!(tuple_3(&b\"abcde\"[..]), Err(Err::Incomplete(Needed::new(2))));\n assert_eq!(\n tuple_3(&b\"abcdejk\"[..]),\n Err(Err::Error(error_position!(&b\"jk\"[..], ErrorKind::Tag)))\n );\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "macros.rs", "content": "macro_rules! succ (\n (0, $submac:ident ! ($($rest:tt)*)) => ($submac!(1, $($rest)*));\n (1, $submac:ident ! ($($rest:tt)*)) => ($submac!(2, $($rest)*));\n (2, $submac:ident ! ($($rest:tt)*)) => ($submac!(3, $($rest)*));\n (3, $submac:ident ! ($($rest:tt)*)) => ($submac!(4, $($rest)*));\n (4, $submac:ident ! ($($rest:tt)*)) => ($submac!(5, $($rest)*));\n (5, $submac:ident ! ($($rest:tt)*)) => ($submac!(6, $($rest)*));\n (6, $submac:ident ! ($($rest:tt)*)) => ($submac!(7, $($rest)*));\n (7, $submac:ident ! ($($rest:tt)*)) => ($submac!(8, $($rest)*));\n (8, $submac:ident ! ($($rest:tt)*)) => ($submac!(9, $($rest)*));\n (9, $submac:ident ! ($($rest:tt)*)) => ($submac!(10, $($rest)*));\n (10, $submac:ident ! ($($rest:tt)*)) => ($submac!(11, $($rest)*));\n (11, $submac:ident ! ($($rest:tt)*)) => ($submac!(12, $($rest)*));\n (12, $submac:ident ! ($($rest:tt)*)) => ($submac!(13, $($rest)*));\n (13, $submac:ident ! ($($rest:tt)*)) => ($submac!(14, $($rest)*));\n (14, $submac:ident ! ($($rest:tt)*)) => ($submac!(15, $($rest)*));\n (15, $submac:ident ! ($($rest:tt)*)) => ($submac!(16, $($rest)*));\n (16, $submac:ident ! ($($rest:tt)*)) => ($submac!(17, $($rest)*));\n (17, $submac:ident ! ($($rest:tt)*)) => ($submac!(18, $($rest)*));\n (18, $submac:ident ! ($($rest:tt)*)) => ($submac!(19, $($rest)*));\n (19, $submac:ident ! ($($rest:tt)*)) => ($submac!(20, $($rest)*));\n (20, $submac:ident ! ($($rest:tt)*)) => ($submac!(21, $($rest)*));\n);"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "traits.rs", "content": "use core::iter::Enumerate;\nuse core::str::CharIndices;\n\nuse crate::error::{ErrorKind, ParseError};\nuse crate::internal::{Err, IResult, Needed};\nuse crate::lib::std::iter::Copied;\nuse crate::lib::std::ops::{\n Bound, Range, RangeBounds, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive,\n};\nuse crate::lib::std::slice::Iter;\nuse crate::lib::std::str::from_utf8;\nuse crate::lib::std::str::Chars;\nuse crate::lib::std::str::FromStr;\nuse crate::IsStreaming;\nuse crate::Mode;\n\n#[cfg(feature = \"alloc\")]\nuse crate::lib::std::string::String;\n#[cfg(feature = \"alloc\")]\nuse crate::lib::std::vec::Vec;\n\n/// Parser input types must implement this trait\npub trait Input: Clone + Sized {\n /// The current input type is a sequence of that `Item` type.\n ///\n /// Example: `u8` for `&[u8]` or `char` for `&str`\n type Item;\n\n /// An iterator over the input type, producing the item\n type Iter: Iterator;\n\n /// An iterator over the input type, producing the item and its byte position\n /// If we're iterating over `&str`, the position\n /// corresponds to the byte index of the character\n type IterIndices: Iterator;\n\n /// Calculates the input length, as indicated by its name,\n /// and the name of the trait itself\n fn input_len(&self) -> usize;\n\n /// Returns a slice of `index` bytes. panics if index > length\n fn take(&self, index: usize) -> Self;\n /// Returns a slice starting at `index` bytes. panics if index > length\n fn take_from(&self, index: usize) -> Self;\n /// Split the stream at the `index` byte offset. panics if index > length\n fn take_split(&self, index: usize) -> (Self, Self);\n\n /// Returns the byte position of the first element satisfying the predicate\n fn position

(&self, predicate: P) -> Option\n where\n P: Fn(Self::Item) -> bool;\n\n /// Returns an iterator over the elements\n fn iter_elements(&self) -> Self::Iter;\n /// Returns an iterator over the elements and their byte offsets\n fn iter_indices(&self) -> Self::IterIndices;\n\n /// Get the byte offset from the element's position in the stream\n fn slice_index(&self, count: usize) -> Result;\n\n /// Looks for the first element of the input type for which the condition returns true,\n /// and returns the input up to this position.\n ///\n /// *streaming version*: If no element is found matching the condition, this will return `Incomplete`\n fn split_at_position>(&self, predicate: P) -> IResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.position(predicate) {\n Some(n) => Ok(self.take_split(n)),\n None => Err(Err::Incomplete(Needed::new(1))),\n }\n }\n\n /// Looks for the first element of the input type for which the condition returns true\n /// and returns the input up to this position.\n ///\n /// Fails if the produced slice is empty.\n ///\n /// *streaming version*: If no element is found matching the condition, this will return `Incomplete`\n fn split_at_position1>(\n &self,\n predicate: P,\n e: ErrorKind,\n ) -> IResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.position(predicate) {\n Some(0) => Err(Err::Error(E::from_error_kind(self.clone(), e))),\n Some(n) => Ok(self.take_split(n)),\n None => Err(Err::Incomplete(Needed::new(1))),\n }\n }\n\n /// Looks for the first element of the input type for which the condition returns true,\n /// and returns the input up to this position.\n ///\n /// *complete version*: If no element is found matching the condition, this will return the whole input\n fn split_at_position_complete>(\n &self,\n predicate: P,\n ) -> IResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.split_at_position(predicate) {\n Err(Err::Incomplete(_)) => Ok(self.take_split(self.input_len())),\n res => res,\n }\n }\n\n /// Looks for the first element of the input type for which the condition returns true\n /// and returns the input up to this position.\n ///\n /// Fails if the produced slice is empty.\n ///\n /// *complete version*: If no element is found matching the condition, this will return the whole input\n fn split_at_position1_complete>(\n &self,\n predicate: P,\n e: ErrorKind,\n ) -> IResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.split_at_position1(predicate, e) {\n Err(Err::Incomplete(_)) => {\n if self.input_len() == 0 {\n Err(Err::Error(E::from_error_kind(self.clone(), e)))\n } else {\n Ok(self.take_split(self.input_len()))\n }\n }\n res => res,\n }\n }\n\n /// mode version of split_at_position\n fn split_at_position_mode>(\n &self,\n predicate: P,\n ) -> crate::PResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.position(predicate) {\n Some(n) => Ok((self.take_from(n), OM::Output::bind(|| self.take(n)))),\n None => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::new(1)))\n } else {\n let len = self.input_len();\n Ok((self.take_from(len), OM::Output::bind(|| self.take(len))))\n }\n }\n }\n }\n\n /// mode version of split_at_position\n fn split_at_position_mode1>(\n &self,\n predicate: P,\n e: ErrorKind,\n ) -> crate::PResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.position(predicate) {\n Some(0) => Err(Err::Error(OM::Error::bind(|| {\n E::from_error_kind(self.clone(), e)\n }))),\n Some(n) => Ok((self.take_from(n), OM::Output::bind(|| self.take(n)))),\n None => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::new(1)))\n } else {\n let len = self.input_len();\n if len == 0 {\n Err(Err::Error(OM::Error::bind(|| {\n E::from_error_kind(self.clone(), e)\n })))\n } else {\n Ok((self.take_from(len), OM::Output::bind(|| self.take(len))))\n }\n }\n }\n }\n }\n}\n\nimpl<'a> Input for &'a [u8] {\n type Item = u8;\n type Iter = Copied>;\n type IterIndices = Enumerate;\n\n fn input_len(&self) -> usize {\n self.len()\n }\n\n #[inline]\n fn take(&self, index: usize) -> Self {\n &self[0..index]\n }\n\n fn take_from(&self, index: usize) -> Self {\n &self[index..]\n }\n #[inline]\n fn take_split(&self, index: usize) -> (Self, Self) {\n let (prefix, suffix) = self.split_at(index);\n (suffix, prefix)\n }\n\n #[inline]\n fn position

(&self, predicate: P) -> Option\n where\n P: Fn(Self::Item) -> bool,\n {\n self.iter().position(|b| predicate(*b))\n }\n\n #[inline]\n fn iter_elements(&self) -> Self::Iter {\n self.iter().copied()\n }\n\n #[inline]\n fn iter_indices(&self) -> Self::IterIndices {\n self.iter_elements().enumerate()\n }\n\n #[inline]\n fn slice_index(&self, count: usize) -> Result {\n if self.len() >= count {\n Ok(count)\n } else {\n Err(Needed::new(count - self.len()))\n }\n }\n\n #[inline(always)]\n fn split_at_position>(&self, predicate: P) -> IResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.iter().position(|c| predicate(*c)) {\n Some(i) => Ok(self.take_split(i)),\n None => Err(Err::Incomplete(Needed::new(1))),\n }\n }\n\n #[inline(always)]\n fn split_at_position1>(\n &self,\n predicate: P,\n e: ErrorKind,\n ) -> IResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.iter().position(|c| predicate(*c)) {\n Some(0) => Err(Err::Error(E::from_error_kind(self, e))),\n Some(i) => Ok(self.take_split(i)),\n None => Err(Err::Incomplete(Needed::new(1))),\n }\n }\n\n fn split_at_position_complete>(\n &self,\n predicate: P,\n ) -> IResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.iter().position(|c| predicate(*c)) {\n Some(i) => Ok(self.take_split(i)),\n None => Ok(self.take_split(self.len())),\n }\n }\n\n #[inline(always)]\n fn split_at_position1_complete>(\n &self,\n predicate: P,\n e: ErrorKind,\n ) -> IResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.iter().position(|c| predicate(*c)) {\n Some(0) => Err(Err::Error(E::from_error_kind(self, e))),\n Some(i) => Ok(self.take_split(i)),\n None => {\n if self.is_empty() {\n Err(Err::Error(E::from_error_kind(self, e)))\n } else {\n Ok(self.take_split(self.len()))\n }\n }\n }\n }\n\n /// mode version of split_at_position\n #[inline(always)]\n fn split_at_position_mode>(\n &self,\n predicate: P,\n ) -> crate::PResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.iter().position(|c| predicate(*c)) {\n Some(n) => Ok((self.take_from(n), OM::Output::bind(|| self.take(n)))),\n None => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::new(1)))\n } else {\n Ok((\n self.take_from(self.len()),\n OM::Output::bind(|| self.take(self.len())),\n ))\n }\n }\n }\n }\n\n /// mode version of split_at_position\n #[inline(always)]\n fn split_at_position_mode1>(\n &self,\n predicate: P,\n e: ErrorKind,\n ) -> crate::PResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.iter().position(|c| predicate(*c)) {\n Some(0) => Err(Err::Error(OM::Error::bind(|| E::from_error_kind(self, e)))),\n Some(n) => Ok((self.take_from(n), OM::Output::bind(|| self.take(n)))),\n None => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::new(1)))\n } else if self.is_empty() {\n Err(Err::Error(OM::Error::bind(|| E::from_error_kind(self, e))))\n } else {\n Ok((\n self.take_from(self.len()),\n OM::Output::bind(|| self.take(self.len())),\n ))\n }\n }\n }\n }\n}\n\nimpl<'a> Input for &'a str {\n type Item = char;\n type Iter = Chars<'a>;\n type IterIndices = CharIndices<'a>;\n\n fn input_len(&self) -> usize {\n self.len()\n }\n\n #[inline]\n fn take(&self, index: usize) -> Self {\n &self[..index]\n }\n\n #[inline]\n fn take_from(&self, index: usize) -> Self {\n &self[index..]\n }\n\n // return byte index\n #[inline]\n fn take_split(&self, index: usize) -> (Self, Self) {\n let (prefix, suffix) = self.split_at(index);\n (suffix, prefix)\n }\n\n fn position

(&self, predicate: P) -> Option\n where\n P: Fn(Self::Item) -> bool,\n {\n self.find(predicate)\n }\n\n #[inline]\n fn iter_elements(&self) -> Self::Iter {\n self.chars()\n }\n\n #[inline]\n fn iter_indices(&self) -> Self::IterIndices {\n self.char_indices()\n }\n\n #[inline]\n fn slice_index(&self, count: usize) -> Result {\n let mut cnt = 0;\n for (index, _) in self.char_indices() {\n if cnt == count {\n return Ok(index);\n }\n cnt += 1;\n }\n if cnt == count {\n return Ok(self.len());\n }\n Err(Needed::Unknown)\n }\n\n #[inline(always)]\n fn split_at_position>(&self, predicate: P) -> IResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.find(predicate) {\n // The position i is returned from str::find() which means it is within the bounds of the string\n Some(i) => {\n let (str1, str2) = self.split_at(i);\n Ok((str2, str1))\n }\n None => Err(Err::Incomplete(Needed::new(1))),\n }\n }\n\n #[inline(always)]\n fn split_at_position1>(\n &self,\n predicate: P,\n e: ErrorKind,\n ) -> IResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.find(predicate) {\n Some(0) => Err(Err::Error(E::from_error_kind(self, e))),\n // The position i is returned from str::find() which means it is within the bounds of the string\n Some(i) => {\n let (str1, str2) = self.split_at(i);\n Ok((str2, str1))\n }\n None => Err(Err::Incomplete(Needed::new(1))),\n }\n }\n\n #[inline(always)]\n fn split_at_position_complete>(\n &self,\n predicate: P,\n ) -> IResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.find(predicate) {\n // The position i is returned from str::find() which means it is within the bounds of the string\n Some(i) => {\n let (str1, str2) = self.split_at(i);\n Ok((str2, str1))\n }\n None => Ok(self.take_split(self.input_len())),\n }\n }\n\n #[inline(always)]\n fn split_at_position1_complete>(\n &self,\n predicate: P,\n e: ErrorKind,\n ) -> IResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.find(predicate) {\n Some(0) => Err(Err::Error(E::from_error_kind(self, e))),\n // The position i is returned from str::find() which means it is within the bounds of the string\n Some(i) => {\n let (str1, str2) = self.split_at(i);\n Ok((str2, str1))\n }\n None => {\n if self.is_empty() {\n Err(Err::Error(E::from_error_kind(self, e)))\n } else {\n // the end of slice is a char boundary\n let (str1, str2) = self.split_at(self.len());\n Ok((str2, str1))\n }\n }\n }\n }\n\n /// mode version of split_at_position\n #[inline(always)]\n fn split_at_position_mode>(\n &self,\n predicate: P,\n ) -> crate::PResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.find(predicate) {\n Some(n) => unsafe {\n // find() returns a byte index that is already in the slice at a char boundary\n Ok((\n self.get_unchecked(n..),\n OM::Output::bind(|| self.get_unchecked(..n)),\n ))\n },\n None => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::new(1)))\n } else {\n // the end of slice is a char boundary\n unsafe {\n Ok((\n self.get_unchecked(self.len()..),\n OM::Output::bind(|| self.get_unchecked(..self.len())),\n ))\n }\n }\n }\n }\n }\n\n /// mode version of split_at_position\n #[inline(always)]\n fn split_at_position_mode1>(\n &self,\n predicate: P,\n e: ErrorKind,\n ) -> crate::PResult\n where\n P: Fn(Self::Item) -> bool,\n {\n match self.find(predicate) {\n Some(0) => Err(Err::Error(OM::Error::bind(|| E::from_error_kind(self, e)))),\n Some(n) => unsafe {\n // find() returns a byte index that is already in the slice at a char boundary\n Ok((\n self.get_unchecked(n..),\n OM::Output::bind(|| self.get_unchecked(..n)),\n ))\n },\n None => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::new(1)))\n } else if self.is_empty() {\n Err(Err::Error(OM::Error::bind(|| E::from_error_kind(self, e))))\n } else {\n // the end of slice is a char boundary\n unsafe {\n Ok((\n self.get_unchecked(self.len()..),\n OM::Output::bind(|| self.get_unchecked(..self.len())),\n ))\n }\n }\n }\n }\n }\n}\n\n/// Useful functions to calculate the offset between slices and show a hexdump of a slice\npub trait Offset {\n /// Offset between the first byte of self and the first byte of the argument\n /// the argument must be a part of self, otherwise this can fail with arithmetic\n /// underflows as it compares byte offsets\n fn offset(&self, second: &Self) -> usize;\n}\n\nimpl Offset for [u8] {\n fn offset(&self, second: &Self) -> usize {\n let fst = self.as_ptr();\n let snd = second.as_ptr();\n\n snd as usize - fst as usize\n }\n}\n\nimpl<'a> Offset for &'a [u8] {\n fn offset(&self, second: &Self) -> usize {\n let fst = self.as_ptr();\n let snd = second.as_ptr();\n\n snd as usize - fst as usize\n }\n}\n\nimpl Offset for str {\n fn offset(&self, second: &Self) -> usize {\n let fst = self.as_ptr();\n let snd = second.as_ptr();\n\n snd as usize - fst as usize\n }\n}\n\nimpl<'a> Offset for &'a str {\n fn offset(&self, second: &Self) -> usize {\n let fst = self.as_ptr();\n let snd = second.as_ptr();\n\n snd as usize - fst as usize\n }\n}\n\n/// Helper trait for types that can be viewed as a byte slice\npub trait AsBytes {\n /// Casts the input type to a byte slice\n fn as_bytes(&self) -> &[u8];\n}\n\nimpl<'a> AsBytes for &'a str {\n #[inline(always)]\n fn as_bytes(&self) -> &[u8] {\n (*self).as_bytes()\n }\n}\n\nimpl AsBytes for str {\n #[inline(always)]\n fn as_bytes(&self) -> &[u8] {\n self.as_ref()\n }\n}\n\nimpl<'a> AsBytes for &'a [u8] {\n #[inline(always)]\n fn as_bytes(&self) -> &[u8] {\n self\n }\n}\n\nimpl AsBytes for [u8] {\n #[inline(always)]\n fn as_bytes(&self) -> &[u8] {\n self\n }\n}\n\nimpl<'a, const N: usize> AsBytes for &'a [u8; N] {\n #[inline(always)]\n fn as_bytes(&self) -> &[u8] {\n self.as_slice()\n }\n}\n\nimpl AsBytes for [u8; N] {\n #[inline(always)]\n fn as_bytes(&self) -> &[u8] {\n self\n }\n}\n\n/// Transforms common types to a char for basic token parsing\n#[allow(clippy::len_without_is_empty)]\npub trait AsChar: Copy {\n /// makes a char from self\n fn as_char(self) -> char;\n\n /// Tests that self is an alphabetic character\n ///\n /// Warning: for `&str` it recognizes alphabetic\n /// characters outside of the 52 ASCII letters\n fn is_alpha(self) -> bool;\n\n /// Tests that self is an alphabetic character\n /// or a decimal digit\n fn is_alphanum(self) -> bool;\n /// Tests that self is a decimal digit\n fn is_dec_digit(self) -> bool;\n /// Tests that self is an hex digit\n fn is_hex_digit(self) -> bool;\n /// Tests that self is an octal digit\n fn is_oct_digit(self) -> bool;\n /// Tests that self is a binary digit\n fn is_bin_digit(self) -> bool;\n /// Gets the len in bytes for self\n fn len(self) -> usize;\n /// Tests that self is ASCII space or tab\n fn is_space(self) -> bool;\n /// Tests if byte is ASCII newline: \\n\n fn is_newline(self) -> bool;\n}\n\nimpl AsChar for u8 {\n #[inline]\n fn as_char(self) -> char {\n self as char\n }\n #[inline]\n fn is_alpha(self) -> bool {\n matches!(self, 0x41..=0x5A | 0x61..=0x7A)\n }\n #[inline]\n fn is_alphanum(self) -> bool {\n self.is_alpha() || self.is_dec_digit()\n }\n #[inline]\n fn is_dec_digit(self) -> bool {\n matches!(self, 0x30..=0x39)\n }\n #[inline]\n fn is_hex_digit(self) -> bool {\n matches!(self, 0x30..=0x39 | 0x41..=0x46 | 0x61..=0x66)\n }\n #[inline]\n fn is_oct_digit(self) -> bool {\n matches!(self, 0x30..=0x37)\n }\n #[inline]\n fn is_bin_digit(self) -> bool {\n matches!(self, 0x30..=0x31)\n }\n #[inline]\n fn len(self) -> usize {\n 1\n }\n #[inline]\n fn is_space(self) -> bool {\n self == b' ' || self == b'\\t'\n }\n fn is_newline(self) -> bool {\n self == b'\\n'\n }\n}\nimpl<'a> AsChar for &'a u8 {\n #[inline]\n fn as_char(self) -> char {\n }\n #[inline]\n fn is_alpha(self) -> bool {\n matches!(*self, 0x41..=0x5A | 0x61..=0x7A)\n }\n #[inline]\n fn is_alphanum(self) -> bool {\n self.is_alpha() || self.is_dec_digit()\n }\n #[inline]\n fn is_dec_digit(self) -> bool {\n matches!(*self, 0x30..=0x39)\n }\n #[inline]\n fn is_hex_digit(self) -> bool {\n matches!(*self, 0x30..=0x39 | 0x41..=0x46 | 0x61..=0x66)\n }\n #[inline]\n fn is_oct_digit(self) -> bool {\n matches!(*self, 0x30..=0x37)\n }\n #[inline]\n fn is_bin_digit(self) -> bool {\n matches!(*self, 0x30..=0x31)\n }\n #[inline]\n fn len(self) -> usize {\n 1\n }\n #[inline]\n fn is_space(self) -> bool {\n }\n fn is_newline(self) -> bool {\n }\n}\n\nimpl AsChar for char {\n #[inline]\n fn as_char(self) -> char {\n self\n }\n #[inline]\n fn is_alpha(self) -> bool {\n self.is_ascii_alphabetic()\n }\n #[inline]\n fn is_alphanum(self) -> bool {\n self.is_alpha() || self.is_dec_digit()\n }\n #[inline]\n fn is_dec_digit(self) -> bool {\n self.is_ascii_digit()\n }\n #[inline]\n fn is_hex_digit(self) -> bool {\n self.is_ascii_hexdigit()\n }\n #[inline]\n fn is_oct_digit(self) -> bool {\n self.is_digit(8)\n }\n #[inline]\n fn is_bin_digit(self) -> bool {\n self.is_digit(2)\n }\n #[inline]\n fn len(self) -> usize {\n self.len_utf8()\n }\n #[inline]\n fn is_space(self) -> bool {\n self == ' ' || self == '\\t'\n }\n fn is_newline(self) -> bool {\n self == '\\n'\n }\n}\n\nimpl<'a> AsChar for &'a char {\n #[inline]\n fn as_char(self) -> char {\n }\n #[inline]\n fn is_alpha(self) -> bool {\n self.is_ascii_alphabetic()\n }\n #[inline]\n fn is_alphanum(self) -> bool {\n self.is_alpha() || self.is_dec_digit()\n }\n #[inline]\n fn is_dec_digit(self) -> bool {\n self.is_ascii_digit()\n }\n #[inline]\n fn is_hex_digit(self) -> bool {\n self.is_ascii_hexdigit()\n }\n #[inline]\n fn is_oct_digit(self) -> bool {\n self.is_digit(8)\n }\n #[inline]\n fn is_bin_digit(self) -> bool {\n self.is_digit(2)\n }\n #[inline]\n fn len(self) -> usize {\n self.len_utf8()\n }\n #[inline]\n fn is_space(self) -> bool {\n }\n fn is_newline(self) -> bool {\n }\n}\n\n/// Indicates whether a comparison was successful, an error, or\n/// if more data was needed\n#[derive(Debug, Eq, PartialEq)]\npub enum CompareResult {\n /// Comparison was successful\n Ok,\n /// We need more data to be sure\n Incomplete,\n /// Comparison failed\n Error,\n}\n\n/// Abstracts comparison operations\npub trait Compare {\n /// Compares self to another value for equality\n fn compare(&self, t: T) -> CompareResult;\n /// Compares self to another value for equality\n /// independently of the case.\n ///\n /// Warning: for `&str`, the comparison is done\n /// by lowercasing both strings and comparing\n /// the result. This is a temporary solution until\n /// a better one appears\n fn compare_no_case(&self, t: T) -> CompareResult;\n}\n\nfn lowercase_byte(c: u8) -> u8 {\n match c {\n b'A'..=b'Z' => c - b'A' + b'a',\n _ => c,\n }\n}\n\nimpl<'a, 'b> Compare<&'b [u8]> for &'a [u8] {\n #[inline(always)]\n fn compare(&self, t: &'b [u8]) -> CompareResult {\n let pos = self.iter().zip(t.iter()).position(|(a, b)| a != b);\n\n match pos {\n Some(_) => CompareResult::Error,\n None => {\n if self.len() >= t.len() {\n CompareResult::Ok\n } else {\n CompareResult::Incomplete\n }\n }\n }\n }\n\n #[inline(always)]\n fn compare_no_case(&self, t: &'b [u8]) -> CompareResult {\n if self\n .iter()\n .zip(t)\n .any(|(a, b)| lowercase_byte(*a) != lowercase_byte(*b))\n {\n CompareResult::Error\n } else if self.len() < t.len() {\n CompareResult::Incomplete\n } else {\n CompareResult::Ok\n }\n }\n}\n\nimpl<'a, 'b> Compare<&'b str> for &'a [u8] {\n #[inline(always)]\n fn compare(&self, t: &'b str) -> CompareResult {\n self.compare(AsBytes::as_bytes(t))\n }\n #[inline(always)]\n fn compare_no_case(&self, t: &'b str) -> CompareResult {\n self.compare_no_case(AsBytes::as_bytes(t))\n }\n}\n\nimpl<'a, 'b> Compare<&'b str> for &'a str {\n #[inline(always)]\n fn compare(&self, t: &'b str) -> CompareResult {\n self.as_bytes().compare(t.as_bytes())\n }\n\n //FIXME: this version is too simple and does not use the current locale\n #[inline(always)]\n fn compare_no_case(&self, t: &'b str) -> CompareResult {\n let pos = self\n .chars()\n .zip(t.chars())\n .position(|(a, b)| a.to_lowercase().ne(b.to_lowercase()));\n\n match pos {\n Some(_) => CompareResult::Error,\n None => {\n if self.len() >= t.len() {\n CompareResult::Ok\n } else {\n CompareResult::Incomplete\n }\n }\n }\n }\n}\n\nimpl<'a, 'b> Compare<&'b [u8]> for &'a str {\n #[inline(always)]\n fn compare(&self, t: &'b [u8]) -> CompareResult {\n AsBytes::as_bytes(self).compare(t)\n }\n #[inline(always)]\n fn compare_no_case(&self, t: &'b [u8]) -> CompareResult {\n AsBytes::as_bytes(self).compare_no_case(t)\n }\n}\n\n/// Look for a token in self\npub trait FindToken {\n /// Returns true if self contains the token\n fn find_token(&self, token: T) -> bool;\n}\n\nimpl<'a> FindToken for &'a [u8] {\n fn find_token(&self, token: u8) -> bool {\n memchr::memchr(token, self).is_some()\n }\n}\n\nimpl<'a> FindToken for &'a str {\n fn find_token(&self, token: u8) -> bool {\n self.as_bytes().find_token(token)\n }\n}\n\nimpl<'a, 'b> FindToken<&'a u8> for &'b [u8] {\n fn find_token(&self, token: &u8) -> bool {\n self.find_token(*token)\n }\n}\n\nimpl<'a, 'b> FindToken<&'a u8> for &'b str {\n fn find_token(&self, token: &u8) -> bool {\n self.as_bytes().find_token(token)\n }\n}\n\nimpl<'a> FindToken for &'a [u8] {\n fn find_token(&self, token: char) -> bool {\n self.iter().any(|i| *i == token as u8)\n }\n}\n\nimpl<'a> FindToken for &'a str {\n fn find_token(&self, token: char) -> bool {\n self.chars().any(|i| i == token)\n }\n}\n\nimpl<'a> FindToken for &'a [char] {\n fn find_token(&self, token: char) -> bool {\n self.iter().any(|i| *i == token)\n }\n}\n\nimpl<'a, 'b> FindToken<&'a char> for &'b [char] {\n fn find_token(&self, token: &char) -> bool {\n self.find_token(*token)\n }\n}\n\n/// Look for a substring in self\npub trait FindSubstring {\n /// Returns the byte position of the substring if it is found\n fn find_substring(&self, substr: T) -> Option;\n}\n\nimpl<'a, 'b> FindSubstring<&'b [u8]> for &'a [u8] {\n fn find_substring(&self, substr: &'b [u8]) -> Option {\n if substr.len() > self.len() {\n return None;\n }\n\n let (&substr_first, substr_rest) = match substr.split_first() {\n Some(split) => split,\n // an empty substring is found at position 0\n // This matches the behavior of str.find(\"\").\n None => return Some(0),\n };\n\n if substr_rest.is_empty() {\n return memchr::memchr(substr_first, self);\n }\n\n let mut offset = 0;\n let haystack = &self[..self.len() - substr_rest.len()];\n\n while let Some(position) = memchr::memchr(substr_first, &haystack[offset..]) {\n offset += position;\n let next_offset = offset + 1;\n if &self[next_offset..][..substr_rest.len()] == substr_rest {\n return Some(offset);\n }\n\n offset = next_offset;\n }\n\n None\n }\n}\n\nimpl<'a, 'b> FindSubstring<&'b str> for &'a [u8] {\n fn find_substring(&self, substr: &'b str) -> Option {\n self.find_substring(AsBytes::as_bytes(substr))\n }\n}\n\nimpl<'a, 'b> FindSubstring<&'b str> for &'a str {\n //returns byte index\n fn find_substring(&self, substr: &'b str) -> Option {\n self.find(substr)\n }\n}\n\n/// Used to integrate `str`'s `parse()` method\npub trait ParseTo {\n /// Succeeds if `parse()` succeeded. The byte slice implementation\n /// will first convert it to a `&str`, then apply the `parse()` function\n fn parse_to(&self) -> Option;\n}\n\nimpl<'a, R: FromStr> ParseTo for &'a [u8] {\n fn parse_to(&self) -> Option {\n from_utf8(self).ok().and_then(|s| s.parse().ok())\n }\n}\n\nimpl<'a, R: FromStr> ParseTo for &'a str {\n fn parse_to(&self) -> Option {\n self.parse().ok()\n }\n}\n\nimpl<'a, const N: usize> Compare<[u8; N]> for &'a [u8] {\n #[inline(always)]\n fn compare(&self, t: [u8; N]) -> CompareResult {\n self.compare(&t[..])\n }\n\n #[inline(always)]\n fn compare_no_case(&self, t: [u8; N]) -> CompareResult {\n self.compare_no_case(&t[..])\n }\n}\n\nimpl<'a, 'b, const N: usize> Compare<&'b [u8; N]> for &'a [u8] {\n #[inline(always)]\n fn compare(&self, t: &'b [u8; N]) -> CompareResult {\n self.compare(&t[..])\n }\n\n #[inline(always)]\n fn compare_no_case(&self, t: &'b [u8; N]) -> CompareResult {\n self.compare_no_case(&t[..])\n }\n}\n\nimpl FindToken for [u8; N] {\n fn find_token(&self, token: u8) -> bool {\n memchr::memchr(token, &self[..]).is_some()\n }\n}\n\nimpl<'a, const N: usize> FindToken<&'a u8> for [u8; N] {\n fn find_token(&self, token: &u8) -> bool {\n self.find_token(*token)\n }\n}\n\n/// Abstracts something which can extend an `Extend`.\n/// Used to build modified input slices in `escaped_transform`\npub trait ExtendInto {\n /// The current input type is a sequence of that `Item` type.\n ///\n /// Example: `u8` for `&[u8]` or `char` for `&str`\n type Item;\n\n /// The type that will be produced\n type Extender;\n\n /// Create a new `Extend` of the correct type\n fn new_builder(&self) -> Self::Extender;\n /// Accumulate the input into an accumulator\n fn extend_into(&self, acc: &mut Self::Extender);\n}\n\n#[cfg(feature = \"alloc\")]\nimpl ExtendInto for [u8] {\n type Item = u8;\n type Extender = Vec;\n\n #[inline]\n fn new_builder(&self) -> Vec {\n Vec::new()\n }\n #[inline]\n fn extend_into(&self, acc: &mut Vec) {\n acc.extend(self.iter().cloned());\n }\n}\n\n#[cfg(feature = \"alloc\")]\nimpl ExtendInto for &[u8] {\n type Item = u8;\n type Extender = Vec;\n\n #[inline]\n fn new_builder(&self) -> Vec {\n Vec::new()\n }\n #[inline]\n fn extend_into(&self, acc: &mut Vec) {\n acc.extend_from_slice(self);\n }\n}\n\n#[cfg(feature = \"alloc\")]\nimpl ExtendInto for str {\n type Item = char;\n type Extender = String;\n\n #[inline]\n fn new_builder(&self) -> String {\n String::new()\n }\n #[inline]\n fn extend_into(&self, acc: &mut String) {\n acc.push_str(self);\n }\n}\n\n#[cfg(feature = \"alloc\")]\nimpl ExtendInto for &str {\n type Item = char;\n type Extender = String;\n\n #[inline]\n fn new_builder(&self) -> String {\n String::new()\n }\n #[inline]\n fn extend_into(&self, acc: &mut String) {\n acc.push_str(self);\n }\n}\n\n#[cfg(feature = \"alloc\")]\nimpl ExtendInto for char {\n type Item = char;\n type Extender = String;\n\n #[inline]\n fn new_builder(&self) -> String {\n String::new()\n }\n #[inline]\n fn extend_into(&self, acc: &mut String) {\n acc.push(*self);\n }\n}\n\n/// Helper trait to convert numbers to usize.\n///\n/// By default, usize implements `From` and `From` but not\n/// `From` and `From` because that would be invalid on some\n/// platforms. This trait implements the conversion for platforms\n/// with 32 and 64 bits pointer platforms\npub trait ToUsize {\n /// converts self to usize\n fn to_usize(&self) -> usize;\n}\n\nimpl ToUsize for u8 {\n #[inline]\n fn to_usize(&self) -> usize {\n }\n}\n\nimpl ToUsize for u16 {\n #[inline]\n fn to_usize(&self) -> usize {\n }\n}\n\nimpl ToUsize for usize {\n #[inline]\n fn to_usize(&self) -> usize {\n }\n}\n\n#[cfg(any(target_pointer_width = \"32\", target_pointer_width = \"64\"))]\nimpl ToUsize for u32 {\n #[inline]\n fn to_usize(&self) -> usize {\n }\n}\n\n#[cfg(target_pointer_width = \"64\")]\nimpl ToUsize for u64 {\n #[inline]\n fn to_usize(&self) -> usize {\n }\n}\n\n/// Equivalent From implementation to avoid orphan rules in bits parsers\npub trait ErrorConvert {\n /// Transform to another error type\n fn convert(self) -> E;\n}\n\nimpl ErrorConvert<(I, ErrorKind)> for ((I, usize), ErrorKind) {\n fn convert(self) -> (I, ErrorKind) {\n ((self.0).0, self.1)\n }\n}\n\nimpl ErrorConvert<((I, usize), ErrorKind)> for (I, ErrorKind) {\n fn convert(self) -> ((I, usize), ErrorKind) {\n ((self.0, 0), self.1)\n }\n}\n\nuse crate::error;\nimpl ErrorConvert> for error::Error<(I, usize)> {\n fn convert(self) -> error::Error {\n error::Error {\n input: self.input.0,\n code: self.code,\n }\n }\n}\n\nimpl ErrorConvert> for error::Error {\n fn convert(self) -> error::Error<(I, usize)> {\n error::Error {\n input: (self.input, 0),\n code: self.code,\n }\n }\n}\n\nimpl ErrorConvert<()> for () {\n fn convert(self) {}\n}\n\n#[cfg(feature = \"std\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"std\")))]\n/// Helper trait to show a byte slice as a hex dump\npub trait HexDisplay {\n /// Converts the value of `self` to a hex dump, returning the owned\n /// `String`.\n fn to_hex(&self, chunk_size: usize) -> String;\n\n /// Converts the value of `self` to a hex dump beginning at `from` address, returning the owned\n /// `String`.\n fn to_hex_from(&self, chunk_size: usize, from: usize) -> String;\n}\n\n#[cfg(feature = \"std\")]\nstatic CHARS: &[u8] = b\"0123456789abcdef\";\n\n#[cfg(feature = \"std\")]\nimpl HexDisplay for [u8] {\n #[allow(unused_variables)]\n fn to_hex(&self, chunk_size: usize) -> String {\n self.to_hex_from(chunk_size, 0)\n }\n\n #[allow(unused_variables)]\n fn to_hex_from(&self, chunk_size: usize, from: usize) -> String {\n let mut v = Vec::with_capacity(self.len() * 3);\n let mut i = from;\n for chunk in self.chunks(chunk_size) {\n let s = format!(\"{:08x}\", i);\n for &ch in s.as_bytes().iter() {\n v.push(ch);\n }\n v.push(b'\\t');\n\n i += chunk_size;\n\n for &byte in chunk {\n v.push(CHARS[(byte >> 4) as usize]);\n v.push(CHARS[(byte & 0xf) as usize]);\n v.push(b' ');\n }\n if chunk_size > chunk.len() {\n for j in 0..(chunk_size - chunk.len()) {\n v.push(b' ');\n v.push(b' ');\n v.push(b' ');\n }\n }\n v.push(b'\\t');\n\n for &byte in chunk {\n if matches!(byte, 32..=126 | 128..=255) {\n v.push(byte);\n } else {\n v.push(b'.');\n }\n }\n v.push(b'\\n');\n }\n\n String::from_utf8_lossy(&v[..]).into_owned()\n }\n}\n\n#[cfg(feature = \"std\")]\nimpl HexDisplay for str {\n #[allow(unused_variables)]\n fn to_hex(&self, chunk_size: usize) -> String {\n self.to_hex_from(chunk_size, 0)\n }\n\n #[allow(unused_variables)]\n fn to_hex_from(&self, chunk_size: usize, from: usize) -> String {\n self.as_bytes().to_hex_from(chunk_size, from)\n }\n}\n\n/// A saturating iterator for usize.\npub struct SaturatingIterator {\n count: usize,\n}\n\nimpl Iterator for SaturatingIterator {\n type Item = usize;\n\n fn next(&mut self) -> Option {\n let old_count = self.count;\n self.count = self.count.saturating_add(1);\n Some(old_count)\n }\n}\n\n/// Abstractions for range-like types.\npub trait NomRange {\n /// The saturating iterator type.\n type Saturating: Iterator;\n /// The bounded iterator type.\n type Bounded: Iterator;\n\n /// `true` if `item` is contained in the range.\n fn contains(&self, item: &Idx) -> bool;\n\n /// Returns the bounds of this range.\n fn bounds(&self) -> (Bound, Bound);\n\n /// `true` if the range is inverted.\n fn is_inverted(&self) -> bool;\n\n /// Creates a saturating iterator.\n /// A saturating iterator counts the number of iterations starting from 0 up to the upper bound of this range.\n /// If the upper bound is infinite the iterator saturates at the largest representable value of its type and\n /// returns it for all further elements.\n fn saturating_iter(&self) -> Self::Saturating;\n\n /// Creates a bounded iterator.\n /// A bounded iterator counts the number of iterations starting from 0 up to the upper bound of this range.\n /// If the upper bounds is infinite the iterator counts up until the amount of iterations has reached the\n /// largest representable value of its type and then returns `None` for all further elements.\n fn bounded_iter(&self) -> Self::Bounded;\n}\n\nimpl NomRange for Range {\n type Saturating = Range;\n type Bounded = Range;\n\n fn bounds(&self) -> (Bound, Bound) {\n (Bound::Included(self.start), Bound::Excluded(self.end))\n }\n\n fn contains(&self, item: &usize) -> bool {\n RangeBounds::contains(self, item)\n }\n\n fn is_inverted(&self) -> bool {\n self.start >= self.end\n }\n\n fn saturating_iter(&self) -> Self::Saturating {\n if self.end == 0 {\n Range::default()\n } else {\n 0..self.end - 1\n }\n }\n\n fn bounded_iter(&self) -> Self::Bounded {\n if self.end == 0 {\n Range::default()\n } else {\n 0..self.end - 1\n }\n }\n}\n\nimpl NomRange for RangeInclusive {\n type Saturating = Range;\n type Bounded = Range;\n\n fn bounds(&self) -> (Bound, Bound) {\n (Bound::Included(*self.start()), Bound::Included(*self.end()))\n }\n\n fn contains(&self, item: &usize) -> bool {\n RangeBounds::contains(self, item)\n }\n\n fn is_inverted(&self) -> bool {\n !RangeInclusive::contains(self, self.start())\n }\n\n fn saturating_iter(&self) -> Self::Saturating {\n 0..*self.end()\n }\n\n fn bounded_iter(&self) -> Self::Bounded {\n 0..*self.end()\n }\n}\n\nimpl NomRange for RangeFrom {\n type Saturating = SaturatingIterator;\n type Bounded = Range;\n\n fn bounds(&self) -> (Bound, Bound) {\n (Bound::Included(self.start), Bound::Unbounded)\n }\n\n fn contains(&self, item: &usize) -> bool {\n RangeBounds::contains(self, item)\n }\n\n fn is_inverted(&self) -> bool {\n false\n }\n\n fn saturating_iter(&self) -> Self::Saturating {\n SaturatingIterator { count: 0 }\n }\n\n fn bounded_iter(&self) -> Self::Bounded {\n 0..usize::MAX\n }\n}\n\nimpl NomRange for RangeTo {\n type Saturating = Range;\n type Bounded = Range;\n\n fn bounds(&self) -> (Bound, Bound) {\n (Bound::Unbounded, Bound::Excluded(self.end))\n }\n\n fn contains(&self, item: &usize) -> bool {\n RangeBounds::contains(self, item)\n }\n\n fn is_inverted(&self) -> bool {\n false\n }\n\n fn saturating_iter(&self) -> Self::Saturating {\n if self.end == 0 {\n Range::default()\n } else {\n 0..self.end - 1\n }\n }\n\n fn bounded_iter(&self) -> Self::Bounded {\n if self.end == 0 {\n Range::default()\n } else {\n 0..self.end - 1\n }\n }\n}\n\nimpl NomRange for RangeToInclusive {\n type Saturating = Range;\n type Bounded = Range;\n\n fn bounds(&self) -> (Bound, Bound) {\n (Bound::Unbounded, Bound::Included(self.end))\n }\n\n fn contains(&self, item: &usize) -> bool {\n RangeBounds::contains(self, item)\n }\n\n fn is_inverted(&self) -> bool {\n false\n }\n\n fn saturating_iter(&self) -> Self::Saturating {\n 0..self.end\n }\n\n fn bounded_iter(&self) -> Self::Bounded {\n 0..self.end\n }\n}\n\nimpl NomRange for RangeFull {\n type Saturating = SaturatingIterator;\n type Bounded = Range;\n\n fn bounds(&self) -> (Bound, Bound) {\n (Bound::Unbounded, Bound::Unbounded)\n }\n\n fn contains(&self, item: &usize) -> bool {\n RangeBounds::contains(self, item)\n }\n\n fn is_inverted(&self) -> bool {\n false\n }\n\n fn saturating_iter(&self) -> Self::Saturating {\n SaturatingIterator { count: 0 }\n }\n\n fn bounded_iter(&self) -> Self::Bounded {\n 0..usize::MAX\n }\n}\n\nimpl NomRange for usize {\n type Saturating = Range;\n type Bounded = Range;\n\n fn bounds(&self) -> (Bound, Bound) {\n (Bound::Included(*self), Bound::Included(*self))\n }\n\n fn contains(&self, item: &usize) -> bool {\n self == item\n }\n\n fn is_inverted(&self) -> bool {\n false\n }\n\n fn saturating_iter(&self) -> Self::Saturating {\n 0..*self\n }\n\n fn bounded_iter(&self) -> Self::Bounded {\n 0..*self\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_offset_u8() {\n let s = b\"abcd123\";\n let a = &s[..];\n let b = &a[2..];\n let c = &a[..4];\n let d = &a[3..5];\n assert_eq!(a.offset(b), 2);\n assert_eq!(a.offset(c), 0);\n assert_eq!(a.offset(d), 3);\n }\n\n #[test]\n fn test_offset_str() {\n let a = \"abc\u0159\u00e8\u00c2\u00df\u00c7d123\";\n let b = &a[7..];\n let c = &a[..5];\n let d = &a[5..9];\n assert_eq!(a.offset(b), 7);\n assert_eq!(a.offset(c), 0);\n assert_eq!(a.offset(d), 5);\n }\n\n #[test]\n fn test_slice_index() {\n let a = \"abc\u0159\u00e8\u00c2\u00df\u00c7d123\";\n assert_eq!(a.slice_index(0), Ok(0));\n assert_eq!(a.slice_index(2), Ok(2));\n }\n\n #[test]\n fn test_slice_index_utf8() {\n let a = \"a\u00a1\u20ac\ud83d\udca2\u20ac\u00a1a\";\n\n for (c, len) in a.chars().zip([1, 2, 3, 4, 3, 2, 1]) {\n assert_eq!(c.len(), len);\n }\n\n assert_eq!(a.slice_index(0), Ok(0));\n assert_eq!(a.slice_index(1), Ok(1));\n assert_eq!(a.slice_index(2), Ok(3));\n assert_eq!(a.slice_index(3), Ok(6));\n assert_eq!(a.slice_index(4), Ok(10));\n assert_eq!(a.slice_index(5), Ok(13));\n assert_eq!(a.slice_index(6), Ok(15));\n assert_eq!(a.slice_index(7), Ok(16));\n\n assert!(a.slice_index(8).is_err());\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "mod.rs", "content": "#[cfg(test)]\nmod tests;\n\nuse core::marker::PhantomData;\n\nuse crate::error::ErrorKind;\nuse crate::error::ParseError;\nuse crate::internal::{Err, Mode, Parser};\n\n/// Tests a list of parsers one by one until one succeeds.\n///\n/// It takes as argument either a tuple or an array of parsers. If using a\n/// tuple, there is a maximum of 21 parsers. If you need more, it is possible to\n/// use an array.\n///\n/// ```rust\n/// # use nom::error_position;\n/// # use nom::{Err,error::ErrorKind, Needed, IResult, Parser};\n/// use nom::character::complete::{alpha1, digit1};\n/// use nom::branch::alt;\n/// # fn main() {\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// alt((alpha1, digit1)).parse(input)\n/// };\n///\n/// // the first parser, alpha1, recognizes the input\n/// assert_eq!(parser(\"abc\"), Ok((\"\", \"abc\")));\n///\n/// // the first parser returns an error, so alt tries the second one\n/// assert_eq!(parser(\"123456\"), Ok((\"\", \"123456\")));\n///\n/// // both parsers failed, and with the default error type, alt will return the last error\n/// assert_eq!(parser(\" \"), Err(Err::Error(error_position!(\" \", ErrorKind::Digit))));\n/// # }\n/// ```\n///\n/// With a custom error type, it is possible to have alt return the error of the parser\n/// that went the farthest in the input data\npub fn alt(l: List) -> Choice {\n Choice { parser: l }\n}\n\n/// Applies a list of parsers in any order.\n///\n/// Permutation will succeed if all of the child parsers succeeded.\n/// It takes as argument a tuple of parsers, and returns a\n/// tuple of the parser results.\n///\n/// ```rust\n/// # use nom::{Err,error::{Error, ErrorKind}, Needed, IResult, Parser};\n/// use nom::character::complete::{alpha1, digit1};\n/// use nom::branch::permutation;\n/// # fn main() {\n/// fn parser(input: &str) -> IResult<&str, (&str, &str)> {\n/// permutation((alpha1, digit1)).parse(input)\n/// }\n///\n/// // permutation recognizes alphabetic characters then digit\n/// assert_eq!(parser(\"abc123\"), Ok((\"\", (\"abc\", \"123\"))));\n///\n/// // but also in inverse order\n/// assert_eq!(parser(\"123abc\"), Ok((\"\", (\"abc\", \"123\"))));\n///\n/// // it will fail if one of the parsers failed\n/// assert_eq!(parser(\"abc;\"), Err(Err::Error(Error::new(\";\", ErrorKind::Digit))));\n/// # }\n/// ```\n///\n/// The parsers are applied greedily: if there are multiple unapplied parsers\n/// that could parse the next slice of input, the first one is used.\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Parser};\n/// use nom::branch::permutation;\n/// use nom::character::complete::{anychar, char};\n///\n/// fn parser(input: &str) -> IResult<&str, (char, char)> {\n/// permutation((anychar, char('a'))).parse(input)\n/// }\n///\n/// // anychar parses 'b', then char('a') parses 'a'\n/// assert_eq!(parser(\"ba\"), Ok((\"\", ('b', 'a'))));\n///\n/// // anychar parses 'a', then char('a') fails on 'b',\n/// // even though char('a') followed by anychar would succeed\n/// assert_eq!(parser(\"ab\"), Err(Err::Error(Error::new(\"b\", ErrorKind::Char))));\n/// ```\n///\npub fn permutation, List>(list: List) -> Permutation {\n Permutation {\n parser: list,\n e: PhantomData,\n }\n}\n\nmacro_rules! alt_trait(\n ($first:ident $second:ident $($id: ident)+) => (\n alt_trait!(__impl $first $second; $($id)+);\n );\n (__impl $($current:ident)*; $head:ident $($id: ident)+) => (\n alt_trait_impl!($($current)*);\n\n alt_trait!(__impl $($current)* $head; $($id)+);\n );\n (__impl $($current:ident)*; $head:ident) => (\n alt_trait_impl!($($current)*);\n alt_trait_impl!($($current)* $head);\n );\n);\n\n/// Wrapping structure for the [alt()] combinator implementation\npub struct Choice {\n parser: T,\n}\n\nmacro_rules! alt_trait_impl(\n ($($id:ident)+) => (\n impl<\n Input: Clone, Output, Error: ParseError,\n $($id: Parser),+\n > Parser for Choice< ( $($id),+ )> {\n type Output = Output;\n type Error = Error;\n\n #[inline(always)]\n fn process(\n &mut self,\n input: Input,\n ) -> crate::PResult {\n match self.parser.0.process::(input.clone()) {\n Ok(res) => Ok(res),\n Err(Err::Failure(e))=> Err(Err::Failure(e)),\n Err(Err::Incomplete(i))=> Err(Err::Incomplete(i)),\n Err(Err::Error(e)) => alt_trait_inner!(1, self, input, e, $($id)+),\n }\n }\n }\n );\n);\n\nmacro_rules! alt_trait_inner(\n ($it:tt, $self:expr, $input:expr, $err:expr, $head:ident $($id:ident)+) => (\n match $self.parser.$it.process::($input.clone()) {\n Ok(res) => Ok(res),\n Err(Err::Failure(e))=>Err(Err::Failure(e)),\n Err(Err::Incomplete(i))=> Err(Err::Incomplete(i)),\n Err(Err::Error(e)) => {\n succ!($it, alt_trait_inner!($self, $input, ::combine($err, e, |e1, e2| e1.or(e2)), $($id)+))\n }\n }\n );\n ($it:tt, $self:expr, $input:expr, $err:expr, $head:ident) => (\n Err(Err::Error(::map($err, |err| Error::append($input, ErrorKind::Alt, err))))\n );\n);\n\nalt_trait!(A B C D E F G H I J K L M N O P Q R S T U);\n\n// Manually implement Alt for (A,), the 1-tuple type\nimpl, A: Parser>\n Parser for Choice<(A,)>\n{\n type Output = Output;\n type Error = Error;\n\n #[inline]\n fn process(\n &mut self,\n input: Input,\n ) -> crate::PResult {\n self.parser.0.process::(input)\n }\n}\n\nimpl<\n const N: usize,\n Input: Clone,\n Output,\n Error: ParseError,\n A: Parser,\n > Parser for Choice<[A; N]>\n{\n type Output = Output;\n type Error = Error;\n\n #[inline]\n fn process(\n &mut self,\n input: Input,\n ) -> crate::PResult {\n let mut error = None;\n\n for branch in &mut self.parser {\n match branch.process::(input.clone()) {\n Err(Err::Error(e)) => match error {\n None => error = Some(e),\n Some(err) => error = Some(OM::Error::combine(err, e, |e1, e2| e1.or(e2))),\n },\n res => return res,\n }\n }\n\n match error {\n Some(e) => Err(Err::Error(OM::Error::map(e, |err| {\n Error::append(input, ErrorKind::Alt, err)\n }))),\n None => Err(Err::Error(OM::Error::bind(|| {\n Error::from_error_kind(input, ErrorKind::Alt)\n }))),\n }\n }\n}\n\nimpl<\n Input: Clone,\n Output,\n Error: ParseError,\n A: Parser,\n > Parser for Choice<&mut [A]>\n{\n type Output = Output;\n type Error = Error;\n\n #[inline]\n fn process(\n &mut self,\n input: Input,\n ) -> crate::PResult {\n let mut error = None;\n\n for branch in self.parser.iter_mut() {\n match branch.process::(input.clone()) {\n Err(Err::Error(e)) => match error {\n None => error = Some(e),\n Some(err) => error = Some(OM::Error::combine(err, e, |e1, e2| e1.or(e2))),\n },\n res => return res,\n }\n }\n\n match error {\n Some(e) => Err(Err::Error(OM::Error::map(e, |err| {\n Error::append(input, ErrorKind::Alt, err)\n }))),\n None => Err(Err::Error(OM::Error::bind(|| {\n Error::from_error_kind(input, ErrorKind::Alt)\n }))),\n }\n }\n}\n\nmacro_rules! permutation_trait(\n (\n $name1:ident $ty1:ident $item1:ident\n $name2:ident $ty2:ident $item2:ident\n $($name3:ident $ty3:ident $item3:ident)*\n ) => (\n permutation_trait!(__impl $name1 $ty1 $item1, $name2 $ty2 $item2; $($name3 $ty3 $item3)*);\n );\n (\n __impl $($name:ident $ty:ident $item:ident),+;\n $name1:ident $ty1:ident $item1:ident $($name2:ident $ty2:ident $item2:ident)*\n ) => (\n permutation_trait_impl!($($name $ty $item),+);\n permutation_trait!(__impl $($name $ty $item),+ , $name1 $ty1 $item1; $($name2 $ty2 $item2)*);\n );\n (__impl $($name:ident $ty:ident $item:ident),+;) => (\n permutation_trait_impl!($($name $ty $item),+);\n );\n);\n\n/// Wrapping structure for the [permutation] combinator implementation\npub struct Permutation {\n parser: T,\n e: PhantomData,\n}\n\nmacro_rules! permutation_trait_impl(\n ($($name:ident $ty:ident $item:ident),+) => (\n impl<\n Input, Error, $($ty),+ , $($name),+\n > Parser for Permutation< ( $($name),+ ), Error>\n where\n Input: Clone,\n Error: ParseError,\n $($name: Parser),+\n {\n type Output = ( $($ty),+ );\n type Error = Error;\n\n #[inline(always)]\n fn process(\n &mut self,\n mut input: Input,\n ) -> crate::PResult {\n let mut res = OM::Output::bind(|| ($(Option::<$ty>::None),+));\n $(let mut $item = false;)+\n\n loop {\n let mut err: Option<::Output> = None;\n permutation_trait_inner!(0, self, input, res, err, $($item)+);\n\n // If we reach here, every iterator has either been applied before,\n // or errored on the remaining input\n if let Some(err) = err {\n // There are remaining parsers, and all errored on the remaining input\n return Err(Err::Error(OM::Error::map(err, |err| Error::append(input, ErrorKind::Permutation, err))));\n }\n\n return Ok((input,OM::Output::map(res, |res| {\n // All parsers were applied\n match res {\n ($(Some($item)),+) => ($($item),+),\n _ => unreachable!(),\n }\n })))\n }\n }\n\n }\n );\n);\n\nmacro_rules! permutation_trait_inner(\n ($it:tt, $self:expr, $input:ident, $res:expr, $err:expr, $head:ident $($item:ident)*) => (\n if !$head {\n\n match $self.parser.$it.process::($input.clone()) {\n Ok((i, o)) => {\n $input = i;\n $res = OM::Output::combine($res, o, |mut res, o | {res.$it = Some(o);res });\n $head = true;\n continue;\n }\n Err(Err::Error(e)) => {\n $err = Some(match $err {\n None => e,\n Some(err) => OM::Error::combine(err, e, |err, e| err.or(e))\n });\n }\n Err(e) => return Err(e),\n };\n }\n succ!($it, permutation_trait_inner!($self, $input, $res, $err, $($item)*));\n );\n ($it:tt, $self:expr, $input:ident, $res:expr, $err:expr,) => ();\n);\n\npermutation_trait!(\n FnA A a\n FnB B b\n FnC C c\n FnD D d\n FnE E e\n FnF F f\n FnG G g\n FnH H h\n FnI I i\n FnJ J j\n FnK K k\n FnL L l\n FnM M m\n FnN N n\n FnO O o\n FnP P p\n FnQ Q q\n FnR R r\n FnS S s\n FnT T t\n FnU U u\n);"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "mod.rs", "content": "pub mod complete;\npub mod streaming;\n#[cfg(test)]\nmod tests;\n\nuse core::marker::PhantomData;\n\nuse crate::error::ErrorKind;\nuse crate::error::ParseError;\nuse crate::internal::{Err, Needed, Parser};\nuse crate::lib::std::result::Result::*;\nuse crate::traits::{Compare, CompareResult};\nuse crate::AsChar;\nuse crate::Check;\nuse crate::ExtendInto;\nuse crate::FindSubstring;\nuse crate::FindToken;\nuse crate::Input;\nuse crate::IsStreaming;\nuse crate::Mode;\nuse crate::OutputM;\nuse crate::OutputMode;\nuse crate::ToUsize;\n\n/// Recognizes a pattern.\n///\n/// The input data will be compared to the tag combinator's argument and will return the part of\n/// the input that matches the argument.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::streaming::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, &str> {\n/// tag(\"Hello\")(s)\n/// }\n///\n/// assert_eq!(parser(\"Hello, World!\"), Ok((\", World!\", \"Hello\")));\n/// assert_eq!(parser(\"Something\"), Err(Err::Error(Error::new(\"Something\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"S\"), Err(Err::Error(Error::new(\"S\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"H\"), Err(Err::Incomplete(Needed::new(4))));\n/// ```\npub fn tag>(tag: T) -> impl Parser\nwhere\n I: Input + Compare,\n T: Input + Clone,\n{\n Tag {\n tag,\n e: PhantomData,\n }\n}\n\n/// Tag implementation\npub struct Tag {\n tag: T,\n e: PhantomData,\n}\n\nimpl, T> Parser for Tag\nwhere\n I: Input + Compare,\n T: Input + Clone,\n{\n type Output = I;\n\n type Error = Error;\n\n fn process(&mut self, i: I) -> crate::PResult {\n let tag_len = self.tag.input_len();\n let t = self.tag.clone();\n\n match i.compare(t) {\n CompareResult::Ok => Ok((i.take_from(tag_len), OM::Output::bind(|| i.take(tag_len)))),\n CompareResult::Incomplete => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::new(tag_len - i.input_len())))\n } else {\n Err(Err::Error(OM::Error::bind(|| {\n let e: ErrorKind = ErrorKind::Tag;\n Error::from_error_kind(i, e)\n })))\n }\n }\n CompareResult::Error => Err(Err::Error(OM::Error::bind(|| {\n let e: ErrorKind = ErrorKind::Tag;\n Error::from_error_kind(i, e)\n }))),\n }\n }\n}\n\n/// Recognizes a case insensitive pattern.\n///\n/// The input data will be compared to the tag combinator's argument and will return the part of\n/// the input that matches the argument with no regard to case.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::streaming::tag_no_case;\n///\n/// fn parser(s: &str) -> IResult<&str, &str> {\n/// tag_no_case(\"hello\")(s)\n/// }\n///\n/// assert_eq!(parser(\"Hello, World!\"), Ok((\", World!\", \"Hello\")));\n/// assert_eq!(parser(\"hello, World!\"), Ok((\", World!\", \"hello\")));\n/// assert_eq!(parser(\"HeLlO, World!\"), Ok((\", World!\", \"HeLlO\")));\n/// assert_eq!(parser(\"Something\"), Err(Err::Error(Error::new(\"Something\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"\"), Err(Err::Incomplete(Needed::new(5))));\n/// ```\npub fn tag_no_case>(tag: T) -> impl Parser\nwhere\n I: Input + Compare,\n T: Input + Clone,\n{\n TagNoCase {\n tag,\n e: PhantomData,\n }\n}\n\n/// Case insensitive Tag implementation\npub struct TagNoCase {\n tag: T,\n e: PhantomData,\n}\n\nimpl, T> Parser for TagNoCase\nwhere\n I: Input + Compare,\n T: Input + Clone,\n{\n type Output = I;\n\n type Error = Error;\n\n fn process(&mut self, i: I) -> crate::PResult {\n let tag_len = self.tag.input_len();\n let t = self.tag.clone();\n\n match i.compare_no_case(t) {\n CompareResult::Ok => Ok((i.take_from(tag_len), OM::Output::bind(|| i.take(tag_len)))),\n CompareResult::Incomplete => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::new(tag_len - i.input_len())))\n } else {\n Err(Err::Error(OM::Error::bind(|| {\n let e: ErrorKind = ErrorKind::Tag;\n Error::from_error_kind(i, e)\n })))\n }\n }\n CompareResult::Error => Err(Err::Error(OM::Error::bind(|| {\n let e: ErrorKind = ErrorKind::Tag;\n Error::from_error_kind(i, e)\n }))),\n }\n }\n}\n\n/// Parser wrapper for `split_at_position`\npub struct SplitPosition {\n predicate: F,\n error: PhantomData,\n}\n\nimpl, F> Parser for SplitPosition\nwhere\n I: Input,\n F: Fn(::Item) -> bool,\n{\n type Output = I;\n\n type Error = Error;\n\n #[inline(always)]\n fn process(&mut self, i: I) -> crate::PResult {\n i.split_at_position_mode::(|c| (self.predicate)(c))\n }\n}\n\n/// Parser wrapper for `split_at_position1`\npub struct SplitPosition1 {\n e: ErrorKind,\n predicate: F,\n error: PhantomData,\n}\n\nimpl, F> Parser for SplitPosition1\nwhere\n I: Input,\n F: Fn(::Item) -> bool,\n{\n type Output = I;\n\n type Error = Error;\n\n #[inline(always)]\n fn process(&mut self, i: I) -> crate::PResult {\n i.split_at_position_mode1::(|c| (self.predicate)(c), self.e)\n }\n}\n\n/// Parse till certain characters are met.\n///\n/// The parser will return the longest slice till one of the characters of the combinator's argument are met.\n///\n/// It doesn't consume the matched character.\n///\n/// It will return a `Err::Error((\"\", ErrorKind::IsNot))` if the pattern wasn't met.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::complete::is_not;\n///\n/// fn not_space(s: &str) -> IResult<&str, &str> {\n/// is_not(\" \\t\\r\\n\")(s)\n/// }\n///\n/// assert_eq!(not_space(\"Hello, World!\"), Ok((\" World!\", \"Hello,\")));\n/// assert_eq!(not_space(\"Sometimes\\t\"), Ok((\"\\t\", \"Sometimes\")));\n/// assert_eq!(not_space(\"Nospace\"), Ok((\"\", \"Nospace\")));\n/// assert_eq!(not_space(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::IsNot))));\n/// ```\npub fn is_not>(arr: T) -> impl Parser\nwhere\n I: Input,\n T: FindToken<::Item>,\n{\n SplitPosition1 {\n e: ErrorKind::IsNot,\n predicate: move |c| arr.find_token(c),\n error: PhantomData,\n }\n}\n\n/// Returns the longest input slice (at least 1) that matches the pattern.\n///\n/// The parser will return the longest slice consisting of the characters in provided in the\n/// combinator's argument.\n///\n/// It will return a `Err(Err::Error((_, ErrorKind::IsA)))` if the pattern wasn't met.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::complete::is_a;\n///\n/// fn hex(s: &str) -> IResult<&str, &str> {\n/// is_a(\"1234567890ABCDEF\")(s)\n/// }\n///\n/// assert_eq!(hex(\"123 and voila\"), Ok((\" and voila\", \"123\")));\n/// assert_eq!(hex(\"DEADBEEF and others\"), Ok((\" and others\", \"DEADBEEF\")));\n/// assert_eq!(hex(\"BADBABEsomething\"), Ok((\"something\", \"BADBABE\")));\n/// assert_eq!(hex(\"D15EA5E\"), Ok((\"\", \"D15EA5E\")));\n/// assert_eq!(hex(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::IsA))));\n/// ```\npub fn is_a>(arr: T) -> impl Parser\nwhere\n I: Input,\n T: FindToken<::Item>,\n{\n SplitPosition1 {\n e: ErrorKind::IsA,\n predicate: move |c| !arr.find_token(c),\n error: PhantomData,\n }\n}\n\n/// Returns the longest input slice (if any) that matches the predicate.\n///\n/// The parser will return the longest slice that matches the given predicate *(a function that\n/// takes the input and returns a bool)*.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, IResult};\n/// use nom::bytes::complete::take_while;\n/// use nom::AsChar;\n///\n/// fn alpha(s: &[u8]) -> IResult<&[u8], &[u8]> {\n/// take_while(AsChar::is_alpha)(s)\n/// }\n///\n/// assert_eq!(alpha(b\"latin123\"), Ok((&b\"123\"[..], &b\"latin\"[..])));\n/// assert_eq!(alpha(b\"12345\"), Ok((&b\"12345\"[..], &b\"\"[..])));\n/// assert_eq!(alpha(b\"latin\"), Ok((&b\"\"[..], &b\"latin\"[..])));\n/// assert_eq!(alpha(b\"\"), Ok((&b\"\"[..], &b\"\"[..])));\n/// ```\npub fn take_while>(cond: F) -> impl Parser\nwhere\n I: Input,\n F: Fn(::Item) -> bool,\n{\n SplitPosition {\n predicate: move |c| !cond(c),\n error: PhantomData,\n }\n}\n\n/// Returns the longest (at least 1) input slice that matches the predicate.\n///\n/// The parser will return the longest slice that matches the given predicate *(a function that\n/// takes the input and returns a bool)*.\n///\n/// It will return an `Err(Err::Error((_, ErrorKind::TakeWhile1)))` if the pattern wasn't met.\n///\n/// # Streaming Specific\n/// *Streaming version* will return a `Err::Incomplete(Needed::new(1))` or if the pattern reaches the end of the input.\n///\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::streaming::take_while1;\n/// use nom::AsChar;\n///\n/// fn alpha(s: &[u8]) -> IResult<&[u8], &[u8]> {\n/// take_while1(AsChar::is_alpha)(s)\n/// }\n///\n/// assert_eq!(alpha(b\"latin123\"), Ok((&b\"123\"[..], &b\"latin\"[..])));\n/// assert_eq!(alpha(b\"latin\"), Err(Err::Incomplete(Needed::new(1))));\n/// assert_eq!(alpha(b\"12345\"), Err(Err::Error(Error::new(&b\"12345\"[..], ErrorKind::TakeWhile1))));\n/// ```\npub fn take_while1>(cond: F) -> impl Parser\nwhere\n I: Input,\n F: Fn(::Item) -> bool,\n{\n SplitPosition1 {\n e: ErrorKind::TakeWhile1,\n predicate: move |c| !cond(c),\n error: PhantomData,\n }\n}\n\n/// Returns the longest (m <= len <= n) input slice that matches the predicate.\n///\n/// The parser will return the longest slice that matches the given predicate *(a function that\n/// takes the input and returns a bool)*.\n///\n/// It will return an `Err::Error((_, ErrorKind::TakeWhileMN))` if the pattern wasn't met.\n/// # Streaming Specific\n/// *Streaming version* will return a `Err::Incomplete(Needed::new(1))` if the pattern reaches the end of the input or is too short.\n///\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::streaming::take_while_m_n;\n/// use nom::AsChar;\n///\n/// fn short_alpha(s: &[u8]) -> IResult<&[u8], &[u8]> {\n/// take_while_m_n(3, 6, AsChar::is_alpha)(s)\n/// }\n///\n/// assert_eq!(short_alpha(b\"latin123\"), Ok((&b\"123\"[..], &b\"latin\"[..])));\n/// assert_eq!(short_alpha(b\"lengthy\"), Ok((&b\"y\"[..], &b\"length\"[..])));\n/// assert_eq!(short_alpha(b\"latin\"), Err(Err::Incomplete(Needed::new(1))));\n/// assert_eq!(short_alpha(b\"ed\"), Err(Err::Incomplete(Needed::new(1))));\n/// assert_eq!(short_alpha(b\"12345\"), Err(Err::Error(Error::new(&b\"12345\"[..], ErrorKind::TakeWhileMN))));\n/// ```\npub fn take_while_m_n>(\n m: usize,\n n: usize,\n predicate: F,\n) -> impl Parser\nwhere\n I: Input,\n F: Fn(::Item) -> bool,\n{\n TakeWhileMN {\n m,\n n,\n predicate,\n e: PhantomData,\n }\n}\n\n/// Parser implementation for [take_while_m_n]\npub struct TakeWhileMN {\n m: usize,\n n: usize,\n predicate: F,\n e: PhantomData,\n}\n\nimpl, F> Parser for TakeWhileMN\nwhere\n I: Input,\n F: Fn(::Item) -> bool,\n{\n type Output = I;\n type Error = Error;\n\n fn process(\n &mut self,\n input: I,\n ) -> crate::PResult {\n let mut count = 0;\n for (i, (index, item)) in input.iter_indices().enumerate() {\n if i == self.n {\n return Ok((\n input.take_from(index),\n OM::Output::bind(|| input.take(index)),\n ));\n }\n\n if !(self.predicate)(item) {\n if i >= self.m {\n return Ok((\n input.take_from(index),\n OM::Output::bind(|| input.take(index)),\n ));\n } else {\n return Err(Err::Error(OM::Error::bind(|| {\n Error::from_error_kind(input, ErrorKind::TakeWhileMN)\n })));\n }\n }\n count += 1;\n }\n\n let input_len = input.input_len();\n if OM::Incomplete::is_streaming() {\n let needed = if self.m > input_len {\n self.m - input_len\n } else {\n 1\n };\n Err(Err::Incomplete(Needed::new(needed)))\n } else if count >= self.m {\n Ok((\n input.take_from(input_len),\n OM::Output::bind(|| input.take(input_len)),\n ))\n } else {\n Err(Err::Error(OM::Error::bind(|| {\n Error::from_error_kind(input, ErrorKind::TakeWhileMN)\n })))\n }\n }\n}\n\n/// Returns the longest input slice (if any) till a predicate is met.\n///\n/// The parser will return the longest slice till the given predicate *(a function that\n/// takes the input and returns a bool)*.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, IResult};\n/// use nom::bytes::complete::take_till;\n///\n/// fn till_colon(s: &str) -> IResult<&str, &str> {\n/// take_till(|c| c == ':')(s)\n/// }\n///\n/// assert_eq!(till_colon(\"latin:123\"), Ok((\":123\", \"latin\")));\n/// assert_eq!(till_colon(\":empty matched\"), Ok((\":empty matched\", \"\"))); //allowed\n/// assert_eq!(till_colon(\"12345\"), Ok((\"\", \"12345\")));\n/// assert_eq!(till_colon(\"\"), Ok((\"\", \"\")));\n/// ```\n#[allow(clippy::redundant_closure)]\npub fn take_till>(cond: F) -> impl Parser\nwhere\n I: Input,\n F: Fn(::Item) -> bool,\n{\n SplitPosition {\n predicate: cond,\n error: PhantomData,\n }\n}\n\n/// Returns the longest (at least 1) input slice till a predicate is met.\n///\n/// The parser will return the longest slice till the given predicate *(a function that\n/// takes the input and returns a bool)*.\n///\n/// # Streaming Specific\n/// *Streaming version* will return a `Err::Incomplete(Needed::new(1))` if the match reaches the\n/// end of input or if there was not match.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::streaming::take_till1;\n///\n/// fn till_colon(s: &str) -> IResult<&str, &str> {\n/// take_till1(|c| c == ':')(s)\n/// }\n///\n/// assert_eq!(till_colon(\"latin:123\"), Ok((\":123\", \"latin\")));\n/// assert_eq!(till_colon(\":empty matched\"), Err(Err::Error(Error::new(\":empty matched\", ErrorKind::TakeTill1))));\n/// assert_eq!(till_colon(\"12345\"), Err(Err::Incomplete(Needed::new(1))));\n/// assert_eq!(till_colon(\"\"), Err(Err::Incomplete(Needed::new(1))));\n/// ```\n#[allow(clippy::redundant_closure)]\npub fn take_till1>(cond: F) -> impl Parser\nwhere\n I: Input,\n F: Fn(::Item) -> bool,\n{\n SplitPosition1 {\n e: ErrorKind::TakeTill1,\n predicate: cond,\n error: PhantomData,\n }\n}\n\n/// Returns an input slice containing the first N input elements (Input[..N]).\n///\n/// # Streaming Specific\n/// *Streaming version* if the input has less than N elements, `take` will\n/// return a `Err::Incomplete(Needed::new(M))` where M is the number of\n/// additional bytes the parser would need to succeed.\n/// It is well defined for `&[u8]` as the number of elements is the byte size,\n/// but for types like `&str`, we cannot know how many bytes correspond for\n/// the next few chars, so the result will be `Err::Incomplete(Needed::Unknown)`\n///\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, IResult};\n/// use nom::bytes::streaming::take;\n///\n/// fn take6(s: &str) -> IResult<&str, &str> {\n/// take(6usize)(s)\n/// }\n///\n/// assert_eq!(take6(\"1234567\"), Ok((\"7\", \"123456\")));\n/// assert_eq!(take6(\"things\"), Ok((\"\", \"things\")));\n/// assert_eq!(take6(\"short\"), Err(Err::Incomplete(Needed::Unknown)));\n/// ```\npub fn take>(count: C) -> impl Parser\nwhere\n I: Input,\n C: ToUsize,\n{\n Take {\n length: count.to_usize(),\n e: PhantomData,\n }\n}\n\n/// Parser implementation for [take]\npub struct Take {\n length: usize,\n e: PhantomData,\n}\n\nimpl> Parser for Take\nwhere\n I: Input,\n{\n type Output = I;\n type Error = Error;\n\n fn process(&mut self, i: I) -> crate::PResult {\n match i.slice_index(self.length) {\n Err(needed) => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(needed))\n } else {\n Err(Err::Error(OM::Error::bind(|| {\n let e: ErrorKind = ErrorKind::Eof;\n Error::from_error_kind(i, e)\n })))\n }\n }\n Ok(index) => Ok((i.take_from(index), OM::Output::bind(|| i.take(index)))),\n }\n }\n}\n\n/// Returns the input slice up to the first occurrence of the pattern.\n///\n/// It doesn't consume the pattern.\n///\n/// # Streaming Specific\n/// *Streaming version* will return a `Err::Incomplete(Needed::new(N))` if the input doesn't\n/// contain the pattern or if the input is smaller than the pattern.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, IResult};\n/// use nom::bytes::streaming::take_until;\n///\n/// fn until_eof(s: &str) -> IResult<&str, &str> {\n/// take_until(\"eof\")(s)\n/// }\n///\n/// assert_eq!(until_eof(\"hello, worldeof\"), Ok((\"eof\", \"hello, world\")));\n/// assert_eq!(until_eof(\"hello, world\"), Err(Err::Incomplete(Needed::Unknown)));\n/// assert_eq!(until_eof(\"hello, worldeo\"), Err(Err::Incomplete(Needed::Unknown)));\n/// assert_eq!(until_eof(\"1eof2eof\"), Ok((\"eof2eof\", \"1\")));\n/// ```\npub fn take_until>(tag: T) -> impl Parser\nwhere\n I: Input + FindSubstring,\n T: Clone,\n{\n TakeUntil {\n tag,\n e: PhantomData,\n }\n}\n\n/// Parser implementation for [take_until]\npub struct TakeUntil {\n tag: T,\n e: PhantomData,\n}\n\nimpl> Parser for TakeUntil\nwhere\n I: Input + FindSubstring,\n T: Clone,\n{\n type Output = I;\n type Error = Error;\n\n fn process(&mut self, i: I) -> crate::PResult {\n match i.find_substring(self.tag.clone()) {\n None => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::Unknown))\n } else {\n Err(Err::Error(OM::Error::bind(|| {\n let e: ErrorKind = ErrorKind::TakeUntil;\n Error::from_error_kind(i, e)\n })))\n }\n }\n Some(index) => Ok((i.take_from(index), OM::Output::bind(|| i.take(index)))),\n }\n }\n}\n\n/// Returns the non empty input slice up to the first occurrence of the pattern.\n///\n/// It doesn't consume the pattern.\n///\n/// # Streaming Specific\n/// *Streaming version* will return a `Err::Incomplete(Needed::new(N))` if the input doesn't\n/// contain the pattern or if the input is smaller than the pattern.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::streaming::take_until1;\n///\n/// fn until_eof(s: &str) -> IResult<&str, &str> {\n/// take_until1(\"eof\")(s)\n/// }\n///\n/// assert_eq!(until_eof(\"hello, worldeof\"), Ok((\"eof\", \"hello, world\")));\n/// assert_eq!(until_eof(\"hello, world\"), Err(Err::Incomplete(Needed::Unknown)));\n/// assert_eq!(until_eof(\"hello, worldeo\"), Err(Err::Incomplete(Needed::Unknown)));\n/// assert_eq!(until_eof(\"1eof2eof\"), Ok((\"eof2eof\", \"1\")));\n/// assert_eq!(until_eof(\"eof\"), Err(Err::Error(Error::new(\"eof\", ErrorKind::TakeUntil))));\n/// ```\npub fn take_until1>(tag: T) -> impl Parser\nwhere\n I: Input + FindSubstring,\n T: Clone,\n{\n TakeUntil1 {\n tag,\n e: PhantomData,\n }\n}\n\n/// Parser implementation for take_until1\npub struct TakeUntil1 {\n tag: T,\n e: PhantomData,\n}\n\nimpl> Parser for TakeUntil1\nwhere\n I: Input + FindSubstring,\n T: Clone,\n{\n type Output = I;\n type Error = Error;\n\n fn process(&mut self, i: I) -> crate::PResult {\n match i.find_substring(self.tag.clone()) {\n None => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::Unknown))\n } else {\n Err(Err::Error(OM::Error::bind(|| {\n let e: ErrorKind = ErrorKind::TakeUntil;\n Error::from_error_kind(i, e)\n })))\n }\n }\n Some(0) => Err(Err::Error(OM::Error::bind(|| {\n Error::from_error_kind(i, ErrorKind::TakeUntil)\n }))),\n\n Some(index) => Ok((i.take_from(index), OM::Output::bind(|| i.take(index)))),\n }\n }\n}\n\n/// Matches a byte string with escaped characters.\n///\n/// * The first argument matches the normal characters (it must not accept the control character)\n/// * The second argument is the control character (like `\\` in most languages)\n/// * The third argument matches the escaped characters\n/// # Example\n/// ```\n/// # use nom::{Err, error::ErrorKind, Needed, IResult};\n/// # use nom::character::complete::digit1;\n/// use nom::bytes::streaming::escaped;\n/// use nom::character::streaming::one_of;\n///\n/// fn esc(s: &str) -> IResult<&str, &str> {\n/// escaped(digit1, '\\\\', one_of(\"\\\"n\\\\\"))(s)\n/// }\n///\n/// assert_eq!(esc(\"123;\"), Ok((\";\", \"123\")));\n/// assert_eq!(esc(\"12\\\\\\\"34;\"), Ok((\";\", \"12\\\\\\\"34\")));\n/// ```\n///\npub fn escaped(\n normal: F,\n control_char: char,\n escapable: G,\n) -> impl Parser\nwhere\n I: Input + Clone + crate::traits::Offset,\n ::Item: crate::traits::AsChar,\n F: Parser,\n G: Parser,\n Error: ParseError,\n{\n Escaped {\n normal,\n escapable,\n control_char,\n e: PhantomData,\n }\n}\n\n/// Parser implementation for [escaped]\npub struct Escaped {\n normal: F,\n escapable: G,\n control_char: char,\n e: PhantomData,\n}\n\nimpl, F, G> Parser for Escaped\nwhere\n I: Input + Clone + crate::traits::Offset,\n ::Item: crate::traits::AsChar,\n F: Parser,\n G: Parser,\n Error: ParseError,\n{\n type Output = I;\n type Error = Error;\n\n fn process(\n &mut self,\n input: I,\n ) -> crate::PResult {\n let mut i = input.clone();\n\n while i.input_len() > 0 {\n let current_len = i.input_len();\n\n match self\n .normal\n .process::>(i.clone())\n {\n Ok((i2, _)) => {\n if i2.input_len() == 0 {\n if OM::Incomplete::is_streaming() {\n return Err(Err::Incomplete(Needed::Unknown));\n } else {\n let index = input.input_len();\n return Ok((\n input.take_from(index),\n OM::Output::bind(|| input.take(index)),\n ));\n }\n } else if i2.input_len() == current_len {\n let index = input.offset(&i2);\n return Ok((\n input.take_from(index),\n OM::Output::bind(|| input.take(index)),\n ));\n } else {\n i = i2;\n }\n }\n Err(Err::Error(_)) => {\n // unwrap() should be safe here since index < $i.input_len()\n if i.iter_elements().next().unwrap().as_char() == self.control_char {\n let next = self.control_char.len_utf8();\n if next >= i.input_len() {\n if OM::Incomplete::is_streaming() {\n return Err(Err::Incomplete(Needed::new(1)));\n } else {\n return Err(Err::Error(OM::Error::bind(|| {\n Error::from_error_kind(input, ErrorKind::Escaped)\n })));\n }\n } else {\n match self\n .escapable\n .process::>(i.take_from(next))\n {\n Ok((i2, _)) => {\n if i2.input_len() == 0 {\n if OM::Incomplete::is_streaming() {\n return Err(Err::Incomplete(Needed::Unknown));\n } else {\n let index = input.input_len();\n return Ok((\n input.take_from(index),\n OM::Output::bind(|| input.take(index)),\n ));\n }\n } else {\n i = i2;\n }\n }\n Err(e) => return Err(e),\n }\n }\n } else {\n let index = input.offset(&i);\n if index == 0 {\n return Err(Err::Error(OM::Error::bind(|| {\n Error::from_error_kind(input, ErrorKind::Escaped)\n })));\n } else {\n return Ok((\n input.take_from(index),\n OM::Output::bind(|| input.take(index)),\n ));\n }\n }\n }\n Err(Err::Failure(e)) => {\n return Err(Err::Failure(e));\n }\n Err(Err::Incomplete(i)) => {\n return Err(Err::Incomplete(i));\n }\n }\n }\n\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::Unknown))\n } else {\n let index = input.input_len();\n Ok((\n input.take_from(index),\n OM::Output::bind(|| input.take(index)),\n ))\n }\n }\n}\n\n/// Matches a byte string with escaped characters.\n///\n/// * The first argument matches the normal characters (it must not match the control character)\n/// * The second argument is the control character (like `\\` in most languages)\n/// * The third argument matches the escaped characters and transforms them\n///\n/// As an example, the chain `abc\\tdef` could be `abc def` (it also consumes the control character)\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind, Needed, IResult};\n/// # use std::str::from_utf8;\n/// use nom::bytes::streaming::{escaped_transform, tag};\n/// use nom::character::streaming::alpha1;\n/// use nom::branch::alt;\n/// use nom::combinator::value;\n///\n/// fn parser(input: &str) -> IResult<&str, String> {\n/// escaped_transform(\n/// alpha1,\n/// '\\\\',\n/// alt((\n/// value(\"\\\\\", tag(\"\\\\\")),\n/// value(\"\\\"\", tag(\"\\\"\")),\n/// value(\"\\n\", tag(\"n\")),\n/// ))\n/// )(input)\n/// }\n///\n/// assert_eq!(parser(\"ab\\\\\\\"cd\\\"\"), Ok((\"\\\"\", String::from(\"ab\\\"cd\"))));\n/// ```\n#[cfg(feature = \"alloc\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\npub fn escaped_transform(\n normal: F,\n control_char: char,\n transform: G,\n) -> impl Parser\nwhere\n I: Clone + crate::traits::Offset + Input,\n I: crate::traits::ExtendInto,\n >::Output: crate::traits::ExtendInto,\n >::Output: crate::traits::ExtendInto,\n ::Item: crate::traits::AsChar,\n F: Parser,\n G: Parser,\n Error: ParseError,\n{\n EscapedTransform {\n normal,\n control_char,\n transform,\n e: PhantomData,\n extend: PhantomData,\n o: PhantomData,\n }\n}\n\n/// Parser implementation for [escaped_transform]\npub struct EscapedTransform {\n normal: F,\n transform: G,\n control_char: char,\n e: PhantomData,\n extend: PhantomData,\n o: PhantomData,\n}\n\nimpl, F, G, ExtendItem, Output> Parser\n for EscapedTransform\nwhere\n I: Clone + crate::traits::Offset + Input,\n I: crate::traits::ExtendInto,\n >::Output: crate::traits::ExtendInto,\n >::Output: crate::traits::ExtendInto,\n ::Item: crate::traits::AsChar,\n F: Parser,\n G: Parser,\n Error: ParseError,\n{\n type Output = Output;\n type Error = Error;\n\n fn process(\n &mut self,\n input: I,\n ) -> crate::PResult {\n let mut index = 0;\n let mut res = OM::Output::bind(|| input.new_builder());\n\n while index < input.input_len() {\n let current_len = input.input_len();\n let remainder = input.take_from(index);\n match self.normal.process::(remainder.clone()) {\n Ok((i2, o)) => {\n res = OM::Output::combine(o, res, |o, mut res| {\n o.extend_into(&mut res);\n res\n });\n if i2.input_len() == 0 {\n if OM::Incomplete::is_streaming() {\n return Err(Err::Incomplete(Needed::Unknown));\n } else {\n let index = input.input_len();\n return Ok((input.take_from(index), res));\n }\n } else if i2.input_len() == current_len {\n return Ok((remainder, res));\n } else {\n index = input.offset(&i2);\n }\n }\n Err(Err::Error(_)) => {\n // unwrap() should be safe here since index < $i.input_len()\n if remainder.iter_elements().next().unwrap().as_char() == self.control_char {\n let next = index + self.control_char.len_utf8();\n let input_len = input.input_len();\n\n if next >= input_len {\n if OM::Incomplete::is_streaming() {\n return Err(Err::Incomplete(Needed::Unknown));\n } else {\n return Err(Err::Error(OM::Error::bind(|| {\n Error::from_error_kind(remainder, ErrorKind::EscapedTransform)\n })));\n }\n } else {\n match self.transform.process::(input.take_from(next)) {\n Ok((i2, o)) => {\n res = OM::Output::combine(o, res, |o, mut res| {\n o.extend_into(&mut res);\n res\n });\n if i2.input_len() == 0 {\n if OM::Incomplete::is_streaming() {\n return Err(Err::Incomplete(Needed::Unknown));\n } else {\n return Ok((input.take_from(input.input_len()), res));\n }\n } else {\n index = input.offset(&i2);\n }\n }\n Err(Err::Error(e)) => return Err(Err::Error(e)),\n Err(Err::Failure(e)) => {\n return Err(Err::Failure(e));\n }\n Err(Err::Incomplete(i)) => {\n return Err(Err::Incomplete(i));\n }\n }\n }\n } else {\n if index == 0 {\n return Err(Err::Error(OM::Error::bind(|| {\n Error::from_error_kind(remainder, ErrorKind::EscapedTransform)\n })));\n }\n return Ok((remainder, res));\n }\n }\n Err(Err::Failure(e)) => {\n return Err(Err::Failure(e));\n }\n Err(Err::Incomplete(i)) => {\n return Err(Err::Incomplete(i));\n }\n }\n }\n\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::Unknown))\n } else {\n Ok((input.take_from(index), res))\n }\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "complete.rs", "content": "use core::marker::PhantomData;\n\nuse crate::error::ParseError;\nuse crate::internal::{IResult, Parser};\nuse crate::traits::{Compare, FindSubstring, FindToken, ToUsize};\nuse crate::Complete;\nuse crate::Emit;\nuse crate::Input;\nuse crate::OutputM;\n\n/// Recognizes a pattern\n///\n/// The input data will be compared to the tag combinator's argument and will return the part of\n/// the input that matches the argument\n///\n/// It will return `Err(Err::Error((_, ErrorKind::Tag)))` if the input doesn't match the pattern\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, &str> {\n/// tag(\"Hello\")(s)\n/// }\n///\n/// assert_eq!(parser(\"Hello, World!\"), Ok((\", World!\", \"Hello\")));\n/// assert_eq!(parser(\"Something\"), Err(Err::Error(Error::new(\"Something\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Tag))));\n/// ```\npub fn tag>(tag: T) -> impl Fn(I) -> IResult\nwhere\n I: Input + Compare,\n T: Input + Clone,\n{\n move |i: I| {\n let mut parser = super::Tag {\n tag: tag.clone(),\n e: PhantomData,\n };\n\n parser.process::>(i)\n }\n}\n\n/// Recognizes a case insensitive pattern.\n///\n/// The input data will be compared to the tag combinator's argument and will return the part of\n/// the input that matches the argument with no regard to case.\n///\n/// It will return `Err(Err::Error((_, ErrorKind::Tag)))` if the input doesn't match the pattern.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::complete::tag_no_case;\n///\n/// fn parser(s: &str) -> IResult<&str, &str> {\n/// tag_no_case(\"hello\")(s)\n/// }\n///\n/// assert_eq!(parser(\"Hello, World!\"), Ok((\", World!\", \"Hello\")));\n/// assert_eq!(parser(\"hello, World!\"), Ok((\", World!\", \"hello\")));\n/// assert_eq!(parser(\"HeLlO, World!\"), Ok((\", World!\", \"HeLlO\")));\n/// assert_eq!(parser(\"Something\"), Err(Err::Error(Error::new(\"Something\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Tag))));\n/// ```\npub fn tag_no_case>(tag: T) -> impl Fn(I) -> IResult\nwhere\n I: Input + Compare,\n T: Input + Clone,\n{\n move |i: I| {\n let mut parser = super::TagNoCase {\n tag: tag.clone(),\n e: PhantomData,\n };\n\n parser.process::>(i)\n }\n}\n\n/// Parse till certain characters are met.\n///\n/// The parser will return the longest slice till one of the characters of the combinator's argument are met.\n///\n/// It doesn't consume the matched character.\n///\n/// It will return a `Err::Error((\"\", ErrorKind::IsNot))` if the pattern wasn't met.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::complete::is_not;\n///\n/// fn not_space(s: &str) -> IResult<&str, &str> {\n/// is_not(\" \\t\\r\\n\")(s)\n/// }\n///\n/// assert_eq!(not_space(\"Hello, World!\"), Ok((\" World!\", \"Hello,\")));\n/// assert_eq!(not_space(\"Sometimes\\t\"), Ok((\"\\t\", \"Sometimes\")));\n/// assert_eq!(not_space(\"Nospace\"), Ok((\"\", \"Nospace\")));\n/// assert_eq!(not_space(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::IsNot))));\n/// ```\npub fn is_not>(arr: T) -> impl FnMut(I) -> IResult\nwhere\n I: Input,\n T: FindToken<::Item>,\n{\n let mut parser = super::is_not(arr);\n\n move |i: I| parser.process::>(i)\n}\n\n/// Returns the longest input slice (at least 1) that matches the pattern.\n///\n/// The parser will return the longest slice consisting of the characters in provided in the\n/// combinator's argument.\n///\n/// It will return a `Err(Err::Error((_, ErrorKind::IsA)))` if the pattern wasn't met.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::complete::is_a;\n///\n/// fn hex(s: &str) -> IResult<&str, &str> {\n/// is_a(\"1234567890ABCDEF\")(s)\n/// }\n///\n/// assert_eq!(hex(\"123 and voila\"), Ok((\" and voila\", \"123\")));\n/// assert_eq!(hex(\"DEADBEEF and others\"), Ok((\" and others\", \"DEADBEEF\")));\n/// assert_eq!(hex(\"BADBABEsomething\"), Ok((\"something\", \"BADBABE\")));\n/// assert_eq!(hex(\"D15EA5E\"), Ok((\"\", \"D15EA5E\")));\n/// assert_eq!(hex(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::IsA))));\n/// ```\npub fn is_a>(arr: T) -> impl FnMut(I) -> IResult\nwhere\n I: Input,\n T: FindToken<::Item>,\n{\n let mut parser = super::is_a(arr);\n\n move |i: I| parser.process::>(i)\n}\n\n/// Returns the longest input slice (if any) that matches the predicate.\n///\n/// The parser will return the longest slice that matches the given predicate *(a function that\n/// takes the input and returns a bool)*.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, IResult};\n/// use nom::bytes::complete::take_while;\n/// use nom::AsChar;\n///\n/// fn alpha(s: &[u8]) -> IResult<&[u8], &[u8]> {\n/// take_while(AsChar::is_alpha)(s)\n/// }\n///\n/// assert_eq!(alpha(b\"latin123\"), Ok((&b\"123\"[..], &b\"latin\"[..])));\n/// assert_eq!(alpha(b\"12345\"), Ok((&b\"12345\"[..], &b\"\"[..])));\n/// assert_eq!(alpha(b\"latin\"), Ok((&b\"\"[..], &b\"latin\"[..])));\n/// assert_eq!(alpha(b\"\"), Ok((&b\"\"[..], &b\"\"[..])));\n/// ```\npub fn take_while>(cond: F) -> impl FnMut(I) -> IResult\nwhere\n I: Input,\n F: Fn(::Item) -> bool,\n{\n let mut parser = super::take_while(cond);\n\n move |i: I| parser.process::>(i)\n}\n\n/// Returns the longest (at least 1) input slice that matches the predicate.\n///\n/// The parser will return the longest slice that matches the given predicate *(a function that\n/// takes the input and returns a bool)*.\n///\n/// It will return an `Err(Err::Error((_, ErrorKind::TakeWhile1)))` if the pattern wasn't met.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::complete::take_while1;\n/// use nom::AsChar;\n///\n/// fn alpha(s: &[u8]) -> IResult<&[u8], &[u8]> {\n/// take_while1(AsChar::is_alpha)(s)\n/// }\n///\n/// assert_eq!(alpha(b\"latin123\"), Ok((&b\"123\"[..], &b\"latin\"[..])));\n/// assert_eq!(alpha(b\"latin\"), Ok((&b\"\"[..], &b\"latin\"[..])));\n/// assert_eq!(alpha(b\"12345\"), Err(Err::Error(Error::new(&b\"12345\"[..], ErrorKind::TakeWhile1))));\n/// ```\npub fn take_while1>(cond: F) -> impl FnMut(I) -> IResult\nwhere\n I: Input,\n F: Fn(::Item) -> bool,\n{\n let mut parser = super::take_while1(cond);\n\n move |i: I| parser.process::>(i)\n}\n\n/// Returns the longest (m <= len <= n) input slice that matches the predicate.\n///\n/// The parser will return the longest slice that matches the given predicate *(a function that\n/// takes the input and returns a bool)*.\n///\n/// It will return an `Err::Error((_, ErrorKind::TakeWhileMN))` if the pattern wasn't met or is out\n/// of range (m <= len <= n).\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::complete::take_while_m_n;\n/// use nom::AsChar;\n///\n/// fn short_alpha(s: &[u8]) -> IResult<&[u8], &[u8]> {\n/// take_while_m_n(3, 6, AsChar::is_alpha)(s)\n/// }\n///\n/// assert_eq!(short_alpha(b\"latin123\"), Ok((&b\"123\"[..], &b\"latin\"[..])));\n/// assert_eq!(short_alpha(b\"lengthy\"), Ok((&b\"y\"[..], &b\"length\"[..])));\n/// assert_eq!(short_alpha(b\"latin\"), Ok((&b\"\"[..], &b\"latin\"[..])));\n/// assert_eq!(short_alpha(b\"ed\"), Err(Err::Error(Error::new(&b\"ed\"[..], ErrorKind::TakeWhileMN))));\n/// assert_eq!(short_alpha(b\"12345\"), Err(Err::Error(Error::new(&b\"12345\"[..], ErrorKind::TakeWhileMN))));\n/// ```\npub fn take_while_m_n>(\n m: usize,\n n: usize,\n cond: F,\n) -> impl FnMut(I) -> IResult\nwhere\n I: Input,\n F: Fn(::Item) -> bool,\n{\n let mut parser = super::take_while_m_n(m, n, cond);\n\n move |i: I| parser.process::>(i)\n}\n\n/// Returns the longest input slice (if any) till a predicate is met.\n///\n/// The parser will return the longest slice till the given predicate *(a function that\n/// takes the input and returns a bool)*.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, IResult};\n/// use nom::bytes::complete::take_till;\n///\n/// fn till_colon(s: &str) -> IResult<&str, &str> {\n/// take_till(|c| c == ':')(s)\n/// }\n///\n/// assert_eq!(till_colon(\"latin:123\"), Ok((\":123\", \"latin\")));\n/// assert_eq!(till_colon(\":empty matched\"), Ok((\":empty matched\", \"\"))); //allowed\n/// assert_eq!(till_colon(\"12345\"), Ok((\"\", \"12345\")));\n/// assert_eq!(till_colon(\"\"), Ok((\"\", \"\")));\n/// ```\n#[allow(clippy::redundant_closure)]\npub fn take_till>(cond: F) -> impl FnMut(I) -> IResult\nwhere\n I: Input,\n F: Fn(::Item) -> bool,\n{\n let mut parser = super::take_till(cond);\n\n move |i: I| parser.process::>(i)\n}\n\n/// Returns the longest (at least 1) input slice till a predicate is met.\n///\n/// The parser will return the longest slice till the given predicate *(a function that\n/// takes the input and returns a bool)*.\n///\n/// It will return `Err(Err::Error((_, ErrorKind::TakeTill1)))` if the input is empty or the\n/// predicate matches the first input.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::complete::take_till1;\n///\n/// fn till_colon(s: &str) -> IResult<&str, &str> {\n/// take_till1(|c| c == ':')(s)\n/// }\n///\n/// assert_eq!(till_colon(\"latin:123\"), Ok((\":123\", \"latin\")));\n/// assert_eq!(till_colon(\":empty matched\"), Err(Err::Error(Error::new(\":empty matched\", ErrorKind::TakeTill1))));\n/// assert_eq!(till_colon(\"12345\"), Ok((\"\", \"12345\")));\n/// assert_eq!(till_colon(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::TakeTill1))));\n/// ```\n#[allow(clippy::redundant_closure)]\npub fn take_till1>(cond: F) -> impl FnMut(I) -> IResult\nwhere\n I: Input,\n F: Fn(::Item) -> bool,\n{\n let mut parser = super::take_till1(cond);\n\n move |i: I| parser.process::>(i)\n}\n\n/// Returns an input slice containing the first N input elements (Input[..N]).\n///\n/// It will return `Err(Err::Error((_, ErrorKind::Eof)))` if the input is shorter than the argument.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::complete::take;\n///\n/// fn take6(s: &str) -> IResult<&str, &str> {\n/// take(6usize)(s)\n/// }\n///\n/// assert_eq!(take6(\"1234567\"), Ok((\"7\", \"123456\")));\n/// assert_eq!(take6(\"things\"), Ok((\"\", \"things\")));\n/// assert_eq!(take6(\"short\"), Err(Err::Error(Error::new(\"short\", ErrorKind::Eof))));\n/// assert_eq!(take6(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Eof))));\n/// ```\n///\n/// The units that are taken will depend on the input type. For example, for a\n/// `&str` it will take a number of `char`'s, whereas for a `&[u8]` it will\n/// take that many `u8`'s:\n///\n/// ```rust\n/// use nom::error::Error;\n/// use nom::bytes::complete::take;\n///\n/// assert_eq!(take::<_, _, Error<_>>(1usize)(\"\ud83d\udc99\"), Ok((\"\", \"\ud83d\udc99\")));\n/// assert_eq!(take::<_, _, Error<_>>(1usize)(\"\ud83d\udc99\".as_bytes()), Ok((b\"\\x9F\\x92\\x99\".as_ref(), b\"\\xF0\".as_ref())));\n/// ```\npub fn take>(count: C) -> impl FnMut(I) -> IResult\nwhere\n I: Input,\n C: ToUsize,\n{\n let mut parser = super::take(count);\n\n move |i: I| parser.process::>(i)\n}\n\n/// Returns the input slice up to the first occurrence of the pattern.\n///\n/// It doesn't consume the pattern. It will return `Err(Err::Error((_, ErrorKind::TakeUntil)))`\n/// if the pattern wasn't met.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::complete::take_until;\n///\n/// fn until_eof(s: &str) -> IResult<&str, &str> {\n/// take_until(\"eof\")(s)\n/// }\n///\n/// assert_eq!(until_eof(\"hello, worldeof\"), Ok((\"eof\", \"hello, world\")));\n/// assert_eq!(until_eof(\"hello, world\"), Err(Err::Error(Error::new(\"hello, world\", ErrorKind::TakeUntil))));\n/// assert_eq!(until_eof(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::TakeUntil))));\n/// assert_eq!(until_eof(\"1eof2eof\"), Ok((\"eof2eof\", \"1\")));\n/// ```\npub fn take_until>(tag: T) -> impl FnMut(I) -> IResult\nwhere\n I: Input + FindSubstring,\n T: Input + Clone,\n{\n let mut parser = super::take_until(tag);\n\n move |i: I| parser.process::>(i)\n}\n\n/// Returns the non empty input slice up to the first occurrence of the pattern.\n///\n/// It doesn't consume the pattern. It will return `Err(Err::Error((_, ErrorKind::TakeUntil)))`\n/// if the pattern wasn't met.\n/// # Example\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult};\n/// use nom::bytes::complete::take_until1;\n///\n/// fn until_eof(s: &str) -> IResult<&str, &str> {\n/// take_until1(\"eof\")(s)\n/// }\n///\n/// assert_eq!(until_eof(\"hello, worldeof\"), Ok((\"eof\", \"hello, world\")));\n/// assert_eq!(until_eof(\"hello, world\"), Err(Err::Error(Error::new(\"hello, world\", ErrorKind::TakeUntil))));\n/// assert_eq!(until_eof(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::TakeUntil))));\n/// assert_eq!(until_eof(\"1eof2eof\"), Ok((\"eof2eof\", \"1\")));\n/// assert_eq!(until_eof(\"eof\"), Err(Err::Error(Error::new(\"eof\", ErrorKind::TakeUntil))));\n/// ```\npub fn take_until1>(tag: T) -> impl FnMut(I) -> IResult\nwhere\n I: Input + FindSubstring,\n T: Input + Clone,\n{\n let mut parser = super::take_until1(tag);\n\n move |i: I| parser.process::>(i)\n}\n\n/// Matches a byte string with escaped characters.\n///\n/// * The first argument matches the normal characters (it must not accept the control character)\n/// * The second argument is the control character (like `\\` in most languages)\n/// * The third argument matches the escaped characters\n/// # Example\n/// ```\n/// # use nom::{Err, error::ErrorKind, Needed, IResult};\n/// # use nom::character::complete::digit1;\n/// use nom::bytes::complete::escaped;\n/// use nom::character::complete::one_of;\n///\n/// fn esc(s: &str) -> IResult<&str, &str> {\n/// escaped(digit1, '\\\\', one_of(r#\"\"n\\\"#))(s)\n/// }\n///\n/// assert_eq!(esc(\"123;\"), Ok((\";\", \"123\")));\n/// assert_eq!(esc(r#\"12\\\"34;\"#), Ok((\";\", r#\"12\\\"34\"#)));\n/// ```\n///\npub fn escaped<'a, I, Error, F, G>(\n normal: F,\n control_char: char,\n escapable: G,\n) -> impl FnMut(I) -> IResult\nwhere\n I: Clone + crate::traits::Offset + Input + 'a,\n ::Item: crate::traits::AsChar,\n F: Parser,\n G: Parser,\n Error: ParseError,\n{\n let mut parser = super::escaped(normal, control_char, escapable);\n\n move |i: I| parser.process::>(i)\n}\n\n/// Matches a byte string with escaped characters.\n///\n/// * The first argument matches the normal characters (it must not match the control character)\n/// * The second argument is the control character (like `\\` in most languages)\n/// * The third argument matches the escaped characters and transforms them\n///\n/// As an example, the chain `abc\\tdef` could be `abc def` (it also consumes the control character)\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind, Needed, IResult};\n/// # use std::str::from_utf8;\n/// use nom::bytes::complete::{escaped_transform, tag};\n/// use nom::character::complete::alpha1;\n/// use nom::branch::alt;\n/// use nom::combinator::value;\n///\n/// fn parser(input: &str) -> IResult<&str, String> {\n/// escaped_transform(\n/// alpha1,\n/// '\\\\',\n/// alt((\n/// value(\"\\\\\", tag(\"\\\\\")),\n/// value(\"\\\"\", tag(\"\\\"\")),\n/// value(\"\\n\", tag(\"n\")),\n/// ))\n/// )(input)\n/// }\n///\n/// assert_eq!(parser(\"ab\\\\\\\"cd\"), Ok((\"\", String::from(\"ab\\\"cd\"))));\n/// assert_eq!(parser(\"ab\\\\ncd\"), Ok((\"\", String::from(\"ab\\ncd\"))));\n/// ```\n#[cfg(feature = \"alloc\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\npub fn escaped_transform(\n normal: F,\n control_char: char,\n transform: G,\n) -> impl FnMut(I) -> IResult\nwhere\n I: Clone + crate::traits::Offset + Input,\n I: crate::traits::ExtendInto,\n O1: crate::traits::ExtendInto,\n O2: crate::traits::ExtendInto,\n ::Item: crate::traits::AsChar,\n F: Parser,\n G: Parser,\n Error: ParseError,\n{\n let mut parser = super::escaped_transform(normal, control_char, transform);\n\n move |i: I| parser.process::>(i)\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use crate::error::ErrorKind;\n use crate::AsChar;\n use crate::Err;\n\n #[test]\n fn complete_take_while_m_n_utf8_all_matching() {\n let result: IResult<&str, &str> =\n super::take_while_m_n(1, 4, |c: char| c.is_alphabetic())(\"\u00f8n\");\n assert_eq!(result, Ok((\"\", \"\u00f8n\")));\n }\n\n #[test]\n fn complete_take_while_m_n_utf8_all_matching_substring() {\n let result: IResult<&str, &str> =\n super::take_while_m_n(1, 1, |c: char| c.is_alphabetic())(\"\u00f8n\");\n assert_eq!(result, Ok((\"n\", \"\u00f8\")));\n }\n\n // issue #1336 \"escaped hangs if normal parser accepts empty\"\n fn escaped_string(input: &str) -> IResult<&str, &str> {\n use crate::character::complete::{alpha0, one_of};\n escaped(alpha0, '\\\\', one_of(\"n\"))(input)\n }\n\n // issue #1336 \"escaped hangs if normal parser accepts empty\"\n #[test]\n fn escaped_hang() {\n escaped_string(\"7\").unwrap();\n escaped_string(\"a7\").unwrap();\n }\n\n // issue ##1118 escaped does not work with empty string\n fn unquote(input: &str) -> IResult<&str, &str> {\n use crate::bytes::complete::*;\n use crate::character::complete::*;\n use crate::combinator::opt;\n use crate::sequence::delimited;\n\n delimited(\n char('\"'),\n escaped(opt(none_of(r#\"\\\"\"#)), '\\\\', one_of(r#\"\\\"rnt\"#)),\n char('\"'),\n )\n .parse(input)\n }\n\n #[test]\n fn escaped_hang_1118() {\n assert_eq!(unquote(r#\"\"\"\"#), Ok((\"\", \"\")));\n }\n\n // issue #1630 take_while_m_n is invalid for multi-byte UTF-8 characters\n #[test]\n fn complete_take_while_m_n_multibyte() {\n use crate::error::Error;\n\n fn multi_byte_chars(s: &str, m: usize, n: usize) -> IResult<&str, &str> {\n take_while_m_n(m, n, |c: char| c.len() > 1)(s)\n }\n\n assert_eq!(multi_byte_chars(\"\u20ac latin\", 0, 64), Ok((\" latin\", \"\u20ac\")));\n assert_eq!(multi_byte_chars(\"\ud834\udd20 latin\", 0, 1), Ok((\" latin\", \"\ud834\udd20\")));\n assert_eq!(multi_byte_chars(\"\u0628\u0627\u0628 latin\", 0, 64), Ok((\" latin\", \"\u0628\u0627\u0628\")));\n assert_eq!(\n multi_byte_chars(\"\ud83d\udca3\ud83d\udca2\u1fa0 latin\", 3, 3),\n Ok((\" latin\", \"\ud83d\udca3\ud83d\udca2\u1fa0\"))\n );\n assert_eq!(multi_byte_chars(\"latin\", 0, 64), Ok((\"latin\", \"\")));\n assert_eq!(multi_byte_chars(\"\u0628\u0627\u0628\", 1, 3), Ok((\"\", \"\u0628\u0627\u0628\")));\n assert_eq!(multi_byte_chars(\"\u0628\u0627\u0628\", 1, 2), Ok((\"\u0628\", \"\u0628\u0627\")));\n assert_eq!(\n multi_byte_chars(\"latin\", 1, 64),\n Err(Err::Error(Error::new(\"latin\", ErrorKind::TakeWhileMN)))\n );\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "mod.rs", "content": "use core::marker::PhantomData;\n\nuse crate::error::ErrorKind;\nuse crate::FindToken;\nuse crate::IsStreaming;\nuse crate::Mode;\nuse crate::{error::ParseError, AsChar, Err, IResult, Input, Needed, Parser};\n\n#[cfg(test)]\nmod tests;\n\npub mod complete;\npub mod streaming;\n\n#[inline]\n#[doc(hidden)]\n#[deprecated(since = \"8.0.0\", note = \"Replaced with `AsChar::is_alpha`\")]\npub fn is_alphabetic(chr: u8) -> bool {\n matches!(chr, 0x41..=0x5A | 0x61..=0x7A)\n}\n\n#[inline]\n#[doc(hidden)]\n#[deprecated(since = \"8.0.0\", note = \"Replaced with `AsChar::is_dec_digit`\")]\npub fn is_digit(chr: u8) -> bool {\n matches!(chr, 0x30..=0x39)\n}\n\n#[inline]\n#[doc(hidden)]\n#[deprecated(since = \"8.0.0\", note = \"Replaced with `AsChar::is_hex_digit`\")]\npub fn is_hex_digit(chr: u8) -> bool {\n matches!(chr, 0x30..=0x39 | 0x41..=0x46 | 0x61..=0x66)\n}\n\n#[inline]\n#[doc(hidden)]\n#[deprecated(since = \"8.0.0\", note = \"Replaced with `AsChar::is_oct_digit`\")]\npub fn is_oct_digit(chr: u8) -> bool {\n matches!(chr, 0x30..=0x37)\n}\n\n/// Tests if byte is ASCII binary digit: 0-1\n///\n/// # Example\n///\n/// ```\n/// # use nom::character::is_bin_digit;\n/// assert_eq!(is_bin_digit(b'a'), false);\n/// assert_eq!(is_bin_digit(b'2'), false);\n/// assert_eq!(is_bin_digit(b'0'), true);\n/// assert_eq!(is_bin_digit(b'1'), true);\n/// ```\n#[inline]\npub fn is_bin_digit(chr: u8) -> bool {\n matches!(chr, 0x30..=0x31)\n}\n\n#[inline]\n#[doc(hidden)]\n#[deprecated(since = \"8.0.0\", note = \"Replaced with `AsChar::is_alphanum`\")]\npub fn is_alphanumeric(chr: u8) -> bool {\n AsChar::is_alphanum(chr)\n}\n\n#[inline]\n#[doc(hidden)]\n#[deprecated(since = \"8.0.0\", note = \"Replaced with `AsChar::is_space`\")]\npub fn is_space(chr: u8) -> bool {\n chr == b' ' || chr == b'\\t'\n}\n\n#[inline]\n#[doc(hidden)]\n#[deprecated(since = \"8.0.0\", note = \"Replaced with `AsChar::is_newline`\")]\npub fn is_newline(chr: u8) -> bool {\n chr == b'\\n'\n}\n\n/// Recognizes one character.\n///\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{ErrorKind, Error}, Needed, IResult};\n/// # use nom::character::streaming::char;\n/// fn parser(i: &str) -> IResult<&str, char> {\n/// char('a')(i)\n/// }\n/// assert_eq!(parser(\"abc\"), Ok((\"bc\", 'a')));\n/// assert_eq!(parser(\"bc\"), Err(Err::Error(Error::new(\"bc\", ErrorKind::Char))));\n/// assert_eq!(parser(\"\"), Err(Err::Incomplete(Needed::new(1))));\n/// ```\npub fn char>(c: char) -> impl Parser\nwhere\n I: Input,\n ::Item: AsChar,\n{\n Char { c, e: PhantomData }\n}\n\n/// Parser implementation for [char()]\npub struct Char {\n c: char,\n e: PhantomData,\n}\n\nimpl> Parser for Char\nwhere\n I: Input,\n ::Item: AsChar,\n{\n type Output = char;\n type Error = Error;\n #[inline(always)]\n fn process(\n &mut self,\n i: I,\n ) -> crate::PResult {\n match (i).iter_elements().next().map(|t| {\n let b = t.as_char() == self.c;\n (&self.c, b)\n }) {\n None => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::new(self.c.len() - i.input_len())))\n } else {\n Err(Err::Error(OM::Error::bind(|| Error::from_char(i, self.c))))\n }\n }\n Some((_, false)) => Err(Err::Error(OM::Error::bind(|| Error::from_char(i, self.c)))),\n Some((c, true)) => Ok((i.take_from(c.len()), OM::Output::bind(|| c.as_char()))),\n }\n }\n}\n\n/// Recognizes one character and checks that it satisfies a predicate\n///\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{ErrorKind, Error}, Needed, IResult};\n/// # use nom::character::complete::satisfy;\n/// fn parser(i: &str) -> IResult<&str, char> {\n/// satisfy(|c| c == 'a' || c == 'b')(i)\n/// }\n/// assert_eq!(parser(\"abc\"), Ok((\"bc\", 'a')));\n/// assert_eq!(parser(\"cd\"), Err(Err::Error(Error::new(\"cd\", ErrorKind::Satisfy))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Satisfy))));\n/// ```\npub fn satisfy>(\n predicate: F,\n) -> impl Parser\nwhere\n I: Input,\n ::Item: AsChar,\n F: Fn(char) -> bool,\n{\n Satisfy {\n predicate,\n make_error: |i: I| Error::from_error_kind(i, ErrorKind::Satisfy),\n }\n}\n\n/// Parser implementation for [satisfy]\npub struct Satisfy {\n predicate: F,\n make_error: MakeError,\n}\n\nimpl, F, MakeError> Parser for Satisfy\nwhere\n I: Input,\n ::Item: AsChar,\n F: Fn(char) -> bool,\n MakeError: Fn(I) -> Error,\n{\n type Output = char;\n type Error = Error;\n\n #[inline(always)]\n fn process(\n &mut self,\n i: I,\n ) -> crate::PResult {\n match (i).iter_elements().next().map(|t| {\n let c = t.as_char();\n let b = (self.predicate)(c);\n (c, b)\n }) {\n None => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::Unknown))\n } else {\n Err(Err::Error(OM::Error::bind(|| (self.make_error)(i))))\n }\n }\n Some((_, false)) => Err(Err::Error(OM::Error::bind(|| (self.make_error)(i)))),\n Some((c, true)) => Ok((i.take_from(c.len()), OM::Output::bind(|| c.as_char()))),\n }\n }\n}\n\n/// Recognizes one of the provided characters.\n///\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind};\n/// # use nom::character::complete::one_of;\n/// assert_eq!(one_of::<_, _, (&str, ErrorKind)>(\"abc\")(\"b\"), Ok((\"\", 'b')));\n/// assert_eq!(one_of::<_, _, (&str, ErrorKind)>(\"a\")(\"bc\"), Err(Err::Error((\"bc\", ErrorKind::OneOf))));\n/// assert_eq!(one_of::<_, _, (&str, ErrorKind)>(\"a\")(\"\"), Err(Err::Error((\"\", ErrorKind::OneOf))));\n/// ```\npub fn one_of>(list: T) -> impl Parser\nwhere\n I: Input,\n ::Item: AsChar,\n T: FindToken,\n{\n Satisfy {\n predicate: move |c: char| list.find_token(c),\n make_error: move |i| Error::from_error_kind(i, ErrorKind::OneOf),\n }\n}\n\n//. Recognizes a character that is not in the provided characters.\n///\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::character::streaming::none_of;\n/// assert_eq!(none_of::<_, _, (_, ErrorKind)>(\"abc\")(\"z\"), Ok((\"\", 'z')));\n/// assert_eq!(none_of::<_, _, (_, ErrorKind)>(\"ab\")(\"a\"), Err(Err::Error((\"a\", ErrorKind::NoneOf))));\n/// assert_eq!(none_of::<_, _, (_, ErrorKind)>(\"a\")(\"\"), Err(Err::Incomplete(Needed::Unknown)));\n/// ```\npub fn none_of>(list: T) -> impl Parser\nwhere\n I: Input,\n ::Item: AsChar,\n T: FindToken,\n{\n Satisfy {\n predicate: move |c: char| !list.find_token(c),\n make_error: move |i| Error::from_error_kind(i, ErrorKind::NoneOf),\n }\n}\n\n// Matches one byte as a character. Note that the input type will\n/// accept a `str`, but not a `&[u8]`, unlike many other nom parsers.\n///\n/// # Example\n///\n/// ```\n/// # use nom::{character::complete::anychar, Err, error::{Error, ErrorKind}, IResult};\n/// fn parser(input: &str) -> IResult<&str, char> {\n/// anychar(input)\n/// }\n///\n/// assert_eq!(parser(\"abc\"), Ok((\"bc\",'a')));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Eof))));\n/// ```\npub fn anychar>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n let mut it = input.iter_elements();\n match it.next() {\n None => Err(Err::Error(E::from_error_kind(input, ErrorKind::Eof))),\n Some(c) => Ok((input.take_from(c.len()), c.as_char())),\n }\n}\n\n/// Parser implementation for char\npub struct AnyChar {\n e: PhantomData,\n}\n\nimpl> Parser for AnyChar\nwhere\n I: Input,\n ::Item: AsChar,\n{\n type Output = char;\n type Error = Error;\n\n fn process(\n &mut self,\n i: I,\n ) -> crate::PResult {\n match (i).iter_elements().next() {\n None => {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::new(1)))\n } else {\n Err(Err::Error(OM::Error::bind(|| {\n Error::from_error_kind(i, ErrorKind::Eof)\n })))\n }\n }\n Some(c) => Ok((i.take_from(c.len()), OM::Output::bind(|| c.as_char()))),\n }\n }\n}\n\n/// Recognizes one or more ASCII numerical characters: 0-9\n///\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there's not enough input data,\n/// or if no terminating token is found (a non digit character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind, IResult, Needed};\n/// # use nom::character::streaming::digit1;\n/// assert_eq!(digit1::<_, (_, ErrorKind)>(\"21c\"), Ok((\"c\", \"21\")));\n/// assert_eq!(digit1::<_, (_, ErrorKind)>(\"c1\"), Err(Err::Error((\"c1\", ErrorKind::Digit))));\n/// assert_eq!(digit1::<_, (_, ErrorKind)>(\"\"), Err(Err::Incomplete(Needed::new(1))));\n/// ```\npub fn digit1>() -> impl Parser\nwhere\n T: Input,\n ::Item: AsChar,\n{\n Digit1 { e: PhantomData }\n}\n\n/// Parser implementation for [digit1]\npub struct Digit1 {\n e: PhantomData,\n}\n\nimpl> Parser for Digit1\nwhere\n ::Item: AsChar,\n{\n type Output = I;\n\n type Error = E;\n\n #[inline]\n fn process(\n &mut self,\n input: I,\n ) -> crate::PResult {\n input.split_at_position_mode1::(|item| !item.is_dec_digit(), ErrorKind::Digit)\n }\n}\n\n/// Recognizes zero or more spaces, tabs, carriage returns and line feeds.\n///\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there's not enough input data,\n/// or if no terminating token is found (a non space character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind, IResult, Needed};\n/// # use nom::character::streaming::multispace0;\n/// assert_eq!(multispace0::<_, (_, ErrorKind)>(\" \\t\\n\\r21c\"), Ok((\"21c\", \" \\t\\n\\r\")));\n/// assert_eq!(multispace0::<_, (_, ErrorKind)>(\"Z21c\"), Ok((\"Z21c\", \"\")));\n/// assert_eq!(multispace0::<_, (_, ErrorKind)>(\"\"), Err(Err::Incomplete(Needed::new(1))));\n/// ```\npub fn multispace0>() -> impl Parser\nwhere\n T: Input,\n ::Item: AsChar,\n{\n MultiSpace0 { e: PhantomData }\n let c = item.as_char();\n !(c == ' ' || c == '\\t' || c == '\\r' || c == '\\n')\n })*/\n}\n\n/// Parser implementation for [multispace0()]\npub struct MultiSpace0 {\n e: PhantomData,\n}\n\nimpl> Parser for MultiSpace0\nwhere\n I: Input,\n ::Item: AsChar,\n{\n type Output = I;\n type Error = Error;\n\n fn process(\n &mut self,\n i: I,\n ) -> crate::PResult {\n i.split_at_position_mode::(|item| {\n let c = item.as_char();\n !(c == ' ' || c == '\\t' || c == '\\r' || c == '\\n')\n })\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "complete.rs", "content": "use crate::branch::alt;\nuse crate::combinator::opt;\nuse crate::error::ErrorKind;\nuse crate::error::ParseError;\nuse crate::internal::{Err, IResult};\nuse crate::traits::{AsChar, FindToken, Input};\nuse crate::traits::{Compare, CompareResult};\nuse crate::Complete;\nuse crate::Emit;\nuse crate::OutputM;\nuse crate::Parser;\n\n/// Recognizes one character.\n///\n/// *Complete version*: Will return an error if there's not enough input data.\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{ErrorKind, Error}, IResult};\n/// # use nom::character::complete::char;\n/// fn parser(i: &str) -> IResult<&str, char> {\n/// char('a')(i)\n/// }\n/// assert_eq!(parser(\"abc\"), Ok((\"bc\", 'a')));\n/// assert_eq!(parser(\" abc\"), Err(Err::Error(Error::new(\" abc\", ErrorKind::Char))));\n/// assert_eq!(parser(\"bc\"), Err(Err::Error(Error::new(\"bc\", ErrorKind::Char))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Char))));\n/// ```\npub fn char>(c: char) -> impl FnMut(I) -> IResult\nwhere\n I: Input,\n ::Item: AsChar,\n{\n let mut parser = super::char(c);\n move |i: I| parser.process::>(i)\n}\n\n/// Recognizes one character and checks that it satisfies a predicate\n///\n/// *Complete version*: Will return an error if there's not enough input data.\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{ErrorKind, Error}, Needed, IResult};\n/// # use nom::character::complete::satisfy;\n/// fn parser(i: &str) -> IResult<&str, char> {\n/// satisfy(|c| c == 'a' || c == 'b')(i)\n/// }\n/// assert_eq!(parser(\"abc\"), Ok((\"bc\", 'a')));\n/// assert_eq!(parser(\"cd\"), Err(Err::Error(Error::new(\"cd\", ErrorKind::Satisfy))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Satisfy))));\n/// ```\npub fn satisfy>(predicate: F) -> impl FnMut(I) -> IResult\nwhere\n I: Input,\n ::Item: AsChar,\n F: Fn(char) -> bool,\n{\n let mut parser = super::satisfy(predicate);\n move |i: I| parser.process::>(i)\n}\n\n/// Recognizes one of the provided characters.\n///\n/// *Complete version*: Will return an error if there's not enough input data.\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind};\n/// # use nom::character::complete::one_of;\n/// assert_eq!(one_of::<_, _, (&str, ErrorKind)>(\"abc\")(\"b\"), Ok((\"\", 'b')));\n/// assert_eq!(one_of::<_, _, (&str, ErrorKind)>(\"a\")(\"bc\"), Err(Err::Error((\"bc\", ErrorKind::OneOf))));\n/// assert_eq!(one_of::<_, _, (&str, ErrorKind)>(\"a\")(\"\"), Err(Err::Error((\"\", ErrorKind::OneOf))));\n/// ```\npub fn one_of>(list: T) -> impl FnMut(I) -> IResult\nwhere\n I: Input,\n ::Item: AsChar,\n T: FindToken,\n{\n let mut parser = super::one_of(list);\n move |i: I| parser.process::>(i)\n}\n\n/// Recognizes a character that is not in the provided characters.\n///\n/// *Complete version*: Will return an error if there's not enough input data.\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind};\n/// # use nom::character::complete::none_of;\n/// assert_eq!(none_of::<_, _, (&str, ErrorKind)>(\"abc\")(\"z\"), Ok((\"\", 'z')));\n/// assert_eq!(none_of::<_, _, (&str, ErrorKind)>(\"ab\")(\"a\"), Err(Err::Error((\"a\", ErrorKind::NoneOf))));\n/// assert_eq!(none_of::<_, _, (&str, ErrorKind)>(\"a\")(\"\"), Err(Err::Error((\"\", ErrorKind::NoneOf))));\n/// ```\npub fn none_of>(list: T) -> impl FnMut(I) -> IResult\nwhere\n I: Input,\n ::Item: AsChar,\n T: FindToken,\n{\n let mut parser = super::none_of(list);\n move |i: I| parser.process::>(i)\n}\n\n/// Recognizes the string \"\\r\\n\".\n///\n/// *Complete version*: Will return an error if there's not enough input data.\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult};\n/// # use nom::character::complete::crlf;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// crlf(input)\n/// }\n///\n/// assert_eq!(parser(\"\\r\\nc\"), Ok((\"c\", \"\\r\\n\")));\n/// assert_eq!(parser(\"ab\\r\\nc\"), Err(Err::Error(Error::new(\"ab\\r\\nc\", ErrorKind::CrLf))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::CrLf))));\n/// ```\npub fn crlf>(input: T) -> IResult\nwhere\n T: Input,\n T: Compare<&'static str>,\n{\n match input.compare(\"\\r\\n\") {\n CompareResult::Ok => Ok(input.take_split(2)),\n _ => {\n let e: ErrorKind = ErrorKind::CrLf;\n Err(Err::Error(E::from_error_kind(input, e)))\n }\n }\n}\n\n//FIXME: there's still an incomplete\n/// Recognizes a string of any char except '\\r\\n' or '\\n'.\n///\n/// *Complete version*: Will return an error if there's not enough input data.\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Needed};\n/// # use nom::character::complete::not_line_ending;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// not_line_ending(input)\n/// }\n///\n/// assert_eq!(parser(\"ab\\r\\nc\"), Ok((\"\\r\\nc\", \"ab\")));\n/// assert_eq!(parser(\"ab\\nc\"), Ok((\"\\nc\", \"ab\")));\n/// assert_eq!(parser(\"abc\"), Ok((\"\", \"abc\")));\n/// assert_eq!(parser(\"\"), Ok((\"\", \"\")));\n/// assert_eq!(parser(\"a\\rb\\nc\"), Err(Err::Error(Error { input: \"a\\rb\\nc\", code: ErrorKind::Tag })));\n/// assert_eq!(parser(\"a\\rbc\"), Err(Err::Error(Error { input: \"a\\rbc\", code: ErrorKind::Tag })));\n/// ```\npub fn not_line_ending>(input: T) -> IResult\nwhere\n T: Input,\n T: Compare<&'static str>,\n ::Item: AsChar,\n{\n match input.position(|item| {\n let c = item.as_char();\n c == '\\r' || c == '\\n'\n }) {\n None => Ok(input.take_split(input.input_len())),\n Some(index) => {\n let mut it = input.take_from(index).iter_elements();\n let nth = it.next().unwrap().as_char();\n if nth == '\\r' {\n let sliced = input.take_from(index);\n let comp = sliced.compare(\"\\r\\n\");\n match comp {\n //FIXME: calculate the right index\n CompareResult::Ok => Ok(input.take_split(index)),\n _ => {\n let e: ErrorKind = ErrorKind::Tag;\n Err(Err::Error(E::from_error_kind(input, e)))\n }\n }\n } else {\n Ok(input.take_split(index))\n }\n }\n }\n}\n\n/// Recognizes an end of line (both '\\n' and '\\r\\n').\n///\n/// *Complete version*: Will return an error if there's not enough input data.\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Needed};\n/// # use nom::character::complete::line_ending;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// line_ending(input)\n/// }\n///\n/// assert_eq!(parser(\"\\r\\nc\"), Ok((\"c\", \"\\r\\n\")));\n/// assert_eq!(parser(\"ab\\r\\nc\"), Err(Err::Error(Error::new(\"ab\\r\\nc\", ErrorKind::CrLf))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::CrLf))));\n/// ```\npub fn line_ending>(input: T) -> IResult\nwhere\n T: Input,\n T: Compare<&'static str>,\n{\n match input.compare(\"\\n\") {\n CompareResult::Ok => Ok(input.take_split(1)),\n CompareResult::Incomplete => Err(Err::Error(E::from_error_kind(input, ErrorKind::CrLf))),\n CompareResult::Error => match input.compare(\"\\r\\n\") {\n CompareResult::Ok => Ok(input.take_split(2)),\n _ => Err(Err::Error(E::from_error_kind(input, ErrorKind::CrLf))),\n },\n }\n}\n\n/// Matches a newline character '\\n'.\n///\n/// *Complete version*: Will return an error if there's not enough input data.\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Needed};\n/// # use nom::character::complete::newline;\n/// fn parser(input: &str) -> IResult<&str, char> {\n/// newline(input)\n/// }\n///\n/// assert_eq!(parser(\"\\nc\"), Ok((\"c\", '\\n')));\n/// assert_eq!(parser(\"\\r\\nc\"), Err(Err::Error(Error::new(\"\\r\\nc\", ErrorKind::Char))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Char))));\n/// ```\npub fn newline>(input: I) -> IResult\nwhere\n I: Input,\n ::Item: AsChar,\n{\n char('\\n')(input)\n}\n\n/// Matches a tab character '\\t'.\n///\n/// *Complete version*: Will return an error if there's not enough input data.\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Needed};\n/// # use nom::character::complete::tab;\n/// fn parser(input: &str) -> IResult<&str, char> {\n/// tab(input)\n/// }\n///\n/// assert_eq!(parser(\"\\tc\"), Ok((\"c\", '\\t')));\n/// assert_eq!(parser(\"\\r\\nc\"), Err(Err::Error(Error::new(\"\\r\\nc\", ErrorKind::Char))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Char))));\n/// ```\npub fn tab>(input: I) -> IResult\nwhere\n I: Input,\n ::Item: AsChar,\n{\n char('\\t')(input)\n}\n\n/// Matches one byte as a character. Note that the input type will\n/// accept a `str`, but not a `&[u8]`, unlike many other nom parsers.\n///\n/// *Complete version*: Will return an error if there's not enough input data.\n/// # Example\n///\n/// ```\n/// # use nom::{character::complete::anychar, Err, error::{Error, ErrorKind}, IResult};\n/// fn parser(input: &str) -> IResult<&str, char> {\n/// anychar(input)\n/// }\n///\n/// assert_eq!(parser(\"abc\"), Ok((\"bc\",'a')));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Eof))));\n/// ```\npub fn anychar>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n let mut it = input.iter_elements();\n match it.next() {\n None => Err(Err::Error(E::from_error_kind(input, ErrorKind::Eof))),\n Some(c) => Ok((input.take_from(c.len()), c.as_char())),\n }\n}\n\n/// Recognizes zero or more lowercase and uppercase ASCII alphabetic characters: a-z, A-Z\n///\n/// *Complete version*: Will return the whole input if no terminating token is found (a non\n/// alphabetic character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind, IResult, Needed};\n/// # use nom::character::complete::alpha0;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// alpha0(input)\n/// }\n///\n/// assert_eq!(parser(\"ab1c\"), Ok((\"1c\", \"ab\")));\n/// assert_eq!(parser(\"1c\"), Ok((\"1c\", \"\")));\n/// assert_eq!(parser(\"\"), Ok((\"\", \"\")));\n/// ```\npub fn alpha0>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position_complete(|item| !item.is_alpha())\n}\n\n/// Recognizes one or more lowercase and uppercase ASCII alphabetic characters: a-z, A-Z\n///\n/// *Complete version*: Will return an error if there's not enough input data,\n/// or the whole input if no terminating token is found (a non alphabetic character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Needed};\n/// # use nom::character::complete::alpha1;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// alpha1(input)\n/// }\n///\n/// assert_eq!(parser(\"aB1c\"), Ok((\"1c\", \"aB\")));\n/// assert_eq!(parser(\"1c\"), Err(Err::Error(Error::new(\"1c\", ErrorKind::Alpha))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Alpha))));\n/// ```\npub fn alpha1>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position1_complete(|item| !item.is_alpha(), ErrorKind::Alpha)\n}\n\n/// Recognizes zero or more ASCII numerical characters: 0-9\n///\n/// *Complete version*: Will return an error if there's not enough input data,\n/// or the whole input if no terminating token is found (a non digit character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind, IResult, Needed};\n/// # use nom::character::complete::digit0;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// digit0(input)\n/// }\n///\n/// assert_eq!(parser(\"21c\"), Ok((\"c\", \"21\")));\n/// assert_eq!(parser(\"21\"), Ok((\"\", \"21\")));\n/// assert_eq!(parser(\"a21c\"), Ok((\"a21c\", \"\")));\n/// assert_eq!(parser(\"\"), Ok((\"\", \"\")));\n/// ```\npub fn digit0>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position_complete(|item| !item.is_dec_digit())\n}\n\n/// Recognizes one or more ASCII numerical characters: 0-9\n///\n/// *Complete version*: Will return an error if there's not enough input data,\n/// or the whole input if no terminating token is found (a non digit character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Needed};\n/// # use nom::character::complete::digit1;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// digit1(input)\n/// }\n///\n/// assert_eq!(parser(\"21c\"), Ok((\"c\", \"21\")));\n/// assert_eq!(parser(\"c1\"), Err(Err::Error(Error::new(\"c1\", ErrorKind::Digit))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Digit))));\n/// ```\n///\n/// ## Parsing an integer\n/// You can use `digit1` in combination with [`map_res`] to parse an integer:\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Needed, Parser};\n/// # use nom::combinator::map_res;\n/// # use nom::character::complete::digit1;\n/// fn parser(input: &str) -> IResult<&str, u32> {\n/// map_res(digit1, str::parse).parse(input)\n/// }\n///\n/// assert_eq!(parser(\"416\"), Ok((\"\", 416)));\n/// assert_eq!(parser(\"12b\"), Ok((\"b\", 12)));\n/// assert!(parser(\"b\").is_err());\n/// ```\n///\n/// [`map_res`]: crate::combinator::map_res\npub fn digit1>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position1_complete(|item| !item.is_dec_digit(), ErrorKind::Digit)\n}\n\n/// Recognizes zero or more ASCII hexadecimal numerical characters: 0-9, A-F, a-f\n///\n/// *Complete version*: Will return the whole input if no terminating token is found (a non hexadecimal digit character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind, IResult, Needed};\n/// # use nom::character::complete::hex_digit0;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// hex_digit0(input)\n/// }\n///\n/// assert_eq!(parser(\"21cZ\"), Ok((\"Z\", \"21c\")));\n/// assert_eq!(parser(\"Z21c\"), Ok((\"Z21c\", \"\")));\n/// assert_eq!(parser(\"\"), Ok((\"\", \"\")));\n/// ```\npub fn hex_digit0>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position_complete(|item| !item.is_hex_digit())\n}\n/// Recognizes one or more ASCII hexadecimal numerical characters: 0-9, A-F, a-f\n///\n/// *Complete version*: Will return an error if there's not enough input data,\n/// or the whole input if no terminating token is found (a non hexadecimal digit character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Needed};\n/// # use nom::character::complete::hex_digit1;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// hex_digit1(input)\n/// }\n///\n/// assert_eq!(parser(\"21cZ\"), Ok((\"Z\", \"21c\")));\n/// assert_eq!(parser(\"H2\"), Err(Err::Error(Error::new(\"H2\", ErrorKind::HexDigit))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::HexDigit))));\n/// ```\npub fn hex_digit1>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position1_complete(|item| !item.is_hex_digit(), ErrorKind::HexDigit)\n}\n\n/// Recognizes zero or more octal characters: 0-7\n///\n/// *Complete version*: Will return the whole input if no terminating token is found (a non octal\n/// digit character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind, IResult, Needed};\n/// # use nom::character::complete::oct_digit0;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// oct_digit0(input)\n/// }\n///\n/// assert_eq!(parser(\"21cZ\"), Ok((\"cZ\", \"21\")));\n/// assert_eq!(parser(\"Z21c\"), Ok((\"Z21c\", \"\")));\n/// assert_eq!(parser(\"\"), Ok((\"\", \"\")));\n/// ```\npub fn oct_digit0>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position_complete(|item| !item.is_oct_digit())\n}\n\n/// Recognizes one or more octal characters: 0-7\n///\n/// *Complete version*: Will return an error if there's not enough input data,\n/// or the whole input if no terminating token is found (a non octal digit character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Needed};\n/// # use nom::character::complete::oct_digit1;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// oct_digit1(input)\n/// }\n///\n/// assert_eq!(parser(\"21cZ\"), Ok((\"cZ\", \"21\")));\n/// assert_eq!(parser(\"H2\"), Err(Err::Error(Error::new(\"H2\", ErrorKind::OctDigit))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::OctDigit))));\n/// ```\npub fn oct_digit1>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position1_complete(|item| !item.is_oct_digit(), ErrorKind::OctDigit)\n}\n\n/// Recognizes zero or more binary characters: 0-1\n///\n/// *Complete version*: Will return the whole input if no terminating token is found (a non binary\n/// digit character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind, IResult, Needed};\n/// # use nom::character::complete::bin_digit0;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// bin_digit0(input)\n/// }\n///\n/// assert_eq!(parser(\"013a\"), Ok((\"3a\", \"01\")));\n/// assert_eq!(parser(\"a013\"), Ok((\"a013\", \"\")));\n/// assert_eq!(parser(\"\"), Ok((\"\", \"\")));\n/// ```\npub fn bin_digit0>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position_complete(|item| !item.is_bin_digit())\n}\n\n/// Recognizes one or more binary characters: 0-1\n///\n/// *Complete version*: Will return an error if there's not enough input data,\n/// or the whole input if no terminating token is found (a non binary digit character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Needed};\n/// # use nom::character::complete::bin_digit1;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// bin_digit1(input)\n/// }\n///\n/// assert_eq!(parser(\"013a\"), Ok((\"3a\", \"01\")));\n/// assert_eq!(parser(\"a013\"), Err(Err::Error(Error::new(\"a013\", ErrorKind::BinDigit))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::BinDigit))));\n/// ```\npub fn bin_digit1>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position1_complete(|item| !item.is_bin_digit(), ErrorKind::BinDigit)\n}\n\n/// Recognizes zero or more ASCII numerical and alphabetic characters: 0-9, a-z, A-Z\n///\n/// *Complete version*: Will return the whole input if no terminating token is found (a non\n/// alphanumerical character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind, IResult, Needed};\n/// # use nom::character::complete::alphanumeric0;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// alphanumeric0(input)\n/// }\n///\n/// assert_eq!(parser(\"21cZ%1\"), Ok((\"%1\", \"21cZ\")));\n/// assert_eq!(parser(\"&Z21c\"), Ok((\"&Z21c\", \"\")));\n/// assert_eq!(parser(\"\"), Ok((\"\", \"\")));\n/// ```\npub fn alphanumeric0>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position_complete(|item| !item.is_alphanum())\n}\n\n/// Recognizes one or more ASCII numerical and alphabetic characters: 0-9, a-z, A-Z\n///\n/// *Complete version*: Will return an error if there's not enough input data,\n/// or the whole input if no terminating token is found (a non alphanumerical character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Needed};\n/// # use nom::character::complete::alphanumeric1;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// alphanumeric1(input)\n/// }\n///\n/// assert_eq!(parser(\"21cZ%1\"), Ok((\"%1\", \"21cZ\")));\n/// assert_eq!(parser(\"&H2\"), Err(Err::Error(Error::new(\"&H2\", ErrorKind::AlphaNumeric))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::AlphaNumeric))));\n/// ```\npub fn alphanumeric1>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position1_complete(|item| !item.is_alphanum(), ErrorKind::AlphaNumeric)\n}\n\n/// Recognizes zero or more spaces and tabs.\n///\n/// *Complete version*: Will return the whole input if no terminating token is found (a non space\n/// character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind, IResult, Needed};\n/// # use nom::character::complete::space0;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// space0(input)\n/// }\n///\n/// assert_eq!(parser(\" \\t21c\"), Ok((\"21c\", \" \\t\")));\n/// assert_eq!(parser(\"Z21c\"), Ok((\"Z21c\", \"\")));\n/// assert_eq!(parser(\"\"), Ok((\"\", \"\")));\n/// ```\npub fn space0>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar + Clone,\n{\n input.split_at_position_complete(|item| {\n let c = item.as_char();\n !(c == ' ' || c == '\\t')\n })\n}\n\n/// Recognizes one or more spaces and tabs.\n///\n/// *Complete version*: Will return an error if there's not enough input data,\n/// or the whole input if no terminating token is found (a non space character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Needed};\n/// # use nom::character::complete::space1;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// space1(input)\n/// }\n///\n/// assert_eq!(parser(\" \\t21c\"), Ok((\"21c\", \" \\t\")));\n/// assert_eq!(parser(\"H2\"), Err(Err::Error(Error::new(\"H2\", ErrorKind::Space))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Space))));\n/// ```\npub fn space1>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position1_complete(\n |item| {\n let c = item.as_char();\n !(c == ' ' || c == '\\t')\n },\n ErrorKind::Space,\n )\n}\n\n/// Recognizes zero or more spaces, tabs, carriage returns and line feeds.\n///\n/// *Complete version*: will return the whole input if no terminating token is found (a non space\n/// character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::ErrorKind, IResult, Needed};\n/// # use nom::character::complete::multispace0;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// multispace0(input)\n/// }\n///\n/// assert_eq!(parser(\" \\t\\n\\r21c\"), Ok((\"21c\", \" \\t\\n\\r\")));\n/// assert_eq!(parser(\"Z21c\"), Ok((\"Z21c\", \"\")));\n/// assert_eq!(parser(\"\"), Ok((\"\", \"\")));\n/// ```\npub fn multispace0>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position_complete(|item| {\n let c = item.as_char();\n !(c == ' ' || c == '\\t' || c == '\\r' || c == '\\n')\n })\n}\n\n/// Recognizes one or more spaces, tabs, carriage returns and line feeds.\n///\n/// *Complete version*: will return an error if there's not enough input data,\n/// or the whole input if no terminating token is found (a non space character).\n/// # Example\n///\n/// ```\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Needed};\n/// # use nom::character::complete::multispace1;\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// multispace1(input)\n/// }\n///\n/// assert_eq!(parser(\" \\t\\n\\r21c\"), Ok((\"21c\", \" \\t\\n\\r\")));\n/// assert_eq!(parser(\"H2\"), Err(Err::Error(Error::new(\"H2\", ErrorKind::MultiSpace))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::MultiSpace))));\n/// ```\npub fn multispace1>(input: T) -> IResult\nwhere\n T: Input,\n ::Item: AsChar,\n{\n input.split_at_position1_complete(\n |item| {\n let c = item.as_char();\n !(c == ' ' || c == '\\t' || c == '\\r' || c == '\\n')\n },\n ErrorKind::MultiSpace,\n )\n}\n\npub(crate) fn sign>(input: T) -> IResult\nwhere\n T: Clone + Input,\n T: for<'a> Compare<&'a [u8]>,\n{\n use crate::bytes::complete::tag;\n use crate::combinator::value;\n\n let (i, opt_sign) = opt(alt((\n value(false, tag(&b\"-\"[..])),\n value(true, tag(&b\"+\"[..])),\n )))\n .parse(input)?;\n let sign = opt_sign.unwrap_or(true);\n\n Ok((i, sign))\n}\n\n#[doc(hidden)]\nmacro_rules! ints {\n ($($t:tt)+) => {\n $(\n /// will parse a number in text form to a number\n ///\n /// *Complete version*: can parse until the end of input.\n pub fn $t>(input: T) -> IResult\n where\n T: Input + Clone,\n ::Item: AsChar,\n T: for <'a> Compare<&'a[u8]>,\n {\n let (i, sign) = sign(input.clone())?;\n\n if i.input_len() == 0 {\n return Err(Err::Error(E::from_error_kind(input, ErrorKind::Digit)));\n }\n\n let mut value: $t = 0;\n if sign {\n let mut pos = 0;\n for c in i.iter_elements() {\n match c.as_char().to_digit(10) {\n None => {\n if pos == 0 {\n return Err(Err::Error(E::from_error_kind(input, ErrorKind::Digit)));\n } else {\n return Ok((i.take_from(pos), value));\n }\n },\n Some(d) => match value.checked_mul(10).and_then(|v| v.checked_add(d as $t)) {\n None => return Err(Err::Error(E::from_error_kind(input, ErrorKind::Digit))),\n Some(v) => {\n pos += c.len();\n value = v;\n },\n }\n }\n }\n } else {\n let mut pos = 0;\n for c in i.iter_elements() {\n match c.as_char().to_digit(10) {\n None => {\n if pos == 0 {\n return Err(Err::Error(E::from_error_kind(input, ErrorKind::Digit)));\n } else {\n return Ok((i.take_from(pos), value));\n }\n },\n Some(d) => match value.checked_mul(10).and_then(|v| v.checked_sub(d as $t)) {\n None => return Err(Err::Error(E::from_error_kind(input, ErrorKind::Digit))),\n Some(v) => {\n pos += c.len();\n value = v;\n },\n }\n }\n }\n }\n\n Ok((i.take_from(i.input_len()), value))\n }\n )+\n }\n}\n\nints! { i8 i16 i32 i64 i128 isize }\n\n#[doc(hidden)]\nmacro_rules! uints {\n ($($t:tt)+) => {\n $(\n /// will parse a number in text form to a number\n ///\n /// *Complete version*: can parse until the end of input.\n pub fn $t>(input: T) -> IResult\n where\n T: Input ,\n ::Item: AsChar,\n {\n let i = input;\n\n if i.input_len() == 0 {\n return Err(Err::Error(E::from_error_kind(i, ErrorKind::Digit)));\n }\n\n let mut value: $t = 0;\n let mut pos = 0;\n for c in i.iter_elements() {\n match c.as_char().to_digit(10) {\n None => {\n if pos == 0 {\n return Err(Err::Error(E::from_error_kind(i, ErrorKind::Digit)));\n } else {\n return Ok((i.take_from(pos), value));\n }\n },\n Some(d) => match value.checked_mul(10).and_then(|v| v.checked_add(d as $t)) {\n None => return Err(Err::Error(E::from_error_kind(i, ErrorKind::Digit))),\n Some(v) => {\n pos += c.len();\n value = v;\n },\n }\n }\n }\n\n Ok((i.take_from(i.input_len()), value))\n }\n )+\n }\n}\n\nuints! { u8 u16 u32 u64 u128 usize }\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use crate::internal::Err;\n use crate::traits::ParseTo;\n use crate::Parser;\n use proptest::prelude::*;\n\n macro_rules! assert_parse(\n ($left: expr, $right: expr) => {\n let res: $crate::IResult<_, _, (_, ErrorKind)> = $left;\n assert_eq!(res, $right);\n };\n );\n\n #[test]\n fn character() {\n let empty: &[u8] = b\"\";\n let a: &[u8] = b\"abcd\";\n let b: &[u8] = b\"1234\";\n let c: &[u8] = b\"a123\";\n let d: &[u8] = \"az\u00e912\".as_bytes();\n let e: &[u8] = b\" \";\n let f: &[u8] = b\" ;\";\n //assert_eq!(alpha1::<_, (_, ErrorKind)>(a), Err(Err::Incomplete(Needed::Size(1))));\n assert_parse!(alpha1(a), Ok((empty, a)));\n assert_eq!(alpha1(b), Err(Err::Error((b, ErrorKind::Alpha))));\n assert_eq!(alpha1::<_, (_, ErrorKind)>(c), Ok((&c[1..], &b\"a\"[..])));\n assert_eq!(\n alpha1::<_, (_, ErrorKind)>(d),\n Ok((\"\u00e912\".as_bytes(), &b\"az\"[..]))\n );\n assert_eq!(digit1(a), Err(Err::Error((a, ErrorKind::Digit))));\n assert_eq!(digit1::<_, (_, ErrorKind)>(b), Ok((empty, b)));\n assert_eq!(digit1(c), Err(Err::Error((c, ErrorKind::Digit))));\n assert_eq!(digit1(d), Err(Err::Error((d, ErrorKind::Digit))));\n assert_eq!(hex_digit1::<_, (_, ErrorKind)>(a), Ok((empty, a)));\n assert_eq!(hex_digit1::<_, (_, ErrorKind)>(b), Ok((empty, b)));\n assert_eq!(hex_digit1::<_, (_, ErrorKind)>(c), Ok((empty, c)));\n assert_eq!(\n hex_digit1::<_, (_, ErrorKind)>(d),\n Ok((\"z\u00e912\".as_bytes(), &b\"a\"[..]))\n );\n assert_eq!(hex_digit1(e), Err(Err::Error((e, ErrorKind::HexDigit))));\n assert_eq!(oct_digit1(a), Err(Err::Error((a, ErrorKind::OctDigit))));\n assert_eq!(oct_digit1::<_, (_, ErrorKind)>(b), Ok((empty, b)));\n assert_eq!(oct_digit1(c), Err(Err::Error((c, ErrorKind::OctDigit))));\n assert_eq!(oct_digit1(d), Err(Err::Error((d, ErrorKind::OctDigit))));\n assert_eq!(bin_digit1(a), Err(Err::Error((a, ErrorKind::BinDigit))));\n assert_eq!(\n bin_digit1::<_, (_, ErrorKind)>(b),\n Ok((&b\"234\"[..], &b\"1\"[..]))\n );\n assert_eq!(bin_digit1(c), Err(Err::Error((c, ErrorKind::BinDigit))));\n assert_eq!(bin_digit1(d), Err(Err::Error((d, ErrorKind::BinDigit))));\n assert_eq!(alphanumeric1::<_, (_, ErrorKind)>(a), Ok((empty, a)));\n //assert_eq!(fix_error!(b,(), alphanumeric), Ok((empty, b)));\n assert_eq!(alphanumeric1::<_, (_, ErrorKind)>(c), Ok((empty, c)));\n assert_eq!(\n alphanumeric1::<_, (_, ErrorKind)>(d),\n Ok((\"\u00e912\".as_bytes(), &b\"az\"[..]))\n );\n assert_eq!(space1::<_, (_, ErrorKind)>(e), Ok((empty, e)));\n assert_eq!(space1::<_, (_, ErrorKind)>(f), Ok((&b\";\"[..], &b\" \"[..])));\n }\n\n #[cfg(feature = \"alloc\")]\n #[test]\n fn character_s() {\n let empty = \"\";\n let a = \"abcd\";\n let b = \"1234\";\n let c = \"a123\";\n let d = \"az\u00e912\";\n let e = \" \";\n assert_eq!(alpha1::<_, (_, ErrorKind)>(a), Ok((empty, a)));\n assert_eq!(alpha1(b), Err(Err::Error((b, ErrorKind::Alpha))));\n assert_eq!(alpha1::<_, (_, ErrorKind)>(c), Ok((&c[1..], \"a\")));\n assert_eq!(alpha1::<_, (_, ErrorKind)>(d), Ok((\"\u00e912\", \"az\")));\n assert_eq!(digit1(a), Err(Err::Error((a, ErrorKind::Digit))));\n assert_eq!(digit1::<_, (_, ErrorKind)>(b), Ok((empty, b)));\n assert_eq!(digit1(c), Err(Err::Error((c, ErrorKind::Digit))));\n assert_eq!(digit1(d), Err(Err::Error((d, ErrorKind::Digit))));\n assert_eq!(hex_digit1::<_, (_, ErrorKind)>(a), Ok((empty, a)));\n assert_eq!(hex_digit1::<_, (_, ErrorKind)>(b), Ok((empty, b)));\n assert_eq!(hex_digit1::<_, (_, ErrorKind)>(c), Ok((empty, c)));\n assert_eq!(hex_digit1::<_, (_, ErrorKind)>(d), Ok((\"z\u00e912\", \"a\")));\n assert_eq!(hex_digit1(e), Err(Err::Error((e, ErrorKind::HexDigit))));\n assert_eq!(oct_digit1(a), Err(Err::Error((a, ErrorKind::OctDigit))));\n assert_eq!(oct_digit1::<_, (_, ErrorKind)>(b), Ok((empty, b)));\n assert_eq!(oct_digit1(c), Err(Err::Error((c, ErrorKind::OctDigit))));\n assert_eq!(oct_digit1(d), Err(Err::Error((d, ErrorKind::OctDigit))));\n assert_eq!(bin_digit1(a), Err(Err::Error((a, ErrorKind::BinDigit))));\n assert_eq!(bin_digit1::<_, (_, ErrorKind)>(b), Ok((\"234\", \"1\")));\n assert_eq!(bin_digit1(c), Err(Err::Error((c, ErrorKind::BinDigit))));\n assert_eq!(bin_digit1(d), Err(Err::Error((d, ErrorKind::BinDigit))));\n assert_eq!(alphanumeric1::<_, (_, ErrorKind)>(a), Ok((empty, a)));\n //assert_eq!(fix_error!(b,(), alphanumeric), Ok((empty, b)));\n assert_eq!(alphanumeric1::<_, (_, ErrorKind)>(c), Ok((empty, c)));\n assert_eq!(alphanumeric1::<_, (_, ErrorKind)>(d), Ok((\"\u00e912\", \"az\")));\n assert_eq!(space1::<_, (_, ErrorKind)>(e), Ok((empty, e)));\n }\n\n use crate::traits::Offset;\n #[test]\n fn offset() {\n let a = &b\"abcd;\"[..];\n let b = &b\"1234;\"[..];\n let c = &b\"a123;\"[..];\n let d = &b\" \\t;\"[..];\n let e = &b\" \\t\\r\\n;\"[..];\n let f = &b\"123abcDEF;\"[..];\n\n match alpha1::<_, (_, ErrorKind)>(a) {\n Ok((i, _)) => {\n assert_eq!(a.offset(i) + i.len(), a.len());\n }\n _ => panic!(\"wrong return type in offset test for alpha\"),\n }\n match digit1::<_, (_, ErrorKind)>(b) {\n Ok((i, _)) => {\n assert_eq!(b.offset(i) + i.len(), b.len());\n }\n _ => panic!(\"wrong return type in offset test for digit\"),\n }\n match alphanumeric1::<_, (_, ErrorKind)>(c) {\n Ok((i, _)) => {\n assert_eq!(c.offset(i) + i.len(), c.len());\n }\n _ => panic!(\"wrong return type in offset test for alphanumeric\"),\n }\n match space1::<_, (_, ErrorKind)>(d) {\n Ok((i, _)) => {\n assert_eq!(d.offset(i) + i.len(), d.len());\n }\n _ => panic!(\"wrong return type in offset test for space\"),\n }\n match multispace1::<_, (_, ErrorKind)>(e) {\n Ok((i, _)) => {\n assert_eq!(e.offset(i) + i.len(), e.len());\n }\n _ => panic!(\"wrong return type in offset test for multispace\"),\n }\n match hex_digit1::<_, (_, ErrorKind)>(f) {\n Ok((i, _)) => {\n assert_eq!(f.offset(i) + i.len(), f.len());\n }\n _ => panic!(\"wrong return type in offset test for hex_digit\"),\n }\n match oct_digit1::<_, (_, ErrorKind)>(f) {\n Ok((i, _)) => {\n assert_eq!(f.offset(i) + i.len(), f.len());\n }\n _ => panic!(\"wrong return type in offset test for oct_digit\"),\n }\n match bin_digit1::<_, (_, ErrorKind)>(f) {\n Ok((i, _)) => {\n assert_eq!(f.offset(i) + i.len(), f.len());\n }\n _ => panic!(\"wrong return type in offset test for bin_digit\"),\n }\n }\n\n #[test]\n fn is_not_line_ending_bytes() {\n let a: &[u8] = b\"ab12cd\\nefgh\";\n assert_eq!(\n not_line_ending::<_, (_, ErrorKind)>(a),\n Ok((&b\"\\nefgh\"[..], &b\"ab12cd\"[..]))\n );\n\n let b: &[u8] = b\"ab12cd\\nefgh\\nijkl\";\n assert_eq!(\n not_line_ending::<_, (_, ErrorKind)>(b),\n Ok((&b\"\\nefgh\\nijkl\"[..], &b\"ab12cd\"[..]))\n );\n\n let c: &[u8] = b\"ab12cd\\r\\nefgh\\nijkl\";\n assert_eq!(\n not_line_ending::<_, (_, ErrorKind)>(c),\n Ok((&b\"\\r\\nefgh\\nijkl\"[..], &b\"ab12cd\"[..]))\n );\n\n let d: &[u8] = b\"ab12cd\";\n assert_eq!(not_line_ending::<_, (_, ErrorKind)>(d), Ok((&[][..], d)));\n }\n\n #[test]\n fn is_not_line_ending_str() {\n let a: &str = \"ab12cd\\nefgh\";\n assert_eq!(not_line_ending(a), Ok((&\"\\nefgh\"[..], &\"ab12cd\"[..])));\n\n let b: &str = \"ab12cd\\nefgh\\nijkl\";\n assert_eq!(not_line_ending(b), Ok((&\"\\nefgh\\nijkl\"[..], &\"ab12cd\"[..])));\n\n let c: &str = \"ab12cd\\r\\nefgh\\nijkl\";\n assert_eq!(not_line_ending(c), Ok((&\"\\r\\nefgh\\nijkl\"[..], &\"ab12cd\"[..])));\n\n let d = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\\n\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n assert_eq!(not_line_ending(d), Ok((&\"\\n\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\"[..], &\"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\"[..])));\n\n let e = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\\r\\n\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n assert_eq!(not_line_ending(e), Ok((&\"\\r\\n\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\"[..], &\"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\"[..])));\n\n let f = \"\u03b2\u00e8\u0192\u00f4\u0159\u00e8\\r\u00c2\u00df\u00c7\u00e1\u0192\u01ad\u00e8\u0159\";\n assert_eq!(not_line_ending(f), Err(Err::Error((f, ErrorKind::Tag))));\n\n let g2: &str = \"ab12cd\";\n assert_eq!(not_line_ending::<_, (_, ErrorKind)>(g2), Ok((\"\", g2)));\n }\n\n #[test]\n fn hex_digit_test() {\n let i = &b\"0123456789abcdefABCDEF;\"[..];\n assert_parse!(hex_digit1(i), Ok((&b\";\"[..], &i[..i.len() - 1])));\n\n let i = &b\"g\"[..];\n assert_parse!(\n hex_digit1(i),\n Err(Err::Error(error_position!(i, ErrorKind::HexDigit)))\n );\n\n let i = &b\"G\"[..];\n assert_parse!(\n hex_digit1(i),\n Err(Err::Error(error_position!(i, ErrorKind::HexDigit)))\n );\n\n assert!(AsChar::is_hex_digit(b'0'));\n assert!(AsChar::is_hex_digit(b'9'));\n assert!(AsChar::is_hex_digit(b'a'));\n assert!(AsChar::is_hex_digit(b'f'));\n assert!(AsChar::is_hex_digit(b'A'));\n assert!(AsChar::is_hex_digit(b'F'));\n assert!(!AsChar::is_hex_digit(b'g'));\n assert!(!AsChar::is_hex_digit(b'G'));\n assert!(!AsChar::is_hex_digit(b'/'));\n assert!(!AsChar::is_hex_digit(b':'));\n assert!(!AsChar::is_hex_digit(b'@'));\n assert!(!AsChar::is_hex_digit(b'\\x60'));\n }\n\n #[test]\n fn oct_digit_test() {\n let i = &b\"01234567;\"[..];\n assert_parse!(oct_digit1(i), Ok((&b\";\"[..], &i[..i.len() - 1])));\n\n let i = &b\"8\"[..];\n assert_parse!(\n oct_digit1(i),\n Err(Err::Error(error_position!(i, ErrorKind::OctDigit)))\n );\n\n assert!(AsChar::is_oct_digit(b'0'));\n assert!(AsChar::is_oct_digit(b'7'));\n assert!(!AsChar::is_oct_digit(b'8'));\n assert!(!AsChar::is_oct_digit(b'9'));\n assert!(!AsChar::is_oct_digit(b'a'));\n assert!(!AsChar::is_oct_digit(b'A'));\n assert!(!AsChar::is_oct_digit(b'/'));\n assert!(!AsChar::is_oct_digit(b':'));\n assert!(!AsChar::is_oct_digit(b'@'));\n assert!(!AsChar::is_oct_digit(b'\\x60'));\n }\n\n #[test]\n fn bin_digit_test() {\n let i = &b\"101010;\"[..];\n assert_parse!(bin_digit1(i), Ok((&b\";\"[..], &i[..i.len() - 1])));\n\n let i = &b\"2\"[..];\n assert_parse!(\n bin_digit1(i),\n Err(Err::Error(error_position!(i, ErrorKind::BinDigit)))\n );\n\n assert!(crate::character::is_bin_digit(b'0'));\n assert!(crate::character::is_bin_digit(b'1'));\n assert!(!crate::character::is_bin_digit(b'8'));\n assert!(!crate::character::is_bin_digit(b'9'));\n assert!(!crate::character::is_bin_digit(b'a'));\n assert!(!crate::character::is_bin_digit(b'A'));\n assert!(!crate::character::is_bin_digit(b'/'));\n assert!(!crate::character::is_bin_digit(b':'));\n assert!(!crate::character::is_bin_digit(b'@'));\n assert!(!crate::character::is_bin_digit(b'\\x60'));\n }\n\n #[test]\n fn full_line_windows() {\n use crate::sequence::pair;\n fn take_full_line(i: &[u8]) -> IResult<&[u8], (&[u8], &[u8])> {\n pair(not_line_ending, line_ending).parse(i)\n }\n let input = b\"abc\\r\\n\";\n let output = take_full_line(input);\n assert_eq!(output, Ok((&b\"\"[..], (&b\"abc\"[..], &b\"\\r\\n\"[..]))));\n }\n\n #[test]\n fn full_line_unix() {\n use crate::sequence::pair;\n fn take_full_line(i: &[u8]) -> IResult<&[u8], (&[u8], &[u8])> {\n pair(not_line_ending, line_ending).parse(i)\n }\n let input = b\"abc\\n\";\n let output = take_full_line(input);\n assert_eq!(output, Ok((&b\"\"[..], (&b\"abc\"[..], &b\"\\n\"[..]))));\n }\n\n #[test]\n fn check_windows_lineending() {\n let input = b\"\\r\\n\";\n let output = line_ending(&input[..]);\n assert_parse!(output, Ok((&b\"\"[..], &b\"\\r\\n\"[..])));\n }\n\n #[test]\n fn check_unix_lineending() {\n let input = b\"\\n\";\n let output = line_ending(&input[..]);\n assert_parse!(output, Ok((&b\"\"[..], &b\"\\n\"[..])));\n }\n\n #[test]\n fn cr_lf() {\n assert_parse!(crlf(&b\"\\r\\na\"[..]), Ok((&b\"a\"[..], &b\"\\r\\n\"[..])));\n assert_parse!(\n crlf(&b\"\\r\"[..]),\n Err(Err::Error(error_position!(&b\"\\r\"[..], ErrorKind::CrLf)))\n );\n assert_parse!(\n crlf(&b\"\\ra\"[..]),\n Err(Err::Error(error_position!(&b\"\\ra\"[..], ErrorKind::CrLf)))\n );\n\n assert_parse!(crlf(\"\\r\\na\"), Ok((\"a\", \"\\r\\n\")));\n assert_parse!(\n crlf(\"\\r\"),\n Err(Err::Error(error_position!(\"\\r\", ErrorKind::CrLf)))\n );\n assert_parse!(\n crlf(\"\\ra\"),\n Err(Err::Error(error_position!(\"\\ra\", ErrorKind::CrLf)))\n );\n }\n\n #[test]\n fn end_of_line() {\n assert_parse!(line_ending(&b\"\\na\"[..]), Ok((&b\"a\"[..], &b\"\\n\"[..])));\n assert_parse!(line_ending(&b\"\\r\\na\"[..]), Ok((&b\"a\"[..], &b\"\\r\\n\"[..])));\n assert_parse!(\n line_ending(&b\"\\r\"[..]),\n Err(Err::Error(error_position!(&b\"\\r\"[..], ErrorKind::CrLf)))\n );\n assert_parse!(\n line_ending(&b\"\\ra\"[..]),\n Err(Err::Error(error_position!(&b\"\\ra\"[..], ErrorKind::CrLf)))\n );\n\n assert_parse!(line_ending(\"\\na\"), Ok((\"a\", \"\\n\")));\n assert_parse!(line_ending(\"\\r\\na\"), Ok((\"a\", \"\\r\\n\")));\n assert_parse!(\n line_ending(\"\\r\"),\n Err(Err::Error(error_position!(\"\\r\", ErrorKind::CrLf)))\n );\n assert_parse!(\n line_ending(\"\\ra\"),\n Err(Err::Error(error_position!(\"\\ra\", ErrorKind::CrLf)))\n );\n }\n\n fn digit_to_i16(input: &str) -> IResult<&str, i16> {\n let i = input;\n let (i, opt_sign) = opt(alt((char('+'), char('-')))).parse(i)?;\n let sign = match opt_sign {\n Some('+') => true,\n Some('-') => false,\n _ => true,\n };\n\n let (i, s) = match digit1::<_, crate::error::Error<_>>(i) {\n Ok((i, s)) => (i, s),\n Err(_) => {\n return Err(Err::Error(crate::error::Error::from_error_kind(\n input,\n ErrorKind::Digit,\n )))\n }\n };\n\n match s.parse_to() {\n Some(n) => {\n if sign {\n Ok((i, n))\n } else {\n Ok((i, -n))\n }\n }\n None => Err(Err::Error(crate::error::Error::from_error_kind(\n i,\n ErrorKind::Digit,\n ))),\n }\n }\n\n fn digit_to_u32(i: &str) -> IResult<&str, u32> {\n let (i, s) = digit1(i)?;\n match s.parse_to() {\n Some(n) => Ok((i, n)),\n None => Err(Err::Error(crate::error::Error::from_error_kind(\n i,\n ErrorKind::Digit,\n ))),\n }\n }\n\n proptest! {\n #[test]\n fn ints(s in \"\\\\PC*\") {\n let res1 = digit_to_i16(&s);\n let res2 = i16(s.as_str());\n assert_eq!(res1, res2);\n }\n\n #[test]\n fn uints(s in \"\\\\PC*\") {\n let res1 = digit_to_u32(&s);\n let res2 = u32(s.as_str());\n assert_eq!(res1, res2);\n }\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "mod.rs", "content": "#[cfg(test)]\nmod tests;\n\nuse core::marker::PhantomData;\n\nuse crate::bytes::take;\nuse crate::error::ErrorKind;\nuse crate::error::ParseError;\nuse crate::internal::{Err, Needed, Parser};\nuse crate::lib::std::num::NonZeroUsize;\n#[cfg(feature = \"alloc\")]\nuse crate::lib::std::vec::Vec;\nuse crate::traits::ToUsize;\nuse crate::Check;\nuse crate::Emit;\nuse crate::Input;\nuse crate::Mode;\nuse crate::NomRange;\nuse crate::OutputM;\nuse crate::OutputMode;\n\n/// Don't pre-allocate more than 64KiB when calling `Vec::with_capacity`.\n///\n/// Pre-allocating memory is a nice optimization but count fields can't\n/// always be trusted. We should clamp initial capacities to some reasonable\n/// amount. This reduces the risk of a bogus count value triggering a panic\n/// due to an OOM error.\n///\n/// This does not affect correctness. Nom will always read the full number\n/// of elements regardless of the capacity cap.\n#[cfg(feature = \"alloc\")]\nconst MAX_INITIAL_CAPACITY_BYTES: usize = 65536;\n\n/// Repeats the embedded parser, gathering the results in a `Vec`.\n///\n/// This stops on [`Err::Error`] and returns the results that were accumulated. To instead chain an error up, see\n/// [`cut`][crate::combinator::cut].\n///\n/// # Arguments\n/// * `f` The parser to apply.\n///\n/// *Note*: if the parser passed in accepts empty inputs (like `alpha0` or `digit0`), `many0` will\n/// return an error, to prevent going into an infinite loop\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};\n/// use nom::multi::many0;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {\n/// many0(tag(\"abc\")).parse(s)\n/// }\n///\n/// assert_eq!(parser(\"abcabc\"), Ok((\"\", vec![\"abc\", \"abc\"])));\n/// assert_eq!(parser(\"abc123\"), Ok((\"123\", vec![\"abc\"])));\n/// assert_eq!(parser(\"123123\"), Ok((\"123123\", vec![])));\n/// assert_eq!(parser(\"\"), Ok((\"\", vec![])));\n/// ```\n#[cfg(feature = \"alloc\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\npub fn many0(\n f: F,\n) -> impl Parser>::Output>, Error = >::Error>\nwhere\n I: Clone + Input,\n F: Parser,\n{\n Many0 { parser: f }\n}\n\n#[cfg(feature = \"alloc\")]\n/// Parser implementation for the [many0] combinator\npub struct Many0 {\n parser: F,\n}\n\n#[cfg(feature = \"alloc\")]\nimpl Parser for Many0\nwhere\n I: Clone + Input,\n F: Parser,\n{\n type Output = crate::lib::std::vec::Vec<>::Output>;\n type Error = >::Error;\n\n fn process(\n &mut self,\n mut i: I,\n ) -> crate::PResult {\n let mut acc = OM::Output::bind(|| crate::lib::std::vec::Vec::with_capacity(4));\n loop {\n let len = i.input_len();\n match self\n .parser\n .process::>(i.clone())\n {\n Err(Err::Error(_)) => return Ok((i, acc)),\n Err(Err::Failure(e)) => return Err(Err::Failure(e)),\n Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),\n Ok((i1, o)) => {\n // infinite loop check: the parser must always consume\n if i1.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(i, ErrorKind::Many0)\n })));\n }\n\n i = i1;\n\n acc = OM::Output::combine(acc, o, |mut acc, o| {\n acc.push(o);\n acc\n })\n }\n }\n }\n }\n}\n\n/// Runs the embedded parser, gathering the results in a `Vec`.\n///\n/// This stops on [`Err::Error`] if there is at least one result, and returns the results that were accumulated. To instead chain an error up,\n/// see [`cut`][crate::combinator::cut].\n///\n/// # Arguments\n/// * `f` The parser to apply.\n///\n/// *Note*: If the parser passed to `many1` accepts empty inputs\n/// (like `alpha0` or `digit0`), `many1` will return an error,\n/// to prevent going into an infinite loop.\n///\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};\n/// use nom::multi::many1;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {\n/// many1(tag(\"abc\")).parse(s)\n/// }\n///\n/// assert_eq!(parser(\"abcabc\"), Ok((\"\", vec![\"abc\", \"abc\"])));\n/// assert_eq!(parser(\"abc123\"), Ok((\"123\", vec![\"abc\"])));\n/// assert_eq!(parser(\"123123\"), Err(Err::Error(Error::new(\"123123\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Tag))));\n/// ```\n#[cfg(feature = \"alloc\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\npub fn many1(\n parser: F,\n) -> impl Parser>::Output>, Error = >::Error>\nwhere\n I: Clone + Input,\n F: Parser,\n{\n Many1 { parser }\n}\n\n#[cfg(feature = \"alloc\")]\n/// Parser implementation for the [many1] combinator\npub struct Many1 {\n parser: F,\n}\n\n#[cfg(feature = \"alloc\")]\nimpl Parser for Many1\nwhere\n I: Clone + Input,\n F: Parser,\n{\n type Output = Vec<>::Output>;\n type Error = >::Error;\n\n fn process(\n &mut self,\n mut i: I,\n ) -> crate::PResult {\n match self\n .parser\n .process::>(i.clone())\n {\n Err(Err::Error(err)) => Err(Err::Error(OM::Error::bind(|| {\n >::Error::append(i, ErrorKind::Many1, err)\n }))),\n Err(Err::Failure(e)) => Err(Err::Failure(e)),\n Err(Err::Incomplete(i)) => Err(Err::Incomplete(i)),\n Ok((i1, o)) => {\n let mut acc = OM::Output::map(o, |o| {\n let mut acc = crate::lib::std::vec::Vec::with_capacity(4);\n acc.push(o);\n acc\n });\n\n i = i1;\n\n loop {\n let len = i.input_len();\n match self\n .parser\n .process::>(i.clone())\n {\n Err(Err::Error(_)) => return Ok((i, acc)),\n Err(Err::Failure(e)) => return Err(Err::Failure(e)),\n Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),\n Ok((i1, o)) => {\n // infinite loop check: the parser must always consume\n if i1.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(i, ErrorKind::Many0)\n })));\n }\n\n i = i1;\n\n acc = OM::Output::combine(acc, o, |mut acc, o| {\n acc.push(o);\n acc\n })\n }\n }\n }\n }\n }\n }\n}\n\n/// Applies the parser `f` until the parser `g` produces a result.\n///\n/// Returns a tuple of the results of `f` in a `Vec` and the result of `g`.\n///\n/// `f` keeps going so long as `g` produces [`Err::Error`]. To instead chain an error up, see [`cut`][crate::combinator::cut].\n///\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};\n/// use nom::multi::many_till;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, (Vec<&str>, &str)> {\n/// many_till(tag(\"abc\"), tag(\"end\")).parse(s)\n/// };\n///\n/// assert_eq!(parser(\"abcabcend\"), Ok((\"\", (vec![\"abc\", \"abc\"], \"end\"))));\n/// assert_eq!(parser(\"abc123end\"), Err(Err::Error(Error::new(\"123end\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"123123end\"), Err(Err::Error(Error::new(\"123123end\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"abcendefg\"), Ok((\"efg\", (vec![\"abc\"], \"end\"))));\n/// ```\n#[cfg(feature = \"alloc\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\npub fn many_till(\n f: F,\n g: G,\n) -> impl Parser>::Output>, >::Output), Error = E>\nwhere\n I: Clone + Input,\n F: Parser,\n G: Parser,\n E: ParseError,\n{\n ManyTill {\n f,\n g,\n e: PhantomData,\n }\n}\n\n#[cfg(feature = \"alloc\")]\n/// Parser implementation for the [many_till] combinator\npub struct ManyTill {\n f: F,\n g: G,\n e: PhantomData,\n}\n\n#[cfg(feature = \"alloc\")]\nimpl Parser for ManyTill\nwhere\n I: Clone + Input,\n F: Parser,\n G: Parser,\n E: ParseError,\n{\n type Output = (Vec<>::Output>, >::Output);\n type Error = E;\n\n fn process(\n &mut self,\n mut i: I,\n ) -> crate::PResult {\n let mut res = OM::Output::bind(crate::lib::std::vec::Vec::new);\n loop {\n let len = i.input_len();\n match self\n .g\n .process::>(i.clone())\n {\n Ok((i1, o)) => return Ok((i1, OM::Output::combine(res, o, |res, o| (res, o)))),\n Err(Err::Failure(e)) => return Err(Err::Failure(e)),\n Err(Err::Incomplete(i)) => return Err(Err::Incomplete(i)),\n Err(Err::Error(_)) => {\n match self.f.process::(i.clone()) {\n Err(Err::Error(err)) => {\n return Err(Err::Error(OM::Error::map(err, |err| {\n E::append(i, ErrorKind::ManyTill, err)\n })))\n }\n Err(Err::Failure(e)) => return Err(Err::Failure(e)),\n Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),\n Ok((i1, o)) => {\n // infinite loop check: the parser must always consume\n if i1.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n E::from_error_kind(i, ErrorKind::Many0)\n })));\n }\n\n i = i1;\n\n res = OM::Output::combine(res, o, |mut acc, o| {\n acc.push(o);\n acc\n })\n }\n }\n }\n }\n }\n }\n}\n\n/// Alternates between two parsers to produce a list of elements.\n///\n/// This stops when either parser returns [`Err::Error`] and returns the results that were accumulated. To instead chain an error up, see\n/// [`cut`][crate::combinator::cut].\n///\n/// # Arguments\n/// * `sep` Parses the separator between list elements.\n/// * `f` Parses the elements of the list.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};\n/// use nom::multi::separated_list0;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {\n/// separated_list0(tag(\"|\"), tag(\"abc\")).parse(s)\n/// }\n///\n/// assert_eq!(parser(\"abc|abc|abc\"), Ok((\"\", vec![\"abc\", \"abc\", \"abc\"])));\n/// assert_eq!(parser(\"abc123abc\"), Ok((\"123abc\", vec![\"abc\"])));\n/// assert_eq!(parser(\"abc|def\"), Ok((\"|def\", vec![\"abc\"])));\n/// assert_eq!(parser(\"\"), Ok((\"\", vec![])));\n/// assert_eq!(parser(\"def|abc\"), Ok((\"def|abc\", vec![])));\n/// ```\n#[cfg(feature = \"alloc\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\npub fn separated_list0(\n sep: G,\n f: F,\n) -> impl Parser>::Output>, Error = E>\nwhere\n I: Clone + Input,\n F: Parser,\n G: Parser,\n E: ParseError,\n{\n SeparatedList0 {\n parser: f,\n separator: sep,\n }\n}\n\n#[cfg(feature = \"alloc\")]\n/// Parser implementation for the [separated_list0] combinator\npub struct SeparatedList0 {\n parser: F,\n separator: G,\n}\n\n#[cfg(feature = \"alloc\")]\nimpl, F, G> Parser for SeparatedList0\nwhere\n I: Clone + Input,\n F: Parser,\n G: Parser,\n{\n type Output = Vec<>::Output>;\n type Error = >::Error;\n\n fn process(\n &mut self,\n mut i: I,\n ) -> crate::PResult {\n let mut res = OM::Output::bind(crate::lib::std::vec::Vec::new);\n\n match self\n .parser\n .process::>(i.clone())\n {\n Err(Err::Error(_)) => return Ok((i, res)),\n Err(Err::Failure(e)) => return Err(Err::Failure(e)),\n Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),\n Ok((i1, o)) => {\n res = OM::Output::combine(res, o, |mut res, o| {\n res.push(o);\n res\n });\n i = i1;\n }\n }\n\n loop {\n let len = i.input_len();\n match self\n .separator\n .process::>(i.clone())\n {\n Err(Err::Error(_)) => return Ok((i, res)),\n Err(Err::Failure(e)) => return Err(Err::Failure(e)),\n Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),\n Ok((i1, _)) => {\n match self\n .parser\n .process::>(i1.clone())\n {\n Err(Err::Error(_)) => return Ok((i, res)),\n Err(Err::Failure(e)) => return Err(Err::Failure(e)),\n Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),\n Ok((i2, o)) => {\n // infinite loop check: the parser must always consume\n if i2.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(i, ErrorKind::SeparatedList)\n })));\n }\n\n res = OM::Output::combine(res, o, |mut res, o| {\n res.push(o);\n res\n });\n\n i = i2;\n }\n }\n }\n }\n }\n }\n}\n\n/// Alternates between two parsers to produce a list of elements until [`Err::Error`].\n///\n/// Fails if the element parser does not produce at least one element.\n///\n/// This stops when either parser returns [`Err::Error`] and returns the results that were accumulated. To instead chain an error up, see\n/// [`cut`][crate::combinator::cut].\n///\n/// # Arguments\n/// * `sep` Parses the separator between list elements.\n/// * `f` Parses the elements of the list.\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};\n/// use nom::multi::separated_list1;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {\n/// separated_list1(tag(\"|\"), tag(\"abc\")).parse(s)\n/// }\n///\n/// assert_eq!(parser(\"abc|abc|abc\"), Ok((\"\", vec![\"abc\", \"abc\", \"abc\"])));\n/// assert_eq!(parser(\"abc123abc\"), Ok((\"123abc\", vec![\"abc\"])));\n/// assert_eq!(parser(\"abc|def\"), Ok((\"|def\", vec![\"abc\"])));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"def|abc\"), Err(Err::Error(Error::new(\"def|abc\", ErrorKind::Tag))));\n/// ```\n#[cfg(feature = \"alloc\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\npub fn separated_list1(\n separator: G,\n parser: F,\n) -> impl Parser>::Output>, Error = E>\nwhere\n I: Clone + Input,\n F: Parser,\n G: Parser,\n E: ParseError,\n{\n SeparatedList1 { parser, separator }\n}\n\n#[cfg(feature = \"alloc\")]\n/// Parser implementation for the [separated_list1] combinator\npub struct SeparatedList1 {\n parser: F,\n separator: G,\n}\n\n#[cfg(feature = \"alloc\")]\nimpl, F, G> Parser for SeparatedList1\nwhere\n I: Clone + Input,\n F: Parser,\n G: Parser,\n{\n type Output = Vec<>::Output>;\n type Error = >::Error;\n\n fn process(\n &mut self,\n mut i: I,\n ) -> crate::PResult {\n let mut res = OM::Output::bind(crate::lib::std::vec::Vec::new);\n\n match self.parser.process::(i.clone()) {\n Err(e) => return Err(e),\n Ok((i1, o)) => {\n res = OM::Output::combine(res, o, |mut res, o| {\n res.push(o);\n res\n });\n i = i1;\n }\n }\n\n loop {\n let len = i.input_len();\n match self\n .separator\n .process::>(i.clone())\n {\n Err(Err::Error(_)) => return Ok((i, res)),\n Err(Err::Failure(e)) => return Err(Err::Failure(e)),\n Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),\n Ok((i1, _)) => {\n match self\n .parser\n .process::>(i1.clone())\n {\n Err(Err::Error(_)) => return Ok((i, res)),\n Err(Err::Failure(e)) => return Err(Err::Failure(e)),\n Err(Err::Incomplete(e)) => return Err(Err::Incomplete(e)),\n Ok((i2, o)) => {\n // infinite loop check: the parser must always consume\n if i2.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(i, ErrorKind::SeparatedList)\n })));\n }\n\n res = OM::Output::combine(res, o, |mut res, o| {\n res.push(o);\n res\n });\n i = i2;\n }\n }\n }\n }\n }\n }\n}\n\n/// Repeats the embedded parser `m..=n` times\n///\n/// This stops before `n` when the parser returns [`Err::Error`] and returns the results that were accumulated. To instead chain an error up, see\n/// [`cut`][crate::combinator::cut].\n///\n/// # Arguments\n/// * `m` The minimum number of iterations.\n/// * `n` The maximum number of iterations.\n/// * `f` The parser to apply.\n///\n/// *Note*: If the parser passed to `many1` accepts empty inputs\n/// (like `alpha0` or `digit0`), `many1` will return an error,\n/// to prevent going into an infinite loop.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};\n/// use nom::multi::many_m_n;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {\n/// many_m_n(0, 2, tag(\"abc\")).parse(s)\n/// }\n///\n/// assert_eq!(parser(\"abcabc\"), Ok((\"\", vec![\"abc\", \"abc\"])));\n/// assert_eq!(parser(\"abc123\"), Ok((\"123\", vec![\"abc\"])));\n/// assert_eq!(parser(\"123123\"), Ok((\"123123\", vec![])));\n/// assert_eq!(parser(\"\"), Ok((\"\", vec![])));\n/// assert_eq!(parser(\"abcabcabc\"), Ok((\"abc\", vec![\"abc\", \"abc\"])));\n/// ```\n#[cfg(feature = \"alloc\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\npub fn many_m_n(\n min: usize,\n max: usize,\n parser: F,\n) -> impl Parser>::Output>, Error = E>\nwhere\n I: Clone + Input,\n F: Parser,\n E: ParseError,\n{\n ManyMN { parser, min, max }\n}\n\n#[cfg(feature = \"alloc\")]\n/// Parser implementation for the [many_m_n] combinator\npub struct ManyMN {\n parser: F,\n min: usize,\n max: usize,\n}\n\n#[cfg(feature = \"alloc\")]\nimpl Parser for ManyMN\nwhere\n I: Clone + Input,\n F: Parser,\n{\n type Output = Vec<>::Output>;\n type Error = >::Error;\n\n fn process(\n &mut self,\n mut input: I,\n ) -> crate::PResult {\n if self.min > self.max {\n return Err(Err::Failure(>::Error::from_error_kind(\n input,\n ErrorKind::ManyMN,\n )));\n }\n\n let max_initial_capacity = MAX_INITIAL_CAPACITY_BYTES\n / crate::lib::std::mem::size_of::<>::Output>().max(1);\n let mut res = OM::Output::bind(|| {\n crate::lib::std::vec::Vec::with_capacity(self.min.min(max_initial_capacity))\n });\n for count in 0..self.max {\n let len = input.input_len();\n match self.parser.process::(input.clone()) {\n Ok((tail, value)) => {\n // infinite loop check: the parser must always consume\n if tail.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(input, ErrorKind::ManyMN)\n })));\n }\n\n res = OM::Output::combine(res, value, |mut res, value| {\n res.push(value);\n res\n });\n input = tail;\n }\n Err(Err::Error(e)) => {\n if count < self.min {\n return Err(Err::Error(OM::Error::map(e, |e| {\n >::Error::append(input, ErrorKind::ManyMN, e)\n })));\n } else {\n return Ok((input, res));\n }\n }\n Err(e) => {\n return Err(e);\n }\n }\n }\n\n Ok((input, res))\n }\n}\n\n/// Repeats the embedded parser, counting the results\n///\n/// This stops on [`Err::Error`]. To instead chain an error up, see\n/// [`cut`][crate::combinator::cut].\n///\n/// # Arguments\n/// * `f` The parser to apply.\n///\n/// *Note*: if the parser passed in accepts empty inputs (like `alpha0` or `digit0`), `many0` will\n/// return an error, to prevent going into an infinite loop\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};\n/// use nom::multi::many0_count;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, usize> {\n/// many0_count(tag(\"abc\")).parse(s)\n/// }\n///\n/// assert_eq!(parser(\"abcabc\"), Ok((\"\", 2)));\n/// assert_eq!(parser(\"abc123\"), Ok((\"123\", 1)));\n/// assert_eq!(parser(\"123123\"), Ok((\"123123\", 0)));\n/// assert_eq!(parser(\"\"), Ok((\"\", 0)));\n/// ```\npub fn many0_count(parser: F) -> impl Parser\nwhere\n I: Clone + Input,\n F: Parser,\n E: ParseError,\n{\n Many0Count { parser }\n}\n\n/// Parser implementation for the [many0_count] combinator\npub struct Many0Count {\n parser: F,\n}\n\nimpl Parser for Many0Count\nwhere\n I: Clone + Input,\n F: Parser,\n{\n type Output = usize;\n type Error = >::Error;\n\n fn process(\n &mut self,\n mut input: I,\n ) -> crate::PResult {\n let mut count = 0;\n\n loop {\n let input_ = input.clone();\n let len = input.input_len();\n match self\n .parser\n .process::>(input_)\n {\n Ok((i, _)) => {\n // infinite loop check: the parser must always consume\n if i.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(input, ErrorKind::Many0Count)\n })));\n }\n\n input = i;\n count += 1;\n }\n\n Err(Err::Error(_)) => return Ok((input, OM::Output::bind(|| count))),\n Err(Err::Failure(e)) => return Err(Err::Failure(e)),\n Err(Err::Incomplete(i)) => return Err(Err::Incomplete(i)),\n }\n }\n }\n}\n\n/// Runs the embedded parser, counting the results.\n///\n/// This stops on [`Err::Error`] if there is at least one result. To instead chain an error up,\n/// see [`cut`][crate::combinator::cut].\n///\n/// # Arguments\n/// * `f` The parser to apply.\n///\n/// *Note*: If the parser passed to `many1` accepts empty inputs\n/// (like `alpha0` or `digit0`), `many1` will return an error,\n/// to prevent going into an infinite loop.\n///\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};\n/// use nom::multi::many1_count;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, usize> {\n/// many1_count(tag(\"abc\")).parse(s)\n/// }\n///\n/// assert_eq!(parser(\"abcabc\"), Ok((\"\", 2)));\n/// assert_eq!(parser(\"abc123\"), Ok((\"123\", 1)));\n/// assert_eq!(parser(\"123123\"), Err(Err::Error(Error::new(\"123123\", ErrorKind::Many1Count))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Many1Count))));\n/// ```\npub fn many1_count(parser: F) -> impl Parser\nwhere\n I: Clone + Input,\n F: Parser,\n E: ParseError,\n{\n Many1Count { parser }\n}\n\n/// Parser implementation for the [many1_count] combinator\npub struct Many1Count {\n parser: F,\n}\n\nimpl Parser for Many1Count\nwhere\n I: Clone + Input,\n F: Parser,\n{\n type Output = usize;\n type Error = >::Error;\n\n fn process(\n &mut self,\n input: I,\n ) -> crate::PResult {\n let mut count = 0;\n\n match self\n .parser\n .process::>(input.clone())\n {\n Err(Err::Error(_)) => Err(Err::Error(OM::Error::bind(move || {\n >::Error::from_error_kind(input, ErrorKind::Many1Count)\n }))),\n Err(Err::Failure(e)) => Err(Err::Failure(e)),\n Err(Err::Incomplete(i)) => Err(Err::Incomplete(i)),\n Ok((mut input, _)) => {\n count += 1;\n\n loop {\n let input_ = input.clone();\n let len = input.input_len();\n match self\n .parser\n .process::>(input_)\n {\n Ok((i, _)) => {\n // infinite loop check: the parser must always consume\n if i.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(input, ErrorKind::Many1Count)\n })));\n }\n\n input = i;\n count += 1;\n }\n\n Err(Err::Error(_)) => return Ok((input, OM::Output::bind(|| count))),\n Err(Err::Failure(e)) => return Err(Err::Failure(e)),\n Err(Err::Incomplete(i)) => return Err(Err::Incomplete(i)),\n }\n }\n }\n }\n }\n}\n\n/// Runs the embedded parser `count` times, gathering the results in a `Vec`\n///\n/// # Arguments\n/// * `f` The parser to apply.\n/// * `count` How often to apply the parser.\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};\n/// use nom::multi::count;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {\n/// count(tag(\"abc\"), 2).parse(s)\n/// }\n///\n/// assert_eq!(parser(\"abcabc\"), Ok((\"\", vec![\"abc\", \"abc\"])));\n/// assert_eq!(parser(\"abc123\"), Err(Err::Error(Error::new(\"123\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"123123\"), Err(Err::Error(Error::new(\"123123\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"abcabcabc\"), Ok((\"abc\", vec![\"abc\", \"abc\"])));\n/// ```\n#[cfg(feature = \"alloc\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\npub fn count(\n parser: F,\n count: usize,\n) -> impl Parser>::Output>, Error = >::Error>\nwhere\n I: Clone,\n F: Parser,\n{\n Count { parser, count }\n}\n\n#[cfg(feature = \"alloc\")]\n/// Parser implementation for the [count] combinator\npub struct Count {\n parser: F,\n count: usize,\n}\n\n#[cfg(feature = \"alloc\")]\nimpl Parser for Count\nwhere\n I: Clone,\n F: Parser,\n{\n type Output = Vec<>::Output>;\n type Error = >::Error;\n\n fn process(&mut self, i: I) -> crate::PResult {\n let mut input = i.clone();\n let max_initial_capacity = MAX_INITIAL_CAPACITY_BYTES\n / crate::lib::std::mem::size_of::<>::Output>().max(1);\n let mut res = OM::Output::bind(|| {\n crate::lib::std::vec::Vec::with_capacity(self.count.min(max_initial_capacity))\n });\n\n for _ in 0..self.count {\n let input_ = input.clone();\n match self.parser.process::(input_) {\n Ok((i, o)) => {\n res = OM::Output::combine(res, o, |mut res, o| {\n res.push(o);\n res\n });\n input = i;\n }\n Err(Err::Error(e)) => {\n return Err(Err::Error(OM::Error::map(e, |e| {\n >::Error::append(i, ErrorKind::Count, e)\n })));\n }\n Err(e) => {\n return Err(e);\n }\n }\n }\n\n Ok((input, res))\n }\n}\n\n/// Runs the embedded parser repeatedly, filling the given slice with results.\n///\n/// This parser fails if the input runs out before the given slice is full.\n///\n/// # Arguments\n/// * `f` The parser to apply.\n/// * `buf` The slice to fill\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};\n/// use nom::multi::fill;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, [&str; 2]> {\n/// let mut buf = [\"\", \"\"];\n/// let (rest, ()) = fill(tag(\"abc\"), &mut buf).parse(s)?;\n/// Ok((rest, buf))\n/// }\n///\n/// assert_eq!(parser(\"abcabc\"), Ok((\"\", [\"abc\", \"abc\"])));\n/// assert_eq!(parser(\"abc123\"), Err(Err::Error(Error::new(\"123\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"123123\"), Err(Err::Error(Error::new(\"123123\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Tag))));\n/// assert_eq!(parser(\"abcabcabc\"), Ok((\"abc\", [\"abc\", \"abc\"])));\n/// ```\npub fn fill<'a, I, E, F>(\n parser: F,\n buf: &'a mut [>::Output],\n) -> impl Parser + 'a\nwhere\n I: Clone,\n F: Parser + 'a,\n E: ParseError,\n{\n Fill { parser, buf }\n}\n\n/// Parser implementation for the [fill] combinator\npub struct Fill<'a, F, O> {\n parser: F,\n buf: &'a mut [O],\n}\n\nimpl<'a, I, F, O> Parser for Fill<'a, F, O>\nwhere\n I: Clone,\n F: Parser,\n{\n type Output = ();\n type Error = >::Error;\n\n fn process(&mut self, i: I) -> crate::PResult {\n let mut input = i.clone();\n\n for elem in self.buf.iter_mut() {\n let input_ = input.clone();\n match self.parser.process::(input_) {\n Ok((i, o)) => {\n OM::Output::map(o, |o| *elem = o);\n input = i;\n }\n Err(Err::Error(e)) => {\n return Err(Err::Error(OM::Error::map(e, |e| {\n >::Error::append(i, ErrorKind::Count, e)\n })));\n }\n Err(e) => {\n return Err(e);\n }\n }\n }\n\n Ok((input, OM::Output::bind(|| ())))\n }\n}\n\n/// Repeats the embedded parser, calling `g` to gather the results.\n///\n/// This stops on [`Err::Error`]. To instead chain an error up, see\n/// [`cut`][crate::combinator::cut].\n///\n/// # Arguments\n/// * `f` The parser to apply.\n/// * `init` A function returning the initial value.\n/// * `g` The function that combines a result of `f` with\n/// the current accumulator.\n///\n/// *Note*: if the parser passed in accepts empty inputs (like `alpha0` or `digit0`), `many0` will\n/// return an error, to prevent going into an infinite loop\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};\n/// use nom::multi::fold_many0;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {\n/// fold_many0(\n/// tag(\"abc\"),\n/// Vec::new,\n/// |mut acc: Vec<_>, item| {\n/// acc.push(item);\n/// acc\n/// }\n/// ).parse(s)\n/// }\n///\n/// assert_eq!(parser(\"abcabc\"), Ok((\"\", vec![\"abc\", \"abc\"])));\n/// assert_eq!(parser(\"abc123\"), Ok((\"123\", vec![\"abc\"])));\n/// assert_eq!(parser(\"123123\"), Ok((\"123123\", vec![])));\n/// assert_eq!(parser(\"\"), Ok((\"\", vec![])));\n/// ```\npub fn fold_many0(\n parser: F,\n init: H,\n g: G,\n) -> impl Parser\nwhere\n I: Clone + Input,\n F: Parser,\n G: FnMut(R, >::Output) -> R,\n H: FnMut() -> R,\n E: ParseError,\n{\n FoldMany0 {\n parser,\n g,\n init,\n r: PhantomData,\n }\n}\n\n/// Parser implementation for the [fold_many0] combinator\npub struct FoldMany0 {\n parser: F,\n g: G,\n init: Init,\n r: PhantomData,\n}\n\nimpl Parser for FoldMany0\nwhere\n I: Clone + Input,\n F: Parser,\n G: FnMut(R, >::Output) -> R,\n Init: FnMut() -> R,\n{\n type Output = R;\n type Error = >::Error;\n\n fn process(&mut self, i: I) -> crate::PResult {\n let mut res = OM::Output::bind(|| (self.init)());\n let mut input = i;\n\n loop {\n let i_ = input.clone();\n let len = input.input_len();\n match self.parser.process::(i_) {\n Ok((i, o)) => {\n // infinite loop check: the parser must always consume\n if i.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(input, ErrorKind::Many0)\n })));\n }\n\n res = OM::Output::combine(res, o, |res, o| (self.g)(res, o));\n input = i;\n }\n Err(Err::Error(_)) => {\n return Ok((input, res));\n }\n Err(e) => {\n return Err(e);\n }\n }\n }\n }\n}\n\n/// Repeats the embedded parser, calling `g` to gather the results.\n///\n/// This stops on [`Err::Error`] if there is at least one result. To instead chain an error up,\n/// see [`cut`][crate::combinator::cut].\n///\n/// # Arguments\n/// * `f` The parser to apply.\n/// * `init` A function returning the initial value.\n/// * `g` The function that combines a result of `f` with\n/// the current accumulator.\n///\n/// *Note*: If the parser passed to `many1` accepts empty inputs\n/// (like `alpha0` or `digit0`), `many1` will return an error,\n/// to prevent going into an infinite loop.\n///\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};\n/// use nom::multi::fold_many1;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {\n/// fold_many1(\n/// tag(\"abc\"),\n/// Vec::new,\n/// |mut acc: Vec<_>, item| {\n/// acc.push(item);\n/// acc\n/// }\n/// ).parse(s)\n/// }\n///\n/// assert_eq!(parser(\"abcabc\"), Ok((\"\", vec![\"abc\", \"abc\"])));\n/// assert_eq!(parser(\"abc123\"), Ok((\"123\", vec![\"abc\"])));\n/// assert_eq!(parser(\"123123\"), Err(Err::Error(Error::new(\"123123\", ErrorKind::Many1))));\n/// assert_eq!(parser(\"\"), Err(Err::Error(Error::new(\"\", ErrorKind::Many1))));\n/// ```\npub fn fold_many1(\n parser: F,\n init: H,\n g: G,\n) -> impl Parser\nwhere\n I: Clone + Input,\n F: Parser,\n G: FnMut(R, >::Output) -> R,\n H: FnMut() -> R,\n E: ParseError,\n{\n FoldMany1 {\n parser,\n g,\n init,\n r: PhantomData,\n }\n}\n\n/// Parser implementation for the [fold_many1] combinator\npub struct FoldMany1 {\n parser: F,\n g: G,\n init: Init,\n r: PhantomData,\n}\n\nimpl Parser for FoldMany1\nwhere\n I: Clone + Input,\n F: Parser,\n G: FnMut(R, >::Output) -> R,\n Init: FnMut() -> R,\n{\n type Output = R;\n type Error = >::Error;\n\n fn process(&mut self, i: I) -> crate::PResult {\n let mut res = OM::Output::bind(|| (self.init)());\n let input = i.clone();\n\n match self.parser.process::(input) {\n Err(Err::Error(_)) => Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(i, ErrorKind::Many1)\n }))),\n Err(e) => Err(e),\n Ok((i1, o1)) => {\n res = OM::Output::combine(res, o1, |res, o| (self.g)(res, o));\n\n let mut input = i1;\n loop {\n let i_ = input.clone();\n let len = input.input_len();\n match self.parser.process::(i_) {\n Ok((i, o)) => {\n // infinite loop check: the parser must always consume\n if i.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(input, ErrorKind::Many1)\n })));\n }\n\n res = OM::Output::combine(res, o, |res, o| (self.g)(res, o));\n input = i;\n }\n Err(Err::Error(_)) => {\n return Ok((input, res));\n }\n Err(e) => {\n return Err(e);\n }\n }\n }\n }\n }\n }\n}\n\n/// Repeats the embedded parser `m..=n` times, calling `g` to gather the results\n///\n/// This stops before `n` when the parser returns [`Err::Error`]. To instead chain an error up, see\n/// [`cut`][crate::combinator::cut].\n///\n/// # Arguments\n/// * `m` The minimum number of iterations.\n/// * `n` The maximum number of iterations.\n/// * `f` The parser to apply.\n/// * `init` A function returning the initial value.\n/// * `g` The function that combines a result of `f` with\n/// the current accumulator.\n///\n/// *Note*: If the parser passed to `many1` accepts empty inputs\n/// (like `alpha0` or `digit0`), `many1` will return an error,\n/// to prevent going into an infinite loop.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};\n/// use nom::multi::fold_many_m_n;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {\n/// fold_many_m_n(\n/// 0,\n/// 2,\n/// tag(\"abc\"),\n/// Vec::new,\n/// |mut acc: Vec<_>, item| {\n/// acc.push(item);\n/// acc\n/// }\n/// ).parse(s)\n/// }\n///\n/// assert_eq!(parser(\"abcabc\"), Ok((\"\", vec![\"abc\", \"abc\"])));\n/// assert_eq!(parser(\"abc123\"), Ok((\"123\", vec![\"abc\"])));\n/// assert_eq!(parser(\"123123\"), Ok((\"123123\", vec![])));\n/// assert_eq!(parser(\"\"), Ok((\"\", vec![])));\n/// assert_eq!(parser(\"abcabcabc\"), Ok((\"abc\", vec![\"abc\", \"abc\"])));\n/// ```\npub fn fold_many_m_n(\n min: usize,\n max: usize,\n parser: F,\n init: H,\n g: G,\n) -> impl Parser\nwhere\n I: Clone + Input,\n F: Parser,\n G: FnMut(R, >::Output) -> R,\n H: FnMut() -> R,\n E: ParseError,\n{\n FoldManyMN {\n parser,\n g,\n init,\n min,\n max,\n r: PhantomData,\n }\n}\n\n/// Parser implementation for the [fold_many_m_n] combinator\npub struct FoldManyMN {\n parser: F,\n g: G,\n init: Init,\n r: PhantomData,\n min: usize,\n max: usize,\n}\n\nimpl Parser for FoldManyMN\nwhere\n I: Clone + Input,\n F: Parser,\n G: FnMut(R, >::Output) -> R,\n Init: FnMut() -> R,\n{\n type Output = R;\n type Error = >::Error;\n\n fn process(\n &mut self,\n mut input: I,\n ) -> crate::PResult {\n if self.min > self.max {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(input, ErrorKind::ManyMN)\n })));\n }\n\n let mut res = OM::Output::bind(|| (self.init)());\n for count in 0..self.max {\n let len = input.input_len();\n match self.parser.process::(input.clone()) {\n Ok((tail, value)) => {\n // infinite loop check: the parser must always consume\n if tail.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(tail, ErrorKind::ManyMN)\n })));\n }\n\n res = OM::Output::combine(res, value, |res, o| (self.g)(res, o));\n input = tail;\n }\n Err(Err::Error(err)) => {\n if count < self.min {\n return Err(Err::Error(OM::Error::map(err, |err| {\n >::Error::append(input, ErrorKind::ManyMN, err)\n })));\n } else {\n break;\n }\n }\n Err(e) => return Err(e),\n }\n }\n\n Ok((input, res))\n }\n}\n\n/// Gets a number from the parser and returns a\n/// subslice of the input of that size.\n/// If the parser returns `Incomplete`,\n/// `length_data` will return an error.\n/// # Arguments\n/// * `f` The parser to apply.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};\n/// use nom::number::complete::be_u16;\n/// use nom::multi::length_data;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &[u8]) -> IResult<&[u8], &[u8]> {\n/// length_data(be_u16).parse(s)\n/// }\n///\n/// assert_eq!(parser(b\"\\x00\\x03abcefg\"), Ok((&b\"efg\"[..], &b\"abc\"[..])));\n/// assert_eq!(parser(b\"\\x00\\x03a\"), Err(Err::Incomplete(Needed::new(2))));\n/// ```\npub fn length_data(f: F) -> impl Parser\nwhere\n I: Input,\n >::Output: ToUsize,\n F: Parser,\n E: ParseError,\n{\n f.flat_map(|size| take(size))\n}\n\n/// Gets a number from the first parser,\n/// takes a subslice of the input of that size,\n/// then applies the second parser on that subslice.\n/// If the second parser returns `Incomplete`,\n/// `length_value` will return an error.\n/// # Arguments\n/// * `f` The parser to apply.\n/// * `g` The parser to apply on the subslice.\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};\n/// use nom::number::complete::be_u16;\n/// use nom::multi::length_value;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &[u8]) -> IResult<&[u8], &[u8]> {\n/// length_value(be_u16, tag(\"abc\")).parse(s)\n/// }\n///\n/// assert_eq!(parser(b\"\\x00\\x03abcefg\"), Ok((&b\"efg\"[..], &b\"abc\"[..])));\n/// assert_eq!(parser(b\"\\x00\\x03123123\"), Err(Err::Error(Error::new(&b\"123\"[..], ErrorKind::Tag))));\n/// assert_eq!(parser(b\"\\x00\\x03a\"), Err(Err::Incomplete(Needed::new(2))));\n/// ```\npub fn length_value(\n f: F,\n g: G,\n) -> impl Parser>::Output, Error = E>\nwhere\n I: Clone + Input,\n >::Output: ToUsize,\n F: Parser,\n G: Parser,\n E: ParseError,\n{\n println!(\"got size: {size}\");\n take(size)\n })\n .and_then(g)*/\n LengthValue {\n length: f,\n parser: g,\n e: PhantomData,\n }\n}\n\n/// Parser implementation for the [length_value] combinator\npub struct LengthValue {\n length: F,\n parser: G,\n e: PhantomData,\n}\n\nimpl Parser for LengthValue\nwhere\n I: Clone + Input,\n F: Parser,\n G: Parser,\n >::Output: ToUsize,\n E: ParseError,\n{\n type Output = >::Output;\n type Error = E;\n\n fn process(\n &mut self,\n input: I,\n ) -> crate::PResult {\n let (i, length) = self\n .length\n .process::>(input)?;\n\n let length: usize = length.to_usize();\n\n if let Some(needed) = length\n .checked_sub(i.input_len())\n .and_then(NonZeroUsize::new)\n {\n Err(Err::Incomplete(Needed::Size(needed)))\n } else {\n let (rest, i) = i.take_split(length);\n match self.parser.process::(i.clone()) {\n Err(Err::Incomplete(_)) => Err(Err::Error(OM::Error::bind(|| {\n E::from_error_kind(i, ErrorKind::Complete)\n }))),\n Err(e) => Err(e),\n Ok((_, o)) => Ok((rest, o)),\n }\n }\n }\n}\n\n/// Gets a number from the first parser,\n/// then applies the second parser that many times.\n/// # Arguments\n/// * `f` The parser to apply to obtain the count.\n/// * `g` The parser to apply repeatedly.\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, Needed, IResult, Parser};\n/// use nom::number::complete::u8;\n/// use nom::multi::length_count;\n/// use nom::bytes::complete::tag;\n/// use nom::combinator::map;\n///\n/// fn parser(s: &[u8]) -> IResult<&[u8], Vec<&[u8]>> {\n/// length_count(map(u8, |i| {\n/// println!(\"got number: {}\", i);\n/// i\n/// }), tag(\"abc\")).parse(s)\n/// }\n///\n/// assert_eq!(parser(&b\"\\x02abcabcabc\"[..]), Ok(((&b\"abc\"[..], vec![&b\"abc\"[..], &b\"abc\"[..]]))));\n/// assert_eq!(parser(b\"\\x03123123123\"), Err(Err::Error(Error::new(&b\"123123123\"[..], ErrorKind::Tag))));\n/// ```\n#[cfg(feature = \"alloc\")]\npub fn length_count(\n f: F,\n g: G,\n) -> impl Parser>::Output>, Error = E>\nwhere\n I: Clone,\n >::Output: ToUsize,\n F: Parser,\n G: Parser,\n E: ParseError,\n{\n LengthCount {\n length: f,\n parser: g,\n e: PhantomData,\n }\n}\n\n#[cfg(feature = \"alloc\")]\n/// Parser implementation for the [length_count] combinator\npub struct LengthCount {\n length: F,\n parser: G,\n e: PhantomData,\n}\n\n#[cfg(feature = \"alloc\")]\nimpl Parser for LengthCount\nwhere\n I: Clone,\n F: Parser,\n G: Parser,\n >::Output: ToUsize,\n E: ParseError,\n{\n type Output = Vec<>::Output>;\n type Error = E;\n\n fn process(\n &mut self,\n input: I,\n ) -> crate::PResult {\n match self\n .length\n .process::>(input)\n {\n Err(e) => Err(e),\n Ok((i, count)) => {\n let count = count.to_usize();\n let mut input = i.clone();\n let max_initial_capacity = MAX_INITIAL_CAPACITY_BYTES\n / crate::lib::std::mem::size_of::<>::Output>().max(1);\n let mut res = OM::Output::bind(|| {\n crate::lib::std::vec::Vec::with_capacity(count.min(max_initial_capacity))\n });\n\n for _ in 0..count {\n let input_ = input.clone();\n match self.parser.process::(input_) {\n Ok((i, o)) => {\n res = OM::Output::combine(res, o, |mut res, o| {\n res.push(o);\n res\n });\n input = i;\n }\n Err(Err::Error(e)) => {\n return Err(Err::Error(OM::Error::map(e, |e| {\n >::Error::append(i, ErrorKind::Count, e)\n })));\n }\n Err(e) => {\n return Err(e);\n }\n }\n }\n\n Ok((input, res))\n }\n }\n }\n}\n\n/// Repeats the embedded parser and collects the results in a type implementing `Extend + Default`.\n/// Fails if the amount of time the embedded parser is run is not\n/// within the specified range.\n/// # Arguments\n/// * `range` Constrains the number of iterations.\n/// * A range without an upper bound `a..` is equivalent to a range of `a..=usize::MAX`.\n/// * A single `usize` value is equivalent to `value..=value`.\n/// * An empty range is invalid.\n/// * `parse` The parser to apply.\n///\n/// ```rust\n/// # #[macro_use] extern crate nom;\n/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};\n/// use nom::multi::many;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {\n/// many(0..=2, tag(\"abc\")).parse(s)\n/// }\n///\n/// assert_eq!(parser(\"abcabc\"), Ok((\"\", vec![\"abc\", \"abc\"])));\n/// assert_eq!(parser(\"abc123\"), Ok((\"123\", vec![\"abc\"])));\n/// assert_eq!(parser(\"123123\"), Ok((\"123123\", vec![])));\n/// assert_eq!(parser(\"\"), Ok((\"\", vec![])));\n/// assert_eq!(parser(\"abcabcabc\"), Ok((\"abc\", vec![\"abc\", \"abc\"])));\n/// ```\n///\n/// This is not limited to `Vec`, other collections like `HashMap`\n/// can be used:\n///\n/// ```rust\n/// # #[macro_use] extern crate nom;\n/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};\n/// use nom::multi::many;\n/// use nom::bytes::complete::{tag, take_while};\n/// use nom::sequence::{separated_pair, terminated};\n/// use nom::AsChar;\n///\n/// use std::collections::HashMap;\n///\n/// fn key_value(s: &str) -> IResult<&str, HashMap<&str, &str>> {\n/// many(0.., terminated(\n/// separated_pair(\n/// take_while(AsChar::is_alpha),\n/// tag(\"=\"),\n/// take_while(AsChar::is_alpha)\n/// ),\n/// tag(\";\")\n/// )).parse(s)\n/// }\n///\n/// assert_eq!(\n/// key_value(\"a=b;c=d;\"),\n/// Ok((\"\", HashMap::from([(\"a\", \"b\"), (\"c\", \"d\")])))\n/// );\n/// ```\n///\n/// If more control is needed on the default value, [fold] can\n/// be used instead:\n///\n/// ```rust\n/// # #[macro_use] extern crate nom;\n/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};\n/// use nom::multi::fold;\n/// use nom::bytes::complete::tag;\n///\n///\n/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {\n/// fold(\n/// 0..=4,\n/// tag(\"abc\"),\n/// // preallocates a vector of the max size\n/// || Vec::with_capacity(4),\n/// |mut acc: Vec<_>, item| {\n/// acc.push(item);\n/// acc\n/// }\n/// ).parse(s)\n/// }\n///\n///\n/// assert_eq!(parser(\"abcabcabcabc\"), Ok((\"\", vec![\"abc\", \"abc\", \"abc\", \"abc\"])));\n/// ```\n#[cfg(feature = \"alloc\")]\n#[cfg_attr(feature = \"docsrs\", doc(cfg(feature = \"alloc\")))]\npub fn many(\n range: G,\n parser: F,\n) -> impl Parser\nwhere\n I: Clone + Input,\n F: Parser,\n Collection: Extend<>::Output> + Default,\n E: ParseError,\n G: NomRange,\n{\n Many {\n parser,\n range,\n c: PhantomData,\n }\n}\n\n/// Parser implementation for the [many] combinator\npub struct Many {\n parser: F,\n range: R,\n c: PhantomData,\n}\n\nimpl Parser for Many\nwhere\n I: Clone + Input,\n F: Parser,\n Collection: Extend<>::Output> + Default,\n R: NomRange,\n{\n type Output = Collection;\n type Error = >::Error;\n\n fn process(\n &mut self,\n mut input: I,\n ) -> crate::PResult {\n if self.range.is_inverted() {\n return Err(Err::Failure(>::Error::from_error_kind(\n input,\n ErrorKind::Many,\n )));\n }\n\n let mut res = OM::Output::bind(Collection::default);\n\n for count in self.range.bounded_iter() {\n let len = input.input_len();\n match self.parser.process::(input.clone()) {\n Ok((tail, value)) => {\n // infinite loop check: the parser must always consume\n if tail.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(input, ErrorKind::Many)\n })));\n }\n\n res = OM::Output::combine(res, value, |mut res, value| {\n res.extend(Some(value));\n res\n });\n input = tail;\n }\n Err(Err::Error(e)) => {\n if !self.range.contains(&count) {\n return Err(Err::Error(OM::Error::map(e, |e| {\n >::Error::append(input, ErrorKind::Many, e)\n })));\n } else {\n return Ok((input, res));\n }\n }\n Err(e) => {\n return Err(e);\n }\n }\n }\n\n Ok((input, res))\n }\n}\n\n/// Applies a parser and accumulates the results using a given\n/// function and initial value.\n/// Fails if the amount of time the embedded parser is run is not\n/// within the specified range.\n///\n/// # Arguments\n/// * `range` Constrains the number of iterations.\n/// * A range without an upper bound `a..` allows the parser to run until it fails.\n/// * A single `usize` value is equivalent to `value..=value`.\n/// * An empty range is invalid.\n/// * `parse` The parser to apply.\n/// * `init` A function returning the initial value.\n/// * `fold` The function that combines a result of `f` with\n/// the current accumulator.\n/// ```rust\n/// # #[macro_use] extern crate nom;\n/// # use nom::{Err, error::ErrorKind, Needed, IResult, Parser};\n/// use nom::multi::fold;\n/// use nom::bytes::complete::tag;\n///\n/// fn parser(s: &str) -> IResult<&str, Vec<&str>> {\n/// fold(\n/// 0..=2,\n/// tag(\"abc\"),\n/// Vec::new,\n/// |mut acc: Vec<_>, item| {\n/// acc.push(item);\n/// acc\n/// }\n/// ).parse(s)\n/// }\n///\n/// assert_eq!(parser(\"abcabc\"), Ok((\"\", vec![\"abc\", \"abc\"])));\n/// assert_eq!(parser(\"abc123\"), Ok((\"123\", vec![\"abc\"])));\n/// assert_eq!(parser(\"123123\"), Ok((\"123123\", vec![])));\n/// assert_eq!(parser(\"\"), Ok((\"\", vec![])));\n/// assert_eq!(parser(\"abcabcabc\"), Ok((\"abc\", vec![\"abc\", \"abc\"])));\n/// ```\npub fn fold(\n range: J,\n parser: F,\n init: H,\n fold: G,\n) -> impl Parser\nwhere\n I: Clone + Input,\n F: Parser,\n G: FnMut(R, >::Output) -> R,\n H: FnMut() -> R,\n E: ParseError,\n J: NomRange,\n{\n Fold {\n parser,\n init,\n fold,\n range,\n }\n}\n\n/// Parser implementation for the [fold] combinator\npub struct Fold {\n parser: F,\n init: H,\n fold: G,\n range: Range,\n}\n\nimpl Parser for Fold\nwhere\n I: Clone + Input,\n F: Parser,\n G: FnMut(Res, >::Output) -> Res,\n H: FnMut() -> Res,\n Range: NomRange,\n{\n type Output = Res;\n type Error = >::Error;\n\n fn process(\n &mut self,\n mut input: I,\n ) -> crate::PResult {\n if self.range.is_inverted() {\n return Err(Err::Failure(>::Error::from_error_kind(\n input,\n ErrorKind::Fold,\n )));\n }\n\n let mut acc = OM::Output::bind(|| (self.init)());\n\n for count in self.range.saturating_iter() {\n let len = input.input_len();\n match self.parser.process::(input.clone()) {\n Ok((tail, value)) => {\n // infinite loop check: the parser must always consume\n if tail.input_len() == len {\n return Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(tail, ErrorKind::Fold)\n })));\n }\n\n acc = OM::Output::combine(acc, value, |acc, value| (self.fold)(acc, value));\n input = tail;\n }\n Err(Err::Error(err)) => {\n if !self.range.contains(&count) {\n return Err(Err::Error(OM::Error::map(err, |err| {\n >::Error::append(input, ErrorKind::Fold, err)\n })));\n } else {\n break;\n }\n }\n Err(e) => return Err(e),\n }\n }\n\n Ok((input, acc))\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "mod.rs", "content": "use core::{\n marker::PhantomData,\n ops::{Add, Shl},\n};\n\nuse crate::{\n branch::alt,\n character::{char, digit1},\n combinator::{cut, map, opt, recognize},\n error::{make_error, ErrorKind, ParseError},\n sequence::pair,\n AsBytes, AsChar, Compare, Either, Emit, Err, Input, IsStreaming, Mode, Needed, Offset, OutputM,\n Parser,\n};\n\npub mod complete;\npub mod streaming;\n\n/// Configurable endianness\n#[derive(Debug, PartialEq, Eq, Clone, Copy)]\npub enum Endianness {\n /// Big endian\n Big,\n /// Little endian\n Little,\n /// Will match the host's endianness\n Native,\n}\n\n/// creates a big endian unsigned integer parser\n///\n/// * `bound`: the number of bytes that will be read\n/// * `Uint`: the output type\n#[inline]\nfn be_uint>(bound: usize) -> impl Parser\nwhere\n I: Input,\n Uint: Default + Shl + Add + From,\n{\n BeUint {\n bound,\n e: PhantomData,\n u: PhantomData,\n }\n}\n\n/// Big endian unsigned integer parser\nstruct BeUint {\n bound: usize,\n e: PhantomData,\n u: PhantomData,\n}\n\nimpl> Parser for BeUint\nwhere\n I: Input,\n Uint: Default + Shl + Add + From,\n{\n type Output = Uint;\n type Error = E;\n\n #[inline(always)]\n fn process(\n &mut self,\n input: I,\n ) -> crate::PResult {\n if input.input_len() < self.bound {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::new(self.bound - input.input_len())))\n } else {\n Err(Err::Error(OM::Error::bind(|| {\n make_error(input, ErrorKind::Eof)\n })))\n }\n } else {\n let res = OM::Output::bind(|| {\n let mut res = Uint::default();\n\n // special case to avoid shift a byte with overflow\n if self.bound > 1 {\n for byte in input.iter_elements().take(self.bound) {\n res = (res << 8) + byte.into();\n }\n } else {\n for byte in input.iter_elements().take(self.bound) {\n res = byte.into();\n }\n }\n\n res\n });\n\n Ok((input.take_from(self.bound), res))\n }\n }\n}\n\n/// Recognizes an unsigned 1 byte integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_u8;\n///\n/// let parser = |s| {\n/// be_u8::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01abcd\"[..]), Ok((&b\"\\x01abcd\"[..], 0x00)));\n/// assert_eq!(parser(&b\"\"[..]), Err(Err::Incomplete(Needed::new(1))));\n/// ```\n#[inline]\npub fn be_u8>() -> impl Parser\nwhere\n I: Input,\n{\n be_uint(1)\n}\n\n/// Recognizes a big endian unsigned 2 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_u16;\n///\n/// let parser = |s| {\n/// be_u16::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01abcd\"[..]), Ok((&b\"abcd\"[..], 0x0001)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(1))));\n/// ```\n#[inline]\npub fn be_u16>() -> impl Parser\nwhere\n I: Input,\n{\n be_uint(2)\n}\n\n/// Recognizes a big endian unsigned 3 byte integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_u24;\n///\n/// let parser = |s| {\n/// be_u24::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02abcd\"[..]), Ok((&b\"abcd\"[..], 0x000102)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(2))));\n/// ```\n#[inline]\npub fn be_u24>() -> impl Parser\nwhere\n I: Input,\n{\n be_uint(3)\n}\n\n/// Recognizes a big endian unsigned 4 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_u32;\n///\n/// let parser = |s| {\n/// be_u32::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03abcd\"[..]), Ok((&b\"abcd\"[..], 0x00010203)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(3))));\n/// ```\n#[inline]\npub fn be_u32>() -> impl Parser\nwhere\n I: Input,\n{\n be_uint(4)\n}\n\n/// Recognizes a big endian unsigned 8 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_u64;\n///\n/// let parser = |s| {\n/// be_u64::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcd\"[..]), Ok((&b\"abcd\"[..], 0x0001020304050607)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(7))));\n/// ```\n#[inline]\npub fn be_u64>() -> impl Parser\nwhere\n I: Input,\n{\n be_uint(8)\n}\n\n/// Recognizes a big endian unsigned 16 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_u128;\n///\n/// let parser = |s| {\n/// be_u128::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x10\\x11\\x12\\x13\\x14\\x15abcd\"[..]), Ok((&b\"abcd\"[..], 0x00010203040506070809101112131415)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(15))));\n/// ```\n#[inline]\npub fn be_u128>() -> impl Parser\nwhere\n I: Input,\n{\n be_uint(16)\n}\n\n/// Recognizes a signed 1 byte integer.\n///\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there is not enough data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_i8;\n///\n/// let mut parser = be_i8::<_, (_, ErrorKind)>();\n///\n/// assert_eq!(parser.parse(&b\"\\x00\\x01abcd\"[..]), Ok((&b\"\\x01abcd\"[..], 0x00)));\n/// assert_eq!(parser.parse(&b\"\"[..]), Err(Err::Incomplete(Needed::new(1))));\n/// ```\n#[inline]\npub fn be_i8>() -> impl Parser\nwhere\n I: Input,\n{\n be_u8().map(|x| x as i8)\n}\n\n/// Recognizes a big endian signed 2 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_i16;\n///\n/// let mut parser = be_i16::<_, (_, ErrorKind)>();\n///\n/// assert_eq!(parser.parse(&b\"\\x00\\x01abcd\"[..]), Ok((&b\"abcd\"[..], 0x0001)));\n/// assert_eq!(parser.parse(&b\"\"[..]), Err(Err::Incomplete(Needed::new(2))));\n/// ```\n#[inline]\npub fn be_i16>() -> impl Parser\nwhere\n I: Input,\n{\n be_u16().map(|x| x as i16)\n}\n\n/// Recognizes a big endian signed 3 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_i24;\n///\n/// let mut parser = be_i24::<_, (_, ErrorKind)>();\n///\n/// assert_eq!(parser.parse(&b\"\\x00\\x01\\x02abcd\"[..]), Ok((&b\"abcd\"[..], 0x000102)));\n/// assert_eq!(parser.parse(&b\"\"[..]), Err(Err::Incomplete(Needed::new(3))));\n/// ```\n#[inline]\npub fn be_i24>() -> impl Parser\nwhere\n I: Input,\n{\n // Same as the unsigned version but we need to sign-extend manually here\n be_u24().map(|x| {\n if x & 0x80_00_00 != 0 {\n (x | 0xff_00_00_00) as i32\n } else {\n x as i32\n }\n })\n}\n\n/// Recognizes a big endian signed 4 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_i32;\n///\n/// let mut parser = be_i32::<_, (_, ErrorKind)>();\n///\n/// assert_eq!(parser.parse(&b\"\\x00\\x01\\x02\\x03abcd\"[..]), Ok((&b\"abcd\"[..], 0x00010203)));\n/// assert_eq!(parser.parse(&b\"\"[..]), Err(Err::Incomplete(Needed::new(4))));\n/// ```\n#[inline]\npub fn be_i32>() -> impl Parser\nwhere\n I: Input,\n{\n be_u32().map(|x| x as i32)\n}\n\n/// Recognizes a big endian signed 8 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_i64;\n///\n/// let mut parser = be_i64::<_, (_, ErrorKind)>();\n///\n/// assert_eq!(parser.parse(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcd\"[..]), Ok((&b\"abcd\"[..], 0x0001020304050607)));\n/// assert_eq!(parser.parse(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(7))));\n/// ```\n#[inline]\npub fn be_i64>() -> impl Parser\nwhere\n I: Input,\n{\n be_u64().map(|x| x as i64)\n}\n\n/// Recognizes a big endian signed 16 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_i128;\n///\n/// let mut parser = be_i128::<_, (_, ErrorKind)>();\n///\n/// assert_eq!(parser.parse(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x10\\x11\\x12\\x13\\x14\\x15abcd\"[..]), Ok((&b\"abcd\"[..], 0x00010203040506070809101112131415)));\n/// assert_eq!(parser.parse(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(15))));\n/// ```\n#[inline]\npub fn be_i128>() -> impl Parser\nwhere\n I: Input,\n{\n be_u128().map(|x| x as i128)\n}\n\n/// creates a little endian unsigned integer parser\n///\n/// * `bound`: the number of bytes that will be read\n/// * `Uint`: the output type\n#[inline]\nfn le_uint>(bound: usize) -> impl Parser\nwhere\n I: Input,\n Uint: Default + Shl + Add + From,\n{\n LeUint {\n bound,\n e: PhantomData,\n u: PhantomData,\n }\n}\n\n/// Little endian unsigned integer parser\nstruct LeUint {\n bound: usize,\n e: PhantomData,\n u: PhantomData,\n}\n\nimpl> Parser for LeUint\nwhere\n I: Input,\n Uint: Default + Shl + Add + From,\n{\n type Output = Uint;\n type Error = E;\n\n #[inline(always)]\n fn process(\n &mut self,\n input: I,\n ) -> crate::PResult {\n if input.input_len() < self.bound {\n if OM::Incomplete::is_streaming() {\n Err(Err::Incomplete(Needed::new(self.bound - input.input_len())))\n } else {\n Err(Err::Error(OM::Error::bind(|| {\n make_error(input, ErrorKind::Eof)\n })))\n }\n } else {\n let res = OM::Output::bind(|| {\n let mut res = Uint::default();\n for (index, byte) in input.iter_elements().take(self.bound).enumerate() {\n res = res + (Uint::from(byte) << (8 * index as u8));\n }\n\n res\n });\n\n Ok((input.take_from(self.bound), res))\n }\n }\n}\n\n/// Recognizes an unsigned 1 byte integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_u8;\n///\n/// let mut parser = le_u8::<_, (_, ErrorKind)>();\n///\n/// assert_eq!(parser.parse(&b\"\\x00\\x01abcd\"[..]), Ok((&b\"\\x01abcd\"[..], 0x00)));\n/// assert_eq!(parser.parse(&b\"\"[..]), Err(Err::Incomplete(Needed::new(1))));\n/// ```\n#[inline]\npub fn le_u8>() -> impl Parser\nwhere\n I: Input,\n{\n le_uint(1)\n}\n\n/// Recognizes a little endian unsigned 2 bytes integer.\n///\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_u16;\n///\n/// let parser = |s| {\n/// le_u16::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01abcd\"[..]), Ok((&b\"abcd\"[..], 0x0100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(1))));\n/// ```\n#[inline]\npub fn le_u16>() -> impl Parser\nwhere\n I: Input,\n{\n le_uint(2)\n}\n\n/// Recognizes a little endian unsigned 3 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_u24;\n///\n/// let parser = |s| {\n/// le_u24::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02abcd\"[..]), Ok((&b\"abcd\"[..], 0x020100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(2))));\n/// ```\n#[inline]\npub fn le_u24>() -> impl Parser\nwhere\n I: Input,\n{\n le_uint(3)\n}\n\n/// Recognizes a little endian unsigned 4 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_u32;\n///\n/// let parser = |s| {\n/// le_u32::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03abcd\"[..]), Ok((&b\"abcd\"[..], 0x03020100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(3))));\n/// ```\n#[inline]\npub fn le_u32>() -> impl Parser\nwhere\n I: Input,\n{\n le_uint(4)\n}\n\n/// Recognizes a little endian unsigned 8 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_u64;\n///\n/// let parser = |s| {\n/// le_u64::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcd\"[..]), Ok((&b\"abcd\"[..], 0x0706050403020100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(7))));\n/// ```\n#[inline]\npub fn le_u64>() -> impl Parser\nwhere\n I: Input,\n{\n le_uint(8)\n}\n\n/// Recognizes a little endian unsigned 16 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_u128;\n///\n/// let mut parser = |s| {\n/// le_u128::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x10\\x11\\x12\\x13\\x14\\x15abcd\"[..]), Ok((&b\"abcd\"[..], 0x15141312111009080706050403020100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(15))));\n/// ```\n#[inline]\npub fn le_u128>() -> impl Parser\nwhere\n I: Input,\n{\n le_uint(16)\n}\n\n/// Recognizes a signed 1 byte integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_i8;\n///\n/// let mut parser = le_i8::<_, (_, ErrorKind)>();\n///\n/// assert_eq!(parser.parse(&b\"\\x00\\x01abcd\"[..]), Ok((&b\"\\x01abcd\"[..], 0x00)));\n/// assert_eq!(parser.parse(&b\"\"[..]), Err(Err::Incomplete(Needed::new(1))));\n/// ```\n#[inline]\npub fn le_i8>() -> impl Parser\nwhere\n I: Input,\n{\n le_u8().map(|x| x as i8)\n}\n\n/// Recognizes a little endian signed 2 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_i16;\n///\n/// let parser = |s| {\n/// le_i16::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01abcd\"[..]), Ok((&b\"abcd\"[..], 0x0100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(1))));\n/// ```\n#[inline]\npub fn le_i16>() -> impl Parser\nwhere\n I: Input,\n{\n le_u16().map(|x| x as i16)\n}\n\n/// Recognizes a little endian signed 3 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_i24;\n///\n/// let parser = |s| {\n/// le_i24::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02abcd\"[..]), Ok((&b\"abcd\"[..], 0x020100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(2))));\n/// ```\n#[inline]\npub fn le_i24>() -> impl Parser\nwhere\n I: Input,\n{\n // Same as the unsigned version but we need to sign-extend manually here\n le_u24().map(|x| {\n if x & 0x80_00_00 != 0 {\n (x | 0xff_00_00_00) as i32\n } else {\n x as i32\n }\n })\n}\n\n/// Recognizes a little endian signed 4 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_i32;\n///\n/// let parser = |s| {\n/// le_i32::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03abcd\"[..]), Ok((&b\"abcd\"[..], 0x03020100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(3))));\n/// ```\n#[inline]\npub fn le_i32>() -> impl Parser\nwhere\n I: Input,\n{\n le_u32().map(|x| x as i32)\n}\n\n/// Recognizes a little endian signed 8 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_i64;\n///\n/// let parser = |s| {\n/// le_i64::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcd\"[..]), Ok((&b\"abcd\"[..], 0x0706050403020100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(7))));\n/// ```\n#[inline]\npub fn le_i64>() -> impl Parser\nwhere\n I: Input,\n{\n le_u64().map(|x| x as i64)\n}\n\n/// Recognizes a little endian signed 16 bytes integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_i128;\n///\n/// let parser = |s| {\n/// le_i128::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x10\\x11\\x12\\x13\\x14\\x15abcd\"[..]), Ok((&b\"abcd\"[..], 0x15141312111009080706050403020100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(15))));\n/// ```\n#[inline]\npub fn le_i128>() -> impl Parser\nwhere\n I: Input,\n{\n le_u128().map(|x| x as i128)\n}\n\n/// Recognizes an unsigned 1 byte integer\n///\n/// Note that endianness does not apply to 1 byte numbers.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::u8;\n///\n/// let parser = |s| {\n/// u8::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"\\x03abcefg\"[..], 0x00)));\n/// assert_eq!(parser(&b\"\"[..]), Err(Err::Incomplete(Needed::new(1))));\n/// ```\n#[inline]\npub fn u8>() -> impl Parser\nwhere\n I: Input,\n{\n be_u8()\n}\n\n/// Recognizes an unsigned 2 bytes integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian u16 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian u16 integer.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::u16;\n///\n/// let be_u16 = |s| {\n/// u16::<_, (_, ErrorKind)>(nom::number::Endianness::Big).parse(s)\n/// };\n///\n/// assert_eq!(be_u16(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0003)));\n/// assert_eq!(be_u16(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(1))));\n///\n/// let le_u16 = |s| {\n/// u16::<_, (_, ErrorKind)>(nom::number::Endianness::Little).parse(s)\n/// };\n///\n/// assert_eq!(le_u16(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0300)));\n/// assert_eq!(le_u16(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(1))));\n/// ```\n#[inline]\npub fn u16>(\n endian: crate::number::Endianness,\n) -> impl Parser\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => Either::Left(be_u16()),\n crate::number::Endianness::Little => Either::Right(le_u16()),\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => Either::Left(be_u16()),\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => Either::Right(le_u16()),\n }\n}\n\n/// Recognizes an unsigned 3 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian u24 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian u24 integer.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::u24;\n///\n/// let be_u24 = |s| {\n/// u24::<_,(_, ErrorKind)>(nom::number::Endianness::Big).parse(s)\n/// };\n///\n/// assert_eq!(be_u24(&b\"\\x00\\x03\\x05abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x000305)));\n/// assert_eq!(be_u24(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(2))));\n///\n/// let le_u24 = |s| {\n/// u24::<_, (_, ErrorKind)>(nom::number::Endianness::Little).parse(s)\n/// };\n///\n/// assert_eq!(le_u24(&b\"\\x00\\x03\\x05abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x050300)));\n/// assert_eq!(le_u24(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(2))));\n/// ```\n#[inline]\npub fn u24>(\n endian: crate::number::Endianness,\n) -> impl Parser\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => Either::Left(be_u24()),\n crate::number::Endianness::Little => Either::Right(le_u24()),\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => Either::Left(be_u24()),\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => Either::Right(le_u24()),\n }\n}\n\n/// Recognizes an unsigned 4 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian u32 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian u32 integer.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::u32;\n///\n/// let be_u32 = |s| {\n/// u32::<_, (_, ErrorKind)>(nom::number::Endianness::Big).parse(s)\n/// };\n///\n/// assert_eq!(be_u32(&b\"\\x00\\x03\\x05\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x00030507)));\n/// assert_eq!(be_u32(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(3))));\n///\n/// let le_u32 = |s| {\n/// u32::<_, (_, ErrorKind)>(nom::number::Endianness::Little).parse(s)\n/// };\n///\n/// assert_eq!(le_u32(&b\"\\x00\\x03\\x05\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x07050300)));\n/// assert_eq!(le_u32(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(3))));\n/// ```\n#[inline]\npub fn u32>(\n endian: crate::number::Endianness,\n) -> impl Parser\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => Either::Left(be_u32()),\n crate::number::Endianness::Little => Either::Right(le_u32()),\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => Either::Left(be_u32()),\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => Either::Right(le_u32()),\n }\n}\n\n/// Recognizes an unsigned 8 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian u64 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian u64 integer.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::u64;\n///\n/// let be_u64 = |s| {\n/// u64::<_, (_, ErrorKind)>(nom::number::Endianness::Big).parse(s)\n/// };\n///\n/// assert_eq!(be_u64(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0001020304050607)));\n/// assert_eq!(be_u64(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(7))));\n///\n/// let le_u64 = |s| {\n/// u64::<_, (_, ErrorKind)>(nom::number::Endianness::Little).parse(s)\n/// };\n///\n/// assert_eq!(le_u64(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0706050403020100)));\n/// assert_eq!(le_u64(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(7))));\n/// ```\n#[inline]\npub fn u64>(\n endian: crate::number::Endianness,\n) -> impl Parser\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => Either::Left(be_u64()),\n crate::number::Endianness::Little => Either::Right(le_u64()),\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => Either::Left(be_u64()),\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => Either::Right(le_u64()),\n }\n}\n\n/// Recognizes an unsigned 16 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian u128 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian u128 integer.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::u128;\n///\n/// let be_u128 = |s| {\n/// u128::<_, (_, ErrorKind)>(nom::number::Endianness::Big).parse(s)\n/// };\n///\n/// assert_eq!(be_u128(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x00010203040506070001020304050607)));\n/// assert_eq!(be_u128(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(15))));\n///\n/// let le_u128 = |s| {\n/// u128::<_, (_, ErrorKind)>(nom::number::Endianness::Little).parse(s)\n/// };\n///\n/// assert_eq!(le_u128(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x07060504030201000706050403020100)));\n/// assert_eq!(le_u128(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(15))));\n/// ```\n#[inline]\npub fn u128>(\n endian: crate::number::Endianness,\n) -> impl Parser\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => Either::Left(be_u128()),\n crate::number::Endianness::Little => Either::Right(le_u128()),\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => Either::Left(be_u128()),\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => Either::Right(le_u128()),\n }\n}\n\n/// Recognizes a signed 1 byte integer\n///\n/// Note that endianness does not apply to 1 byte numbers.\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there is not enough data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::i8;\n///\n/// let parser = |s| {\n/// i8::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"\\x03abcefg\"[..], 0x00)));\n/// assert_eq!(parser(&b\"\"[..]), Err(Err::Incomplete(Needed::new(1))));\n/// ```\n#[inline]\npub fn i8>() -> impl Parser\nwhere\n I: Input,\n{\n u8().map(|x| x as i8)\n}\n\n/// Recognizes a signed 2 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian i16 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian i16 integer.\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there is not enough data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::i16;\n///\n/// let be_i16 = |s| {\n/// i16::<_, (_, ErrorKind)>(nom::number::Endianness::Big).parse(s)\n/// };\n///\n/// assert_eq!(be_i16(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0003)));\n/// assert_eq!(be_i16(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(1))));\n///\n/// let le_i16 = |s| {\n/// i16::<_, (_, ErrorKind)>(nom::number::Endianness::Little).parse(s)\n/// };\n///\n/// assert_eq!(le_i16(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0300)));\n/// assert_eq!(le_i16(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(1))));\n/// ```\n#[inline]\npub fn i16>(\n endian: crate::number::Endianness,\n) -> impl Parser\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => Either::Left(be_i16()),\n crate::number::Endianness::Little => Either::Right(le_i16()),\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => Either::Left(be_i16()),\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => Either::Right(le_i16()),\n }\n}\n\n/// Recognizes a signed 3 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian i24 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian i24 integer.\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there is not enough data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::i24;\n///\n/// let be_i24 = |s| {\n/// i24::<_, (_, ErrorKind)>(nom::number::Endianness::Big).parse(s)\n/// };\n///\n/// assert_eq!(be_i24(&b\"\\x00\\x03\\x05abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x000305)));\n/// assert_eq!(be_i24(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(2))));\n///\n/// let le_i24 = |s| {\n/// i24::<_, (_, ErrorKind)>(nom::number::Endianness::Little).parse(s)\n/// };\n///\n/// assert_eq!(le_i24(&b\"\\x00\\x03\\x05abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x050300)));\n/// assert_eq!(le_i24(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(2))));\n/// ```\n#[inline]\npub fn i24>(\n endian: crate::number::Endianness,\n) -> impl Parser\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => Either::Left(be_i24()),\n crate::number::Endianness::Little => Either::Right(le_i24()),\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => Either::Left(be_i24()),\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => Either::Right(le_i24()),\n }\n}\n\n/// Recognizes a signed 4 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian i32 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian i32 integer.\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there is not enough data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::i32;\n///\n/// let be_i32 = |s| {\n/// i32::<_, (_, ErrorKind)>(nom::number::Endianness::Big).parse(s)\n/// };\n///\n/// assert_eq!(be_i32(&b\"\\x00\\x03\\x05\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x00030507)));\n/// assert_eq!(be_i32(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(3))));\n///\n/// let le_i32 = |s| {\n/// i32::<_, (_, ErrorKind)>(nom::number::Endianness::Little).parse(s)\n/// };\n///\n/// assert_eq!(le_i32(&b\"\\x00\\x03\\x05\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x07050300)));\n/// assert_eq!(le_i32(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(3))));\n/// ```\n#[inline]\npub fn i32>(\n endian: crate::number::Endianness,\n) -> impl Parser\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => Either::Left(be_i32()),\n crate::number::Endianness::Little => Either::Right(le_i32()),\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => Either::Left(be_i32()),\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => Either::Right(le_i32()),\n }\n}\n\n/// Recognizes a signed 8 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian i64 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian i64 integer.\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there is not enough data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::i64;\n///\n/// let be_i64 = |s| {\n/// i64::<_, (_, ErrorKind)>(nom::number::Endianness::Big).parse(s)\n/// };\n///\n/// assert_eq!(be_i64(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0001020304050607)));\n/// assert_eq!(be_i64(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(7))));\n///\n/// let le_i64 = |s| {\n/// i64::<_, (_, ErrorKind)>(nom::number::Endianness::Little).parse(s)\n/// };\n///\n/// assert_eq!(le_i64(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0706050403020100)));\n/// assert_eq!(le_i64(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(7))));\n/// ```\n#[inline]\npub fn i64>(\n endian: crate::number::Endianness,\n) -> impl Parser\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => Either::Left(be_i64()),\n crate::number::Endianness::Little => Either::Right(le_i64()),\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => Either::Left(be_i64()),\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => Either::Right(le_i64()),\n }\n}\n\n/// Recognizes a signed 16 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian i128 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian i128 integer.\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there is not enough data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::i128;\n///\n/// let be_i128 = |s| {\n/// i128::<_, (_, ErrorKind)>(nom::number::Endianness::Big).parse(s)\n/// };\n///\n/// assert_eq!(be_i128(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x00010203040506070001020304050607)));\n/// assert_eq!(be_i128(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(15))));\n///\n/// let le_i128 = |s| {\n/// i128::<_, (_, ErrorKind)>(nom::number::Endianness::Little).parse(s)\n/// };\n///\n/// assert_eq!(le_i128(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x07060504030201000706050403020100)));\n/// assert_eq!(le_i128(&b\"\\x01\"[..]), Err(Err::Incomplete(Needed::new(15))));\n/// ```\n#[inline]\npub fn i128>(\n endian: crate::number::Endianness,\n) -> impl Parser\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => Either::Left(be_i128()),\n crate::number::Endianness::Little => Either::Right(le_i128()),\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => Either::Left(be_i128()),\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => Either::Right(le_i128()),\n }\n}\n\n/// Recognizes a big endian 4 bytes floating point number.\n///\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there is not enough data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_f32;\n///\n/// let parser = |s| {\n/// be_f32::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&[0x40, 0x29, 0x00, 0x00][..]), Ok((&b\"\"[..], 2.640625)));\n/// assert_eq!(parser(&[0x01][..]), Err(Err::Incomplete(Needed::new(3))));\n/// ```\n#[inline]\npub fn be_f32>() -> impl Parser\nwhere\n I: Input,\n{\n be_u32().map(f32::from_bits)\n}\n\n/// Recognizes a big endian 8 bytes floating point number.\n///\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there is not enough data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::be_f64;\n///\n/// let parser = |s| {\n/// be_f64::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&[0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(parser(&[0x01][..]), Err(Err::Incomplete(Needed::new(7))));\n/// ```\n#[inline]\npub fn be_f64>() -> impl Parser\nwhere\n I: Input,\n{\n be_u64().map(f64::from_bits)\n}\n\n/// Recognizes a little endian 4 bytes floating point number.\n///\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there is not enough data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_f32;\n///\n/// let parser = |s| {\n/// le_f32::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&[0x00, 0x00, 0x48, 0x41][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(parser(&[0x01][..]), Err(Err::Incomplete(Needed::new(3))));\n/// ```\n#[inline]\npub fn le_f32>() -> impl Parser\nwhere\n I: Input,\n{\n le_u32().map(f32::from_bits)\n}\n\n/// Recognizes a little endian 8 bytes floating point number.\n///\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there is not enough data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::le_f64;\n///\n/// let parser = |s| {\n/// le_f64::<_, (_, ErrorKind)>().parse(s)\n/// };\n///\n/// assert_eq!(parser(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x41][..]), Ok((&b\"\"[..], 3145728.0)));\n/// assert_eq!(parser(&[0x01][..]), Err(Err::Incomplete(Needed::new(7))));\n/// ```\n#[inline]\npub fn le_f64>() -> impl Parser\nwhere\n I: Input,\n{\n le_u64().map(f64::from_bits)\n}\n\n/// Recognizes a 4 byte floating point number\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian f32 float,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian f32 float.\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there is not enough data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::f32;\n///\n/// let be_f32 = |s| {\n/// f32::<_, (_, ErrorKind)>(nom::number::Endianness::Big).parse(s)\n/// };\n///\n/// assert_eq!(be_f32(&[0x41, 0x48, 0x00, 0x00][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(be_f32(&b\"abc\"[..]), Err(Err::Incomplete(Needed::new(1))));\n///\n/// let le_f32 = |s| {\n/// f32::<_, (_, ErrorKind)>(nom::number::Endianness::Little).parse(s)\n/// };\n///\n/// assert_eq!(le_f32(&[0x00, 0x00, 0x48, 0x41][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(le_f32(&b\"abc\"[..]), Err(Err::Incomplete(Needed::new(1))));\n/// ```\n#[inline]\npub fn f32>(\n endian: crate::number::Endianness,\n) -> impl Parser\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => Either::Left(be_f32()),\n crate::number::Endianness::Little => Either::Right(le_f32()),\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => Either::Left(be_f32()),\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => Either::Right(le_f32()),\n }\n}\n\n/// Recognizes an 8 byte floating point number\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian f64 float,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian f64 float.\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if there is not enough data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::number::f64;\n///\n/// let be_f64 = |s| {\n/// f64::<_, (_, ErrorKind)>(nom::number::Endianness::Big).parse(s)\n/// };\n///\n/// assert_eq!(be_f64(&[0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(be_f64(&b\"abc\"[..]), Err(Err::Incomplete(Needed::new(5))));\n///\n/// let le_f64 = |s| {\n/// f64::<_, (_, ErrorKind)>(nom::number::Endianness::Little).parse(s)\n/// };\n///\n/// assert_eq!(le_f64(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(le_f64(&b\"abc\"[..]), Err(Err::Incomplete(Needed::new(5))));\n/// ```\n#[inline]\npub fn f64>(\n endian: crate::number::Endianness,\n) -> impl Parser\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => Either::Left(be_f64()),\n crate::number::Endianness::Little => Either::Right(le_f64()),\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => Either::Left(be_f64()),\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => Either::Right(le_f64()),\n }\n}\n\n/// Recognizes a floating point number in text format and returns the corresponding part of the input.\n///\n/// *Streaming version*: Will return `Err(nom::Err::Incomplete(_))` if it reaches the end of input.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// use nom::number::recognize_float;\n///\n/// let parser = |s| {\n/// recognize_float().parse(s)\n/// };\n///\n/// assert_eq!(parser(\"11e-1;\"), Ok((\";\", \"11e-1\")));\n/// assert_eq!(parser(\"123E-02;\"), Ok((\";\", \"123E-02\")));\n/// assert_eq!(parser(\"123K-01\"), Ok((\"K-01\", \"123\")));\n/// assert_eq!(parser(\"abc\"), Err(Err::Error((\"abc\", ErrorKind::Char))));\n/// ```\n#[rustfmt::skip]\npub fn recognize_float>() -> impl Parser\nwhere\n T: Clone + Offset,\n T: Input,\n ::Item: AsChar,\n{\n recognize((\n opt(alt((char('+'), char('-')))),\n alt((\n map((digit1(), opt(pair(char('.'), opt(digit1())))), |_| ()),\n map((char('.'), digit1()), |_| ())\n )),\n opt((\n alt((char('e'), char('E'))),\n opt(alt((char('+'), char('-')))),\n cut(digit1())\n ))\n ))\n}\n\n/// float number text parser that also recognizes \"nan\", \"infinity\" and \"inf\" (case insensitive)\npub fn recognize_float_or_exceptions>() -> impl Parser\nwhere\n T: Clone + Offset,\n T: Input + Compare<&'static str>,\n ::Item: AsChar,\n{\n alt((\n recognize_float::<_, E>(),\n |i: T| {\n crate::bytes::streaming::tag_no_case::<_, _, E>(\"nan\")(i.clone())\n .map_err(|_| crate::Err::Error(E::from_error_kind(i, ErrorKind::Float)))\n },\n |i: T| {\n crate::bytes::streaming::tag_no_case::<_, _, E>(\"infinity\")(i.clone())\n .map_err(|_| crate::Err::Error(E::from_error_kind(i, ErrorKind::Float)))\n },\n |i: T| {\n crate::bytes::streaming::tag_no_case::<_, _, E>(\"inf\")(i.clone())\n .map_err(|_| crate::Err::Error(E::from_error_kind(i, ErrorKind::Float)))\n },\n ))\n}\n\n/// single precision floating point number parser from text\npub fn float>() -> impl Parser\nwhere\n T: Clone + Offset,\n T: Input + crate::traits::ParseTo + Compare<&'static str>,\n ::Item: AsChar + Clone,\n T: AsBytes,\n T: for<'a> Compare<&'a [u8]>,\n{\n Float {\n o: PhantomData,\n e: PhantomData,\n }\n}\n\n/// double precision floating point number parser from text\npub fn double>() -> impl Parser\nwhere\n T: Clone + Offset,\n T: Input + crate::traits::ParseTo + Compare<&'static str>,\n ::Item: AsChar + Clone,\n T: AsBytes,\n T: for<'a> Compare<&'a [u8]>,\n{\n Float {\n o: PhantomData,\n e: PhantomData,\n }\n}\n\n/// f64 parser from text\nstruct Float {\n o: PhantomData,\n e: PhantomData,\n}\n\nimpl> Parser for Float\nwhere\n I: Clone + Offset,\n I: Input + crate::traits::ParseTo + Compare<&'static str>,\n ::Item: AsChar + Clone,\n I: AsBytes,\n I: for<'a> Compare<&'a [u8]>,\n{\n type Output = O;\n type Error = E;\n\n fn process(\n &mut self,\n input: I,\n ) -> crate::PResult {\n let (i, s) =\n recognize_float_or_exceptions().process::>(input)?;\n\n match s.parse_to() {\n Some(f) => Ok((i, OM::Output::bind(|| f))),\n None => Err(crate::Err::Error(OM::Error::bind(|| {\n E::from_error_kind(i, crate::error::ErrorKind::Float)\n }))),\n }\n }\n}\n\n#[cfg(test)]\n#[cfg(feature = \"std\")]\nmod tests {\n use super::*;\n use crate::error::ErrorKind;\n use crate::internal::Err;\n\n macro_rules! assert_parse(\n ($left: expr, $right: expr) => {\n let res: $crate::IResult<_, _, (_, ErrorKind)> = $left;\n assert_eq!(res, $right);\n };\n );\n\n #[test]\n fn float_test() {\n let mut test_cases = vec![\n \"+3.14\",\n \"3.14\",\n \"-3.14\",\n \"0\",\n \"0.0\",\n \"1.\",\n \".789\",\n \"-.5\",\n \"1e7\",\n \"-1E-7\",\n \".3e-2\",\n \"1.e4\",\n \"1.2e4\",\n \"12.34\",\n \"-1.234E-12\",\n \"-1.234e-12\",\n \"0.00000000000000000087\",\n ];\n\n for test in test_cases.drain(..) {\n let expected32 = str::parse::(test).unwrap();\n let expected64 = str::parse::(test).unwrap();\n\n println!(\"now parsing: {} -> {}\", test, expected32);\n\n assert_parse!(recognize_float().parse_complete(test), Ok((\"\", test)));\n\n assert_parse!(float(test), Ok((\"\", expected32)));\n\n assert_parse!(\n double().parse_complete(test.as_bytes()),\n Ok((&b\"\"[..], expected64))\n );\n assert_parse!(double().parse_complete(test), Ok((\"\", expected64)));\n }\n\n let remaining_exponent = \"-1.234E-\";\n assert_parse!(\n recognize_float().parse_complete(remaining_exponent),\n Err(Err::Failure((\"\", ErrorKind::Digit)))\n );\n\n assert!(nan.is_nan());\n\n let (_i, inf) = float::<_, ()>(\"inf\").unwrap();\n assert!(inf.is_infinite());\n let (i, inf) = float::<_, ()>(\"infinity\").unwrap();\n assert!(inf.is_infinite());\n assert!(i.is_empty());*/\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "complete.rs", "content": "use crate::branch::alt;\nuse crate::bytes::complete::tag;\nuse crate::character::complete::{char, digit1, sign};\nuse crate::combinator::{cut, map, opt, recognize};\nuse crate::error::ErrorKind;\nuse crate::error::ParseError;\nuse crate::internal::*;\nuse crate::lib::std::ops::{Add, Shl};\nuse crate::sequence::pair;\nuse crate::traits::{AsBytes, AsChar, Compare, Input, Offset};\n\n/// Recognizes an unsigned 1 byte integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_u8;\n///\n/// let parser = |s| {\n/// be_u8(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"\\x03abcefg\"[..], 0x00)));\n/// assert_eq!(parser(&b\"\"[..]), Err(Err::Error((&[][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_u8>(input: I) -> IResult\nwhere\n I: Input,\n{\n be_uint(input, 1)\n}\n\n/// Recognizes a big endian unsigned 2 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_u16;\n///\n/// let parser = |s| {\n/// be_u16(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0003)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_u16>(input: I) -> IResult\nwhere\n I: Input,\n{\n be_uint(input, 2)\n}\n\n/// Recognizes a big endian unsigned 3 byte integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_u24;\n///\n/// let parser = |s| {\n/// be_u24(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03\\x05abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x000305)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_u24>(input: I) -> IResult\nwhere\n I: Input,\n{\n be_uint(input, 3)\n}\n\n/// Recognizes a big endian unsigned 4 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_u32;\n///\n/// let parser = |s| {\n/// be_u32(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03\\x05\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x00030507)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_u32>(input: I) -> IResult\nwhere\n I: Input,\n{\n be_uint(input, 4)\n}\n\n/// Recognizes a big endian unsigned 8 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_u64;\n///\n/// let parser = |s| {\n/// be_u64(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0001020304050607)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_u64>(input: I) -> IResult\nwhere\n I: Input,\n{\n be_uint(input, 8)\n}\n\n/// Recognizes a big endian unsigned 16 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_u128;\n///\n/// let parser = |s| {\n/// be_u128(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x00010203040506070001020304050607)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_u128>(input: I) -> IResult\nwhere\n I: Input,\n{\n be_uint(input, 16)\n}\n\n#[inline]\nfn be_uint>(input: I, bound: usize) -> IResult\nwhere\n I: Input,\n Uint: Default + Shl + Add + From,\n{\n super::be_uint(bound).parse_complete(input)\n}\n\n/// Recognizes a signed 1 byte integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_i8;\n///\n/// let parser = |s| {\n/// be_i8(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"\\x03abcefg\"[..], 0x00)));\n/// assert_eq!(parser(&b\"\"[..]), Err(Err::Error((&[][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_i8>(input: I) -> IResult\nwhere\n I: Input,\n{\n be_u8.map(|x| x as i8).parse(input)\n}\n\n/// Recognizes a big endian signed 2 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_i16;\n///\n/// let parser = |s| {\n/// be_i16(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0003)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_i16>(input: I) -> IResult\nwhere\n I: Input,\n{\n be_u16.map(|x| x as i16).parse(input)\n}\n\n/// Recognizes a big endian signed 3 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_i24;\n///\n/// let parser = |s| {\n/// be_i24(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03\\x05abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x000305)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_i24>(input: I) -> IResult\nwhere\n I: Input,\n{\n // Same as the unsigned version but we need to sign-extend manually here\n be_u24\n .map(|x| {\n if x & 0x80_00_00 != 0 {\n (x | 0xff_00_00_00) as i32\n } else {\n x as i32\n }\n })\n .parse(input)\n}\n\n/// Recognizes a big endian signed 4 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_i32;\n///\n/// let parser = |s| {\n/// be_i32(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03\\x05\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x00030507)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_i32>(input: I) -> IResult\nwhere\n I: Input,\n{\n be_u32.map(|x| x as i32).parse(input)\n}\n\n/// Recognizes a big endian signed 8 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_i64;\n///\n/// let parser = |s| {\n/// be_i64(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0001020304050607)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_i64>(input: I) -> IResult\nwhere\n I: Input,\n{\n be_u64.map(|x| x as i64).parse(input)\n}\n\n/// Recognizes a big endian signed 16 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_i128;\n///\n/// let parser = |s| {\n/// be_i128(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x00010203040506070001020304050607)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_i128>(input: I) -> IResult\nwhere\n I: Input,\n{\n be_u128.map(|x| x as i128).parse(input)\n}\n\n/// Recognizes an unsigned 1 byte integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_u8;\n///\n/// let parser = |s| {\n/// le_u8(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"\\x03abcefg\"[..], 0x00)));\n/// assert_eq!(parser(&b\"\"[..]), Err(Err::Error((&[][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_u8>(input: I) -> IResult\nwhere\n I: Input,\n{\n le_uint(input, 1)\n}\n\n/// Recognizes a little endian unsigned 2 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_u16;\n///\n/// let parser = |s| {\n/// le_u16(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0300)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_u16>(input: I) -> IResult\nwhere\n I: Input,\n{\n le_uint(input, 2)\n}\n\n/// Recognizes a little endian unsigned 3 byte integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_u24;\n///\n/// let parser = |s| {\n/// le_u24(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03\\x05abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x050300)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_u24>(input: I) -> IResult\nwhere\n I: Input,\n{\n le_uint(input, 3)\n}\n\n/// Recognizes a little endian unsigned 4 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_u32;\n///\n/// let parser = |s| {\n/// le_u32(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03\\x05\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x07050300)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_u32>(input: I) -> IResult\nwhere\n I: Input,\n{\n le_uint(input, 4)\n}\n\n/// Recognizes a little endian unsigned 8 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_u64;\n///\n/// let parser = |s| {\n/// le_u64(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0706050403020100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_u64>(input: I) -> IResult\nwhere\n I: Input,\n{\n le_uint(input, 8)\n}\n\n/// Recognizes a little endian unsigned 16 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_u128;\n///\n/// let parser = |s| {\n/// le_u128(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x07060504030201000706050403020100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_u128>(input: I) -> IResult\nwhere\n I: Input,\n{\n le_uint(input, 16)\n}\n\n#[inline]\nfn le_uint>(input: I, bound: usize) -> IResult\nwhere\n I: Input,\n Uint: Default + Shl + Add + From,\n{\n super::le_uint(bound).parse_complete(input)\n}\n\n/// Recognizes a signed 1 byte integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_i8;\n///\n/// let parser = |s| {\n/// le_i8(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"\\x03abcefg\"[..], 0x00)));\n/// assert_eq!(parser(&b\"\"[..]), Err(Err::Error((&[][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_i8>(input: I) -> IResult\nwhere\n I: Input,\n{\n be_u8.map(|x| x as i8).parse(input)\n}\n\n/// Recognizes a little endian signed 2 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_i16;\n///\n/// let parser = |s| {\n/// le_i16(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0300)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_i16>(input: I) -> IResult\nwhere\n I: Input,\n{\n le_u16.map(|x| x as i16).parse(input)\n}\n\n/// Recognizes a little endian signed 3 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_i24;\n///\n/// let parser = |s| {\n/// le_i24(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03\\x05abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x050300)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_i24>(input: I) -> IResult\nwhere\n I: Input,\n{\n // Same as the unsigned version but we need to sign-extend manually here\n le_u24\n .map(|x| {\n if x & 0x80_00_00 != 0 {\n (x | 0xff_00_00_00) as i32\n } else {\n x as i32\n }\n })\n .parse(input)\n}\n\n/// Recognizes a little endian signed 4 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_i32;\n///\n/// let parser = |s| {\n/// le_i32(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03\\x05\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x07050300)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_i32>(input: I) -> IResult\nwhere\n I: Input,\n{\n le_u32.map(|x| x as i32).parse(input)\n}\n\n/// Recognizes a little endian signed 8 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_i64;\n///\n/// let parser = |s| {\n/// le_i64(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0706050403020100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_i64>(input: I) -> IResult\nwhere\n I: Input,\n{\n le_u64.map(|x| x as i64).parse(input)\n}\n\n/// Recognizes a little endian signed 16 bytes integer.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_i128;\n///\n/// let parser = |s| {\n/// le_i128(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x07060504030201000706050403020100)));\n/// assert_eq!(parser(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_i128>(input: I) -> IResult\nwhere\n I: Input,\n{\n le_u128.map(|x| x as i128).parse(input)\n}\n\n/// Recognizes an unsigned 1 byte integer\n///\n/// Note that endianness does not apply to 1 byte numbers.\n/// *complete version*: returns an error if there is not enough input data\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::u8;\n///\n/// let parser = |s| {\n/// u8(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"\\x03abcefg\"[..], 0x00)));\n/// assert_eq!(parser(&b\"\"[..]), Err(Err::Error((&[][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn u8>(input: I) -> IResult\nwhere\n I: Input,\n{\n super::u8().parse_complete(input)\n}\n\n/// Recognizes an unsigned 2 bytes integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian u16 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian u16 integer.\n/// *complete version*: returns an error if there is not enough input data\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::u16;\n///\n/// let be_u16 = |s| {\n/// u16(nom::number::Endianness::Big)(s)\n/// };\n///\n/// assert_eq!(be_u16(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0003)));\n/// assert_eq!(be_u16(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n///\n/// let le_u16 = |s| {\n/// u16(nom::number::Endianness::Little)(s)\n/// };\n///\n/// assert_eq!(le_u16(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0300)));\n/// assert_eq!(le_u16(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn u16>(\n endian: crate::number::Endianness,\n) -> impl Fn(I) -> IResult\nwhere\n I: Input,\n{\n move |input| super::u16(endian).parse_complete(input)\n}\n\n/// Recognizes an unsigned 3 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian u24 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian u24 integer.\n/// *complete version*: returns an error if there is not enough input data\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::u24;\n///\n/// let be_u24 = |s| {\n/// u24(nom::number::Endianness::Big)(s)\n/// };\n///\n/// assert_eq!(be_u24(&b\"\\x00\\x03\\x05abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x000305)));\n/// assert_eq!(be_u24(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n///\n/// let le_u24 = |s| {\n/// u24(nom::number::Endianness::Little)(s)\n/// };\n///\n/// assert_eq!(le_u24(&b\"\\x00\\x03\\x05abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x050300)));\n/// assert_eq!(le_u24(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn u24>(\n endian: crate::number::Endianness,\n) -> impl Fn(I) -> IResult\nwhere\n I: Input,\n{\n move |input| super::u24(endian).parse_complete(input)\n}\n\n/// Recognizes an unsigned 4 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian u32 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian u32 integer.\n/// *complete version*: returns an error if there is not enough input data\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::u32;\n///\n/// let be_u32 = |s| {\n/// u32(nom::number::Endianness::Big)(s)\n/// };\n///\n/// assert_eq!(be_u32(&b\"\\x00\\x03\\x05\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x00030507)));\n/// assert_eq!(be_u32(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n///\n/// let le_u32 = |s| {\n/// u32(nom::number::Endianness::Little)(s)\n/// };\n///\n/// assert_eq!(le_u32(&b\"\\x00\\x03\\x05\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x07050300)));\n/// assert_eq!(le_u32(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn u32>(\n endian: crate::number::Endianness,\n) -> impl Fn(I) -> IResult\nwhere\n I: Input,\n{\n move |input| super::u32(endian).parse_complete(input)\n}\n\n/// Recognizes an unsigned 8 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian u64 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian u64 integer.\n/// *complete version*: returns an error if there is not enough input data\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::u64;\n///\n/// let be_u64 = |s| {\n/// u64(nom::number::Endianness::Big)(s)\n/// };\n///\n/// assert_eq!(be_u64(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0001020304050607)));\n/// assert_eq!(be_u64(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n///\n/// let le_u64 = |s| {\n/// u64(nom::number::Endianness::Little)(s)\n/// };\n///\n/// assert_eq!(le_u64(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0706050403020100)));\n/// assert_eq!(le_u64(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn u64>(\n endian: crate::number::Endianness,\n) -> impl Fn(I) -> IResult\nwhere\n I: Input,\n{\n move |input| super::u64(endian).parse_complete(input)\n}\n\n/// Recognizes an unsigned 16 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian u128 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian u128 integer.\n/// *complete version*: returns an error if there is not enough input data\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::u128;\n///\n/// let be_u128 = |s| {\n/// u128(nom::number::Endianness::Big)(s)\n/// };\n///\n/// assert_eq!(be_u128(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x00010203040506070001020304050607)));\n/// assert_eq!(be_u128(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n///\n/// let le_u128 = |s| {\n/// u128(nom::number::Endianness::Little)(s)\n/// };\n///\n/// assert_eq!(le_u128(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x07060504030201000706050403020100)));\n/// assert_eq!(le_u128(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn u128>(\n endian: crate::number::Endianness,\n) -> impl Fn(I) -> IResult\nwhere\n I: Input,\n{\n move |input| super::u128(endian).parse_complete(input)\n}\n\n/// Recognizes a signed 1 byte integer\n///\n/// Note that endianness does not apply to 1 byte numbers.\n/// *complete version*: returns an error if there is not enough input data\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::i8;\n///\n/// let parser = |s| {\n/// i8(s)\n/// };\n///\n/// assert_eq!(parser(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"\\x03abcefg\"[..], 0x00)));\n/// assert_eq!(parser(&b\"\"[..]), Err(Err::Error((&[][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn i8>(i: I) -> IResult\nwhere\n I: Input,\n{\n super::u8().map(|x| x as i8).parse_complete(i)\n}\n\n/// Recognizes a signed 2 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian i16 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian i16 integer.\n/// *complete version*: returns an error if there is not enough input data\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::i16;\n///\n/// let be_i16 = |s| {\n/// i16(nom::number::Endianness::Big)(s)\n/// };\n///\n/// assert_eq!(be_i16(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0003)));\n/// assert_eq!(be_i16(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n///\n/// let le_i16 = |s| {\n/// i16(nom::number::Endianness::Little)(s)\n/// };\n///\n/// assert_eq!(le_i16(&b\"\\x00\\x03abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0300)));\n/// assert_eq!(le_i16(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn i16>(\n endian: crate::number::Endianness,\n) -> impl Fn(I) -> IResult\nwhere\n I: Input,\n{\n move |input| super::i16(endian).parse_complete(input)\n}\n\n/// Recognizes a signed 3 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian i24 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian i24 integer.\n/// *complete version*: returns an error if there is not enough input data\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::i24;\n///\n/// let be_i24 = |s| {\n/// i24(nom::number::Endianness::Big)(s)\n/// };\n///\n/// assert_eq!(be_i24(&b\"\\x00\\x03\\x05abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x000305)));\n/// assert_eq!(be_i24(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n///\n/// let le_i24 = |s| {\n/// i24(nom::number::Endianness::Little)(s)\n/// };\n///\n/// assert_eq!(le_i24(&b\"\\x00\\x03\\x05abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x050300)));\n/// assert_eq!(le_i24(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn i24>(\n endian: crate::number::Endianness,\n) -> impl Fn(I) -> IResult\nwhere\n I: Input,\n{\n move |input| super::i24(endian).parse_complete(input)\n}\n\n/// Recognizes a signed 4 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian i32 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian i32 integer.\n/// *complete version*: returns an error if there is not enough input data\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::i32;\n///\n/// let be_i32 = |s| {\n/// i32(nom::number::Endianness::Big)(s)\n/// };\n///\n/// assert_eq!(be_i32(&b\"\\x00\\x03\\x05\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x00030507)));\n/// assert_eq!(be_i32(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n///\n/// let le_i32 = |s| {\n/// i32(nom::number::Endianness::Little)(s)\n/// };\n///\n/// assert_eq!(le_i32(&b\"\\x00\\x03\\x05\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x07050300)));\n/// assert_eq!(le_i32(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn i32>(\n endian: crate::number::Endianness,\n) -> impl Fn(I) -> IResult\nwhere\n I: Input,\n{\n move |input| super::i32(endian).parse_complete(input)\n}\n\n/// Recognizes a signed 8 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian i64 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian i64 integer.\n/// *complete version*: returns an error if there is not enough input data\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::i64;\n///\n/// let be_i64 = |s| {\n/// i64(nom::number::Endianness::Big)(s)\n/// };\n///\n/// assert_eq!(be_i64(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0001020304050607)));\n/// assert_eq!(be_i64(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n///\n/// let le_i64 = |s| {\n/// i64(nom::number::Endianness::Little)(s)\n/// };\n///\n/// assert_eq!(le_i64(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x0706050403020100)));\n/// assert_eq!(le_i64(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn i64>(\n endian: crate::number::Endianness,\n) -> impl Fn(I) -> IResult\nwhere\n I: Input,\n{\n move |input| super::i64(endian).parse_complete(input)\n}\n\n/// Recognizes a signed 16 byte integer\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian i128 integer,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian i128 integer.\n/// *complete version*: returns an error if there is not enough input data\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::i128;\n///\n/// let be_i128 = |s| {\n/// i128(nom::number::Endianness::Big)(s)\n/// };\n///\n/// assert_eq!(be_i128(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x00010203040506070001020304050607)));\n/// assert_eq!(be_i128(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n///\n/// let le_i128 = |s| {\n/// i128(nom::number::Endianness::Little)(s)\n/// };\n///\n/// assert_eq!(le_i128(&b\"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07abcefg\"[..]), Ok((&b\"abcefg\"[..], 0x07060504030201000706050403020100)));\n/// assert_eq!(le_i128(&b\"\\x01\"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn i128>(\n endian: crate::number::Endianness,\n) -> impl Fn(I) -> IResult\nwhere\n I: Input,\n{\n move |input| super::i128(endian).parse_complete(input)\n}\n\n/// Recognizes a big endian 4 bytes floating point number.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_f32;\n///\n/// let parser = |s| {\n/// be_f32(s)\n/// };\n///\n/// assert_eq!(parser(&[0x41, 0x48, 0x00, 0x00][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(parser(&b\"abc\"[..]), Err(Err::Error((&b\"abc\"[..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_f32>(input: I) -> IResult\nwhere\n I: Input,\n{\n match be_u32(input) {\n Err(e) => Err(e),\n Ok((i, o)) => Ok((i, f32::from_bits(o))),\n }\n}\n\n/// Recognizes a big endian 8 bytes floating point number.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::be_f64;\n///\n/// let parser = |s| {\n/// be_f64(s)\n/// };\n///\n/// assert_eq!(parser(&[0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(parser(&b\"abc\"[..]), Err(Err::Error((&b\"abc\"[..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn be_f64>(input: I) -> IResult\nwhere\n I: Input,\n{\n match be_u64(input) {\n Err(e) => Err(e),\n Ok((i, o)) => Ok((i, f64::from_bits(o))),\n }\n}\n\n/// Recognizes a little endian 4 bytes floating point number.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_f32;\n///\n/// let parser = |s| {\n/// le_f32(s)\n/// };\n///\n/// assert_eq!(parser(&[0x00, 0x00, 0x48, 0x41][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(parser(&b\"abc\"[..]), Err(Err::Error((&b\"abc\"[..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_f32>(input: I) -> IResult\nwhere\n I: Input,\n{\n match le_u32(input) {\n Err(e) => Err(e),\n Ok((i, o)) => Ok((i, f32::from_bits(o))),\n }\n}\n\n/// Recognizes a little endian 8 bytes floating point number.\n///\n/// *Complete version*: Returns an error if there is not enough input data.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::le_f64;\n///\n/// let parser = |s| {\n/// le_f64(s)\n/// };\n///\n/// assert_eq!(parser(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(parser(&b\"abc\"[..]), Err(Err::Error((&b\"abc\"[..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn le_f64>(input: I) -> IResult\nwhere\n I: Input,\n{\n match le_u64(input) {\n Err(e) => Err(e),\n Ok((i, o)) => Ok((i, f64::from_bits(o))),\n }\n}\n\n/// Recognizes a 4 byte floating point number\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian f32 float,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian f32 float.\n/// *complete version*: returns an error if there is not enough input data\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::f32;\n///\n/// let be_f32 = |s| {\n/// f32(nom::number::Endianness::Big)(s)\n/// };\n///\n/// assert_eq!(be_f32(&[0x41, 0x48, 0x00, 0x00][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(be_f32(&b\"abc\"[..]), Err(Err::Error((&b\"abc\"[..], ErrorKind::Eof))));\n///\n/// let le_f32 = |s| {\n/// f32(nom::number::Endianness::Little)(s)\n/// };\n///\n/// assert_eq!(le_f32(&[0x00, 0x00, 0x48, 0x41][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(le_f32(&b\"abc\"[..]), Err(Err::Error((&b\"abc\"[..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn f32>(endian: crate::number::Endianness) -> fn(I) -> IResult\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => be_f32,\n crate::number::Endianness::Little => le_f32,\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => be_f32,\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => le_f32,\n }\n}\n\n/// Recognizes an 8 byte floating point number\n///\n/// If the parameter is `nom::number::Endianness::Big`, parse a big endian f64 float,\n/// otherwise if `nom::number::Endianness::Little` parse a little endian f64 float.\n/// *complete version*: returns an error if there is not enough input data\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::f64;\n///\n/// let be_f64 = |s| {\n/// f64(nom::number::Endianness::Big)(s)\n/// };\n///\n/// assert_eq!(be_f64(&[0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(be_f64(&b\"abc\"[..]), Err(Err::Error((&b\"abc\"[..], ErrorKind::Eof))));\n///\n/// let le_f64 = |s| {\n/// f64(nom::number::Endianness::Little)(s)\n/// };\n///\n/// assert_eq!(le_f64(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40][..]), Ok((&b\"\"[..], 12.5)));\n/// assert_eq!(le_f64(&b\"abc\"[..]), Err(Err::Error((&b\"abc\"[..], ErrorKind::Eof))));\n/// ```\n#[inline]\npub fn f64>(endian: crate::number::Endianness) -> fn(I) -> IResult\nwhere\n I: Input,\n{\n match endian {\n crate::number::Endianness::Big => be_f64,\n crate::number::Endianness::Little => le_f64,\n #[cfg(target_endian = \"big\")]\n crate::number::Endianness::Native => be_f64,\n #[cfg(target_endian = \"little\")]\n crate::number::Endianness::Native => le_f64,\n }\n}\n\n/// Recognizes a hex-encoded integer.\n///\n/// *Complete version*: Will parse until the end of input if it has less than 8 bytes.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::hex_u32;\n///\n/// let parser = |s| {\n/// hex_u32(s)\n/// };\n///\n/// assert_eq!(parser(&b\"01AE\"[..]), Ok((&b\"\"[..], 0x01AE)));\n/// assert_eq!(parser(&b\"abc\"[..]), Ok((&b\"\"[..], 0x0ABC)));\n/// assert_eq!(parser(&b\"ggg\"[..]), Err(Err::Error((&b\"ggg\"[..], ErrorKind::IsA))));\n/// ```\n#[inline]\npub fn hex_u32>(input: I) -> IResult\nwhere\n I: Input,\n ::Item: AsChar,\n I: AsBytes,\n{\n let e: ErrorKind = ErrorKind::IsA;\n let (i, o) = input.split_at_position1_complete(\n |c| {\n let c = c.as_char();\n !\"0123456789abcdefABCDEF\".contains(c)\n },\n e,\n )?;\n\n // Do not parse more than 8 characters for a u32\n let (remaining, parsed) = if o.input_len() <= 8 {\n (i, o)\n } else {\n input.take_split(8)\n };\n\n let res = parsed\n .as_bytes()\n .iter()\n .rev()\n .enumerate()\n .map(|(k, &v)| {\n let digit = v as char;\n digit.to_digit(16).unwrap_or(0) << (k * 4)\n })\n .sum();\n\n Ok((remaining, res))\n}\n\n/// Recognizes floating point number in a byte string and returns the corresponding slice.\n///\n/// *Complete version*: Can parse until the end of input.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::recognize_float;\n///\n/// let parser = |s| {\n/// recognize_float(s)\n/// };\n///\n/// assert_eq!(parser(\"11e-1\"), Ok((\"\", \"11e-1\")));\n/// assert_eq!(parser(\"123E-02\"), Ok((\"\", \"123E-02\")));\n/// assert_eq!(parser(\"123K-01\"), Ok((\"K-01\", \"123\")));\n/// assert_eq!(parser(\"abc\"), Err(Err::Error((\"abc\", ErrorKind::Char))));\n/// ```\n#[rustfmt::skip]\npub fn recognize_float>(input: T) -> IResult\nwhere\n T: Clone + Offset,\n T: Input,\n ::Item: AsChar,\n{\n recognize((\n opt(alt((char('+'), char('-')))),\n alt((\n map((digit1, opt(pair(char('.'), opt(digit1)))), |_| ()),\n map((char('.'), digit1), |_| ())\n )),\n opt((\n alt((char('e'), char('E'))),\n opt(alt((char('+'), char('-')))),\n cut(digit1)\n ))\n )).parse(input)\n}\n\n// workaround until issues with minimal-lexical are fixed\n#[doc(hidden)]\npub fn recognize_float_or_exceptions>(input: T) -> IResult\nwhere\n T: Clone + Offset,\n T: Input + Compare<&'static str>,\n ::Item: AsChar,\n{\n alt((\n |i: T| {\n recognize_float::<_, E>(i.clone()).map_err(|e| match e {\n crate::Err::Error(_) => crate::Err::Error(E::from_error_kind(i, ErrorKind::Float)),\n crate::Err::Failure(_) => crate::Err::Failure(E::from_error_kind(i, ErrorKind::Float)),\n crate::Err::Incomplete(needed) => crate::Err::Incomplete(needed),\n })\n },\n |i: T| {\n crate::bytes::complete::tag_no_case::<_, _, E>(\"nan\")(i.clone())\n .map_err(|_| crate::Err::Error(E::from_error_kind(i, ErrorKind::Float)))\n },\n |i: T| {\n crate::bytes::complete::tag_no_case::<_, _, E>(\"infinity\")(i.clone())\n .map_err(|_| crate::Err::Error(E::from_error_kind(i, ErrorKind::Float)))\n },\n |i: T| {\n crate::bytes::complete::tag_no_case::<_, _, E>(\"inf\")(i.clone())\n .map_err(|_| crate::Err::Error(E::from_error_kind(i, ErrorKind::Float)))\n },\n ))\n .parse(input)\n}\n\n/// Recognizes a floating point number in text format\n///\n/// It returns a tuple of (`sign`, `integer part`, `fraction part` and `exponent`) of the input\n/// data.\n///\n/// *Complete version*: Can parse until the end of input.\n///\npub fn recognize_float_parts>(input: T) -> IResult\nwhere\n T: Clone + Offset,\n T: Input,\n ::Item: AsChar,\n T: for<'a> Compare<&'a [u8]>,\n T: AsBytes,\n{\n let (i, sign) = sign(input.clone())?;\n\n //let (i, zeroes) = take_while(|c: ::Item| c.as_char() == '0')(i)?;\n let (i, zeroes) = match i.as_bytes().iter().position(|c| *c != b'0') {\n Some(index) => i.take_split(index),\n None => i.take_split(i.input_len()),\n };\n //let (i, mut integer) = digit0(i)?;\n let (i, mut integer) = match i\n .as_bytes()\n .iter()\n .position(|c| !(*c >= b'0' && *c <= b'9'))\n {\n Some(index) => i.take_split(index),\n None => i.take_split(i.input_len()),\n };\n\n if integer.input_len() == 0 && zeroes.input_len() > 0 {\n // keep the last zero if integer is empty\n integer = zeroes.take_from(zeroes.input_len() - 1);\n }\n\n let (i, opt_dot) = opt(tag(&b\".\"[..])).parse(i)?;\n let (i, fraction) = if opt_dot.is_none() {\n let i2 = i.clone();\n (i2, i.take(0))\n } else {\n // match number, trim right zeroes\n let mut zero_count = 0usize;\n let mut position = None;\n for (pos, c) in i.as_bytes().iter().enumerate() {\n if *c >= b'0' && *c <= b'9' {\n if *c == b'0' {\n zero_count += 1;\n } else {\n zero_count = 0;\n }\n } else {\n position = Some(pos);\n break;\n }\n }\n\n #[allow(clippy::or_fun_call)]\n let position = position.unwrap_or(i.input_len());\n\n let index = if zero_count == 0 {\n position\n } else if zero_count == position {\n position - zero_count + 1\n } else {\n position - zero_count\n };\n\n (i.take_from(position), i.take(index))\n };\n\n if integer.input_len() == 0 && fraction.input_len() == 0 {\n return Err(Err::Error(E::from_error_kind(input, ErrorKind::Float)));\n }\n\n let i2 = i.clone();\n let (i, e) = match i.as_bytes().iter().next() {\n Some(b'e') => (i.take_from(1), true),\n Some(b'E') => (i.take_from(1), true),\n _ => (i, false),\n };\n\n let (i, exp) = if e {\n cut(crate::character::complete::i32).parse(i)?\n } else {\n (i2, 0)\n };\n\n Ok((i, (sign, integer, fraction, exp)))\n}\n\nuse crate::traits::ParseTo;\n\n/// Recognizes floating point number in text format and returns a f32.\n///\n/// *Complete version*: Can parse until the end of input.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::float;\n///\n/// let parser = |s| {\n/// float(s)\n/// };\n///\n/// assert_eq!(parser(\"11e-1\"), Ok((\"\", 1.1)));\n/// assert_eq!(parser(\"123E-02\"), Ok((\"\", 1.23)));\n/// assert_eq!(parser(\"123K-01\"), Ok((\"K-01\", 123.0)));\n/// assert_eq!(parser(\"abc\"), Err(Err::Error((\"abc\", ErrorKind::Float))));\n/// ```\npub fn float>(input: T) -> IResult\nwhere\n T: Clone + Offset + ParseTo + Compare<&'static str>,\n T: Input,\n ::Item: AsChar,\n ::Iter: Clone,\n T: AsBytes,\n T: for<'a> Compare<&'a [u8]>,\n{\n let (i, (sign, integer, fraction, exponent)) = recognize_float_parts(input)?;\n\n let mut float: f32 = minimal_lexical::parse_float(\n integer.as_bytes().iter(),\n fraction.as_bytes().iter(),\n exponent,\n );\n if !sign {\n float = -float;\n }\n\n Ok((i, float))\n let (i, s) = recognize_float_or_exceptions(input)?;\n match s.parse_to() {\n Some(f) => Ok((i, f)),\n None => Err(crate::Err::Error(E::from_error_kind(\n i,\n crate::error::ErrorKind::Float,\n ))),\n }\n}\n\n/// Recognizes floating point number in text format and returns a f64.\n///\n/// *Complete version*: Can parse until the end of input.\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed};\n/// # use nom::Needed::Size;\n/// use nom::number::complete::double;\n///\n/// let parser = |s| {\n/// double(s)\n/// };\n///\n/// assert_eq!(parser(\"11e-1\"), Ok((\"\", 1.1)));\n/// assert_eq!(parser(\"123E-02\"), Ok((\"\", 1.23)));\n/// assert_eq!(parser(\"123K-01\"), Ok((\"K-01\", 123.0)));\n/// assert_eq!(parser(\"abc\"), Err(Err::Error((\"abc\", ErrorKind::Float))));\n/// ```\npub fn double>(input: T) -> IResult\nwhere\n T: Clone + Offset + ParseTo + Compare<&'static str>,\n T: Input,\n ::Item: AsChar,\n ::Iter: Clone,\n T: AsBytes,\n T: for<'a> Compare<&'a [u8]>,\n{\n let (i, (sign, integer, fraction, exponent)) = recognize_float_parts(input)?;\n\n let mut float: f64 = minimal_lexical::parse_float(\n integer.as_bytes().iter(),\n fraction.as_bytes().iter(),\n exponent,\n );\n if !sign {\n float = -float;\n }\n\n Ok((i, float))\n let (i, s) = recognize_float_or_exceptions(input)?;\n match s.parse_to() {\n Some(f) => Ok((i, f)),\n None => Err(crate::Err::Error(E::from_error_kind(\n i,\n crate::error::ErrorKind::Float,\n ))),\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use crate::error::ErrorKind;\n use crate::internal::Err;\n use proptest::prelude::*;\n\n macro_rules! assert_parse(\n ($left: expr, $right: expr) => {\n let res: $crate::IResult<_, _, (_, ErrorKind)> = $left;\n assert_eq!(res, $right);\n };\n );\n\n #[test]\n fn i8_tests() {\n assert_parse!(i8(&[0x00][..]), Ok((&b\"\"[..], 0)));\n assert_parse!(i8(&[0x7f][..]), Ok((&b\"\"[..], 127)));\n assert_parse!(i8(&[0xff][..]), Ok((&b\"\"[..], -1)));\n assert_parse!(i8(&[0x80][..]), Ok((&b\"\"[..], -128)));\n }\n\n #[test]\n fn be_i8_tests() {\n assert_parse!(be_i8(&[0x00][..]), Ok((&b\"\"[..], 0)));\n assert_parse!(be_i8(&[0x7f][..]), Ok((&b\"\"[..], 127)));\n assert_parse!(be_i8(&[0xff][..]), Ok((&b\"\"[..], -1)));\n assert_parse!(be_i8(&[0x80][..]), Ok((&b\"\"[..], -128)));\n }\n\n #[test]\n fn be_i16_tests() {\n assert_parse!(be_i16(&[0x00, 0x00][..]), Ok((&b\"\"[..], 0)));\n assert_parse!(be_i16(&[0x7f, 0xff][..]), Ok((&b\"\"[..], 32_767_i16)));\n assert_parse!(be_i16(&[0xff, 0xff][..]), Ok((&b\"\"[..], -1)));\n assert_parse!(be_i16(&[0x80, 0x00][..]), Ok((&b\"\"[..], -32_768_i16)));\n }\n\n #[test]\n fn be_u24_tests() {\n assert_parse!(be_u24(&[0x00, 0x00, 0x00][..]), Ok((&b\"\"[..], 0)));\n assert_parse!(be_u24(&[0x00, 0xFF, 0xFF][..]), Ok((&b\"\"[..], 65_535_u32)));\n assert_parse!(\n be_u24(&[0x12, 0x34, 0x56][..]),\n Ok((&b\"\"[..], 1_193_046_u32))\n );\n }\n\n #[test]\n fn be_i24_tests() {\n assert_parse!(be_i24(&[0xFF, 0xFF, 0xFF][..]), Ok((&b\"\"[..], -1_i32)));\n assert_parse!(be_i24(&[0xFF, 0x00, 0x00][..]), Ok((&b\"\"[..], -65_536_i32)));\n assert_parse!(\n be_i24(&[0xED, 0xCB, 0xAA][..]),\n Ok((&b\"\"[..], -1_193_046_i32))\n );\n }\n\n #[test]\n fn be_i32_tests() {\n assert_parse!(be_i32(&[0x00, 0x00, 0x00, 0x00][..]), Ok((&b\"\"[..], 0)));\n assert_parse!(\n be_i32(&[0x7f, 0xff, 0xff, 0xff][..]),\n Ok((&b\"\"[..], 2_147_483_647_i32))\n );\n assert_parse!(be_i32(&[0xff, 0xff, 0xff, 0xff][..]), Ok((&b\"\"[..], -1)));\n assert_parse!(\n be_i32(&[0x80, 0x00, 0x00, 0x00][..]),\n Ok((&b\"\"[..], -2_147_483_648_i32))\n );\n }\n\n #[test]\n fn be_i64_tests() {\n assert_parse!(\n be_i64(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]),\n Ok((&b\"\"[..], 0))\n );\n assert_parse!(\n be_i64(&[0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff][..]),\n Ok((&b\"\"[..], 9_223_372_036_854_775_807_i64))\n );\n assert_parse!(\n be_i64(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff][..]),\n Ok((&b\"\"[..], -1))\n );\n assert_parse!(\n be_i64(&[0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]),\n Ok((&b\"\"[..], -9_223_372_036_854_775_808_i64))\n );\n }\n\n #[test]\n fn be_i128_tests() {\n assert_parse!(\n be_i128(\n &[\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00\n ][..]\n ),\n Ok((&b\"\"[..], 0))\n );\n assert_parse!(\n be_i128(\n &[\n 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff\n ][..]\n ),\n Ok((\n &b\"\"[..],\n 170_141_183_460_469_231_731_687_303_715_884_105_727_i128\n ))\n );\n assert_parse!(\n be_i128(\n &[\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff\n ][..]\n ),\n Ok((&b\"\"[..], -1))\n );\n assert_parse!(\n be_i128(\n &[\n 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00\n ][..]\n ),\n Ok((\n &b\"\"[..],\n -170_141_183_460_469_231_731_687_303_715_884_105_728_i128\n ))\n );\n }\n\n #[test]\n fn le_i8_tests() {\n assert_parse!(le_i8(&[0x00][..]), Ok((&b\"\"[..], 0)));\n assert_parse!(le_i8(&[0x7f][..]), Ok((&b\"\"[..], 127)));\n assert_parse!(le_i8(&[0xff][..]), Ok((&b\"\"[..], -1)));\n assert_parse!(le_i8(&[0x80][..]), Ok((&b\"\"[..], -128)));\n }\n\n #[test]\n fn le_i16_tests() {\n assert_parse!(le_i16(&[0x00, 0x00][..]), Ok((&b\"\"[..], 0)));\n assert_parse!(le_i16(&[0xff, 0x7f][..]), Ok((&b\"\"[..], 32_767_i16)));\n assert_parse!(le_i16(&[0xff, 0xff][..]), Ok((&b\"\"[..], -1)));\n assert_parse!(le_i16(&[0x00, 0x80][..]), Ok((&b\"\"[..], -32_768_i16)));\n }\n\n #[test]\n fn le_u24_tests() {\n assert_parse!(le_u24(&[0x00, 0x00, 0x00][..]), Ok((&b\"\"[..], 0)));\n assert_parse!(le_u24(&[0xFF, 0xFF, 0x00][..]), Ok((&b\"\"[..], 65_535_u32)));\n assert_parse!(\n le_u24(&[0x56, 0x34, 0x12][..]),\n Ok((&b\"\"[..], 1_193_046_u32))\n );\n }\n\n #[test]\n fn le_i24_tests() {\n assert_parse!(le_i24(&[0xFF, 0xFF, 0xFF][..]), Ok((&b\"\"[..], -1_i32)));\n assert_parse!(le_i24(&[0x00, 0x00, 0xFF][..]), Ok((&b\"\"[..], -65_536_i32)));\n assert_parse!(\n le_i24(&[0xAA, 0xCB, 0xED][..]),\n Ok((&b\"\"[..], -1_193_046_i32))\n );\n }\n\n #[test]\n fn le_i32_tests() {\n assert_parse!(le_i32(&[0x00, 0x00, 0x00, 0x00][..]), Ok((&b\"\"[..], 0)));\n assert_parse!(\n le_i32(&[0xff, 0xff, 0xff, 0x7f][..]),\n Ok((&b\"\"[..], 2_147_483_647_i32))\n );\n assert_parse!(le_i32(&[0xff, 0xff, 0xff, 0xff][..]), Ok((&b\"\"[..], -1)));\n assert_parse!(\n le_i32(&[0x00, 0x00, 0x00, 0x80][..]),\n Ok((&b\"\"[..], -2_147_483_648_i32))\n );\n }\n\n #[test]\n fn le_i64_tests() {\n assert_parse!(\n le_i64(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]),\n Ok((&b\"\"[..], 0))\n );\n assert_parse!(\n le_i64(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f][..]),\n Ok((&b\"\"[..], 9_223_372_036_854_775_807_i64))\n );\n assert_parse!(\n le_i64(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff][..]),\n Ok((&b\"\"[..], -1))\n );\n assert_parse!(\n le_i64(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80][..]),\n Ok((&b\"\"[..], -9_223_372_036_854_775_808_i64))\n );\n }\n\n #[test]\n fn le_i128_tests() {\n assert_parse!(\n le_i128(\n &[\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00\n ][..]\n ),\n Ok((&b\"\"[..], 0))\n );\n assert_parse!(\n le_i128(\n &[\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0x7f\n ][..]\n ),\n Ok((\n &b\"\"[..],\n 170_141_183_460_469_231_731_687_303_715_884_105_727_i128\n ))\n );\n assert_parse!(\n le_i128(\n &[\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff\n ][..]\n ),\n Ok((&b\"\"[..], -1))\n );\n assert_parse!(\n le_i128(\n &[\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x80\n ][..]\n ),\n Ok((\n &b\"\"[..],\n -170_141_183_460_469_231_731_687_303_715_884_105_728_i128\n ))\n );\n }\n\n #[test]\n fn be_f32_tests() {\n assert_parse!(be_f32(&[0x00, 0x00, 0x00, 0x00][..]), Ok((&b\"\"[..], 0_f32)));\n assert_parse!(\n be_f32(&[0x4d, 0x31, 0x1f, 0xd8][..]),\n Ok((&b\"\"[..], 185_728_392_f32))\n );\n }\n\n #[test]\n fn be_f64_tests() {\n assert_parse!(\n be_f64(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]),\n Ok((&b\"\"[..], 0_f64))\n );\n assert_parse!(\n be_f64(&[0x41, 0xa6, 0x23, 0xfb, 0x10, 0x00, 0x00, 0x00][..]),\n Ok((&b\"\"[..], 185_728_392_f64))\n );\n }\n\n #[test]\n fn le_f32_tests() {\n assert_parse!(le_f32(&[0x00, 0x00, 0x00, 0x00][..]), Ok((&b\"\"[..], 0_f32)));\n assert_parse!(\n le_f32(&[0xd8, 0x1f, 0x31, 0x4d][..]),\n Ok((&b\"\"[..], 185_728_392_f32))\n );\n }\n\n #[test]\n fn le_f64_tests() {\n assert_parse!(\n le_f64(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]),\n Ok((&b\"\"[..], 0_f64))\n );\n assert_parse!(\n le_f64(&[0x00, 0x00, 0x00, 0x10, 0xfb, 0x23, 0xa6, 0x41][..]),\n Ok((&b\"\"[..], 185_728_392_f64))\n );\n }\n\n #[test]\n fn hex_u32_tests() {\n assert_parse!(\n hex_u32(&b\";\"[..]),\n Err(Err::Error(error_position!(&b\";\"[..], ErrorKind::IsA)))\n );\n assert_parse!(hex_u32(&b\"ff;\"[..]), Ok((&b\";\"[..], 255)));\n assert_parse!(hex_u32(&b\"1be2;\"[..]), Ok((&b\";\"[..], 7138)));\n assert_parse!(hex_u32(&b\"c5a31be2;\"[..]), Ok((&b\";\"[..], 3_315_801_058)));\n assert_parse!(hex_u32(&b\"C5A31be2;\"[..]), Ok((&b\";\"[..], 3_315_801_058)));\n assert_parse!(hex_u32(&b\"00c5a31be2;\"[..]), Ok((&b\"e2;\"[..], 12_952_347)));\n assert_parse!(\n hex_u32(&b\"c5a31be201;\"[..]),\n Ok((&b\"01;\"[..], 3_315_801_058))\n );\n assert_parse!(hex_u32(&b\"ffffffff;\"[..]), Ok((&b\";\"[..], 4_294_967_295)));\n assert_parse!(hex_u32(&b\"0x1be2;\"[..]), Ok((&b\"x1be2;\"[..], 0)));\n assert_parse!(hex_u32(&b\"12af\"[..]), Ok((&b\"\"[..], 0x12af)));\n }\n\n #[test]\n #[cfg(feature = \"std\")]\n fn float_test() {\n let mut test_cases = vec![\n \"+3.14\",\n \"3.14\",\n \"-3.14\",\n \"0\",\n \"0.0\",\n \"1.\",\n \".789\",\n \"-.5\",\n \"1e7\",\n \"-1E-7\",\n \".3e-2\",\n \"1.e4\",\n \"1.2e4\",\n \"12.34\",\n \"-1.234E-12\",\n \"-1.234e-12\",\n \"0.00000000000000000087\",\n ];\n\n for test in test_cases.drain(..) {\n let expected32 = str::parse::(test).unwrap();\n let expected64 = str::parse::(test).unwrap();\n\n println!(\"now parsing: {} -> {}\", test, expected32);\n\n assert_parse!(recognize_float(test), Ok((\"\", test)));\n\n assert_parse!(float(test.as_bytes()), Ok((&b\"\"[..], expected32)));\n assert_parse!(float(test), Ok((\"\", expected32)));\n\n assert_parse!(double(test.as_bytes()), Ok((&b\"\"[..], expected64)));\n assert_parse!(double(test), Ok((\"\", expected64)));\n }\n\n let remaining_exponent = \"-1.234E-\";\n assert_parse!(\n recognize_float(remaining_exponent),\n Err(Err::Failure((\"\", ErrorKind::Digit)))\n );\n\n let (_i, nan) = float::<_, ()>(\"NaN\").unwrap();\n assert!(nan.is_nan());\n\n let (_i, inf) = float::<_, ()>(\"inf\").unwrap();\n assert!(inf.is_infinite());\n let (i, inf) = float::<_, ()>(\"infinity\").unwrap();\n assert!(inf.is_infinite());\n assert!(i.is_empty());\n }\n\n #[test]\n fn configurable_endianness() {\n use crate::number::Endianness;\n\n fn be_tst16(i: &[u8]) -> IResult<&[u8], u16> {\n u16(Endianness::Big)(i)\n }\n fn le_tst16(i: &[u8]) -> IResult<&[u8], u16> {\n u16(Endianness::Little)(i)\n }\n assert_eq!(be_tst16(&[0x80, 0x00]), Ok((&b\"\"[..], 32_768_u16)));\n assert_eq!(le_tst16(&[0x80, 0x00]), Ok((&b\"\"[..], 128_u16)));\n\n fn be_tst32(i: &[u8]) -> IResult<&[u8], u32> {\n u32(Endianness::Big)(i)\n }\n fn le_tst32(i: &[u8]) -> IResult<&[u8], u32> {\n u32(Endianness::Little)(i)\n }\n assert_eq!(\n be_tst32(&[0x12, 0x00, 0x60, 0x00]),\n Ok((&b\"\"[..], 302_014_464_u32))\n );\n assert_eq!(\n le_tst32(&[0x12, 0x00, 0x60, 0x00]),\n Ok((&b\"\"[..], 6_291_474_u32))\n );\n\n fn be_tst64(i: &[u8]) -> IResult<&[u8], u64> {\n u64(Endianness::Big)(i)\n }\n fn le_tst64(i: &[u8]) -> IResult<&[u8], u64> {\n u64(Endianness::Little)(i)\n }\n assert_eq!(\n be_tst64(&[0x12, 0x00, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]),\n Ok((&b\"\"[..], 1_297_142_246_100_992_000_u64))\n );\n assert_eq!(\n le_tst64(&[0x12, 0x00, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]),\n Ok((&b\"\"[..], 36_028_874_334_666_770_u64))\n );\n\n fn be_tsti16(i: &[u8]) -> IResult<&[u8], i16> {\n i16(Endianness::Big)(i)\n }\n fn le_tsti16(i: &[u8]) -> IResult<&[u8], i16> {\n i16(Endianness::Little)(i)\n }\n assert_eq!(be_tsti16(&[0x00, 0x80]), Ok((&b\"\"[..], 128_i16)));\n assert_eq!(le_tsti16(&[0x00, 0x80]), Ok((&b\"\"[..], -32_768_i16)));\n\n fn be_tsti32(i: &[u8]) -> IResult<&[u8], i32> {\n i32(Endianness::Big)(i)\n }\n fn le_tsti32(i: &[u8]) -> IResult<&[u8], i32> {\n i32(Endianness::Little)(i)\n }\n assert_eq!(\n be_tsti32(&[0x00, 0x12, 0x60, 0x00]),\n Ok((&b\"\"[..], 1_204_224_i32))\n );\n assert_eq!(\n le_tsti32(&[0x00, 0x12, 0x60, 0x00]),\n Ok((&b\"\"[..], 6_296_064_i32))\n );\n\n fn be_tsti64(i: &[u8]) -> IResult<&[u8], i64> {\n i64(Endianness::Big)(i)\n }\n fn le_tsti64(i: &[u8]) -> IResult<&[u8], i64> {\n i64(Endianness::Little)(i)\n }\n assert_eq!(\n be_tsti64(&[0x00, 0xFF, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]),\n Ok((&b\"\"[..], 71_881_672_479_506_432_i64))\n );\n assert_eq!(\n le_tsti64(&[0x00, 0xFF, 0x60, 0x00, 0x12, 0x00, 0x80, 0x00]),\n Ok((&b\"\"[..], 36_028_874_334_732_032_i64))\n );\n }\n\n #[cfg(feature = \"std\")]\n fn parse_f64(i: &str) -> IResult<&str, f64, ()> {\n match recognize_float_or_exceptions(i) {\n Err(e) => Err(e),\n Ok((i, s)) => {\n if s.is_empty() {\n return Err(Err::Error(()));\n }\n match s.parse_to() {\n Some(n) => Ok((i, n)),\n None => Err(Err::Error(())),\n }\n }\n }\n }\n\n proptest! {\n #[test]\n #[cfg(feature = \"std\")]\n fn floats(s in \"\\\\PC*\") {\n println!(\"testing {}\", s);\n let res1 = parse_f64(&s);\n let res2 = double::<_, ()>(s.as_str());\n assert_eq!(res1, res2);\n }\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "mod.rs", "content": "pub mod complete;\npub mod streaming;\n\nuse crate::error::{ErrorKind, ParseError};\nuse crate::internal::{Err, IResult, Needed, Parser};\nuse crate::traits::ErrorConvert;\nuse crate::Input;\n\n/// Converts a byte-level input to a bit-level input, for consumption by a parser that uses bits.\n///\n/// Afterwards, the input is converted back to a byte-level parser, with any remaining bits thrown\n/// away.\n///\n/// # Example\n/// ```\n/// use nom::bits::{bits, streaming::take};\n/// use nom::error::Error;\n/// use nom::IResult;\n///\n/// fn parse(input: &[u8]) -> IResult<&[u8], (u8, u8)> {\n/// bits::<_, _, Error<(&[u8], usize)>, _, _>((take(4usize), take(8usize)))(input)\n/// }\n///\n/// let input = &[0x12, 0x34, 0xff, 0xff];\n///\n/// let output = parse(input).expect(\"We take 1.5 bytes and the input is longer than 2 bytes\");\n///\n/// // The first byte is consumed, the second byte is partially consumed and dropped.\n/// let remaining = output.0;\n/// assert_eq!(remaining, [0xff, 0xff]);\n///\n/// let parsed = output.1;\n/// assert_eq!(parsed.0, 0x01);\n/// assert_eq!(parsed.1, 0x23);\n/// ```\npub fn bits(mut parser: P) -> impl FnMut(I) -> IResult\nwhere\n E1: ParseError<(I, usize)> + ErrorConvert,\n E2: ParseError,\n I: Input,\n P: Parser<(I, usize), Output = O, Error = E1>,\n{\n move |input: I| match parser.parse((input, 0)) {\n Ok(((rest, offset), result)) => {\n // If the next byte has been partially read, it will be sliced away as well.\n // The parser functions might already slice away all fully read bytes.\n // That's why `offset / 8` isn't necessarily needed at all times.\n let remaining_bytes_index = offset / 8 + if offset % 8 == 0 { 0 } else { 1 };\n Ok((rest.take_from(remaining_bytes_index), result))\n }\n Err(Err::Incomplete(n)) => Err(Err::Incomplete(n.map(|u| u.get() / 8 + 1))),\n Err(Err::Error(e)) => Err(Err::Error(e.convert())),\n Err(Err::Failure(e)) => Err(Err::Failure(e.convert())),\n }\n}\n\n/// Counterpart to `bits`, `bytes` transforms its bit stream input into a byte slice for the underlying\n/// parser, allowing byte-slice parsers to work on bit streams.\n///\n/// A partial byte remaining in the input will be ignored and the given parser will start parsing\n/// at the next full byte.\n///\n/// ```\n/// use nom::bits::{bits, bytes, streaming::take};\n/// use nom::combinator::rest;\n/// use nom::error::Error;\n/// use nom::IResult;\n///\n/// fn parse(input: &[u8]) -> IResult<&[u8], (u8, u8, &[u8])> {\n/// bits::<_, _, Error<(&[u8], usize)>, _, _>((\n/// take(4usize),\n/// take(8usize),\n/// bytes::<_, _, Error<&[u8]>, _, _>(rest)\n/// ))(input)\n/// }\n///\n/// let input = &[0x12, 0x34, 0xff, 0xff];\n///\n/// assert_eq!(parse( input ), Ok(( &[][..], (0x01, 0x23, &[0xff, 0xff][..]) )));\n/// ```\npub fn bytes(mut parser: P) -> impl FnMut((I, usize)) -> IResult<(I, usize), O, E2>\nwhere\n E1: ParseError + ErrorConvert,\n E2: ParseError<(I, usize)>,\n I: Input + Clone,\n P: Parser,\n{\n move |(input, offset): (I, usize)| {\n let inner = if offset % 8 != 0 {\n input.take_from(1 + offset / 8)\n } else {\n input.take_from(offset / 8)\n };\n let i = (input, offset);\n match parser.parse(inner) {\n Ok((rest, res)) => Ok(((rest, 0), res)),\n Err(Err::Incomplete(Needed::Unknown)) => Err(Err::Incomplete(Needed::Unknown)),\n Err(Err::Incomplete(Needed::Size(sz))) => Err(match sz.get().checked_mul(8) {\n Some(v) => Err::Incomplete(Needed::new(v)),\n None => Err::Failure(E2::from_error_kind(i, ErrorKind::TooLarge)),\n }),\n Err(Err::Error(e)) => Err(Err::Error(e.convert())),\n Err(Err::Failure(e)) => Err(Err::Failure(e.convert())),\n }\n }\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n use crate::bits::streaming::take;\n use crate::error::Error;\n\n #[test]\n /// Take the `bits` function and assert that remaining bytes are correctly returned, if the\n /// previous bytes are fully consumed\n fn test_complete_byte_consumption_bits() {\n let input = &[0x12, 0x34, 0x56, 0x78];\n\n // Take 3 bit slices with sizes [4, 8, 4].\n let result: IResult<&[u8], (u8, u8, u8)> =\n bits::<_, _, Error<(&[u8], usize)>, _, _>((take(4usize), take(8usize), take(4usize)))(input);\n\n let output = result.expect(\"We take 2 bytes and the input is longer than 2 bytes\");\n\n let remaining = output.0;\n assert_eq!(remaining, [0x56, 0x78]);\n\n let parsed = output.1;\n assert_eq!(parsed.0, 0x01);\n assert_eq!(parsed.1, 0x23);\n assert_eq!(parsed.2, 0x04);\n }\n\n #[test]\n /// Take the `bits` function and assert that remaining bytes are correctly returned, if the\n /// previous bytes are NOT fully consumed. Partially consumed bytes are supposed to be dropped.\n /// I.e. if we consume 1.5 bytes of 4 bytes, 2 bytes will be returned, bits 13-16 will be\n /// dropped.\n fn test_partial_byte_consumption_bits() {\n let input = &[0x12, 0x34, 0x56, 0x78];\n\n // Take bit slices with sizes [4, 8].\n let result: IResult<&[u8], (u8, u8)> =\n bits::<_, _, Error<(&[u8], usize)>, _, _>((take(4usize), take(8usize)))(input);\n\n let output = result.expect(\"We take 1.5 bytes and the input is longer than 2 bytes\");\n\n let remaining = output.0;\n assert_eq!(remaining, [0x56, 0x78]);\n\n let parsed = output.1;\n assert_eq!(parsed.0, 0x01);\n assert_eq!(parsed.1, 0x23);\n }\n\n #[test]\n #[cfg(feature = \"std\")]\n /// Ensure that in Incomplete error is thrown, if too few bytes are passed for a given parser.\n fn test_incomplete_bits() {\n let input = &[0x12];\n\n // Take bit slices with sizes [4, 8].\n let result: IResult<&[u8], (u8, u8)> =\n bits::<_, _, Error<(&[u8], usize)>, _, _>((take(4usize), take(8usize)))(input);\n\n assert!(result.is_err());\n let error = result.err().unwrap();\n assert_eq!(\"Parsing requires 2 bytes/chars\", error.to_string());\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "complete.rs", "content": "use crate::error::{ErrorKind, ParseError};\nuse crate::internal::{Err, IResult};\nuse crate::lib::std::ops::{AddAssign, Div, Shl, Shr};\nuse crate::traits::{Input, ToUsize};\n\n/// Generates a parser taking `count` bits\n///\n/// # Example\n/// ```rust\n/// # use nom::bits::complete::take;\n/// # use nom::IResult;\n/// # use nom::error::{Error, ErrorKind};\n/// // Input is a tuple of (input: I, bit_offset: usize)\n/// fn parser(input: (&[u8], usize), count: usize)-> IResult<(&[u8], usize), u8> {\n/// take(count)(input)\n/// }\n///\n/// // Consumes 0 bits, returns 0\n/// assert_eq!(parser(([0b00010010].as_ref(), 0), 0), Ok((([0b00010010].as_ref(), 0), 0)));\n///\n/// // Consumes 4 bits, returns their values and increase offset to 4\n/// assert_eq!(parser(([0b00010010].as_ref(), 0), 4), Ok((([0b00010010].as_ref(), 4), 0b00000001)));\n///\n/// // Consumes 4 bits, offset is 4, returns their values and increase offset to 0 of next byte\n/// assert_eq!(parser(([0b00010010].as_ref(), 4), 4), Ok((([].as_ref(), 0), 0b00000010)));\n///\n/// // Tries to consume 12 bits but only 8 are available\n/// assert_eq!(parser(([0b00010010].as_ref(), 0), 12), Err(nom::Err::Error(Error{input: ([0b00010010].as_ref(), 0), code: ErrorKind::Eof })));\n/// ```\npub fn take>(\n count: C,\n) -> impl Fn((I, usize)) -> IResult<(I, usize), O, E>\nwhere\n I: Input,\n C: ToUsize,\n O: From + AddAssign + Shl + Shr,\n{\n let count = count.to_usize();\n move |(input, bit_offset): (I, usize)| {\n if count == 0 {\n Ok(((input, bit_offset), 0u8.into()))\n } else if input.input_len() * 8 < count + bit_offset {\n Err(Err::Error(E::from_error_kind(\n (input, bit_offset),\n ErrorKind::Eof,\n )))\n } else {\n let cnt = (count + bit_offset).div(8);\n let mut acc: O = 0_u8.into();\n let mut offset: usize = bit_offset;\n let mut remaining: usize = count;\n let mut end_offset: usize = 0;\n\n for byte in input.iter_elements().take(cnt + 1) {\n if remaining == 0 {\n break;\n }\n let val: O = if offset == 0 {\n byte.into()\n } else {\n ((byte << offset) >> offset).into()\n };\n\n if remaining < 8 - offset {\n acc += val >> (8 - offset - remaining);\n end_offset = remaining + offset;\n break;\n } else {\n acc += val << (remaining - (8 - offset));\n remaining -= 8 - offset;\n offset = 0;\n }\n }\n Ok(((input.take_from(cnt), end_offset), acc))\n }\n }\n}\n\n/// Generates a parser taking `count` bits and comparing them to `pattern`\npub fn tag>(\n pattern: O,\n count: C,\n) -> impl Fn((I, usize)) -> IResult<(I, usize), O, E>\nwhere\n I: Input + Clone,\n C: ToUsize,\n O: From + AddAssign + Shl + Shr + PartialEq,\n{\n let count = count.to_usize();\n move |input: (I, usize)| {\n let inp = input.clone();\n\n take(count)(input).and_then(|(i, o)| {\n if pattern == o {\n Ok((i, o))\n } else {\n Err(Err::Error(error_position!(inp, ErrorKind::TagBits)))\n }\n })\n }\n}\n\n/// Parses one specific bit as a bool.\n///\n/// # Example\n/// ```rust\n/// # use nom::bits::complete::bool;\n/// # use nom::IResult;\n/// # use nom::error::{Error, ErrorKind};\n///\n/// fn parse(input: (&[u8], usize)) -> IResult<(&[u8], usize), bool> {\n/// bool(input)\n/// }\n///\n/// assert_eq!(parse(([0b10000000].as_ref(), 0)), Ok((([0b10000000].as_ref(), 1), true)));\n/// assert_eq!(parse(([0b10000000].as_ref(), 1)), Ok((([0b10000000].as_ref(), 2), false)));\n/// ```\npub fn bool>(input: (I, usize)) -> IResult<(I, usize), bool, E>\nwhere\n I: Input,\n{\n let (res, bit): (_, u32) = take(1usize)(input)?;\n Ok((res, bit != 0))\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n\n #[test]\n fn test_take_0() {\n let input = [0b00010010].as_ref();\n let count = 0usize;\n assert_eq!(count, 0usize);\n let offset = 0usize;\n\n let result: crate::IResult<(&[u8], usize), usize> = take(count)((input, offset));\n\n assert_eq!(result, Ok(((input, offset), 0)));\n }\n\n #[test]\n fn test_take_eof() {\n let input = [0b00010010].as_ref();\n\n let result: crate::IResult<(&[u8], usize), usize> = take(1usize)((input, 8));\n\n assert_eq!(\n result,\n Err(crate::Err::Error(crate::error::Error {\n input: (input, 8),\n code: ErrorKind::Eof\n }))\n )\n }\n\n #[test]\n fn test_take_span_over_multiple_bytes() {\n let input = [0b00010010, 0b00110100, 0b11111111, 0b11111111].as_ref();\n\n let result: crate::IResult<(&[u8], usize), usize> = take(24usize)((input, 4));\n\n assert_eq!(\n result,\n Ok((([0b11111111].as_ref(), 4), 0b1000110100111111111111))\n );\n }\n\n #[test]\n fn test_bool_0() {\n let input = [0b10000000].as_ref();\n\n let result: crate::IResult<(&[u8], usize), bool> = bool((input, 0));\n\n assert_eq!(result, Ok(((input, 1), true)));\n }\n\n #[test]\n fn test_bool_eof() {\n let input = [0b10000000].as_ref();\n\n let result: crate::IResult<(&[u8], usize), bool> = bool((input, 8));\n\n assert_eq!(\n result,\n Err(crate::Err::Error(crate::error::Error {\n input: (input, 8),\n code: ErrorKind::Eof\n }))\n );\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "mod.rs", "content": "#![allow(unused_imports)]\n\nuse core::marker::PhantomData;\n\n#[cfg(feature = \"alloc\")]\nuse crate::lib::std::boxed::Box;\n\nuse crate::error::{ErrorKind, FromExternalError, ParseError};\nuse crate::internal::*;\nuse crate::lib::std::borrow::Borrow;\nuse crate::lib::std::convert::Into;\n#[cfg(feature = \"std\")]\nuse crate::lib::std::fmt::Debug;\nuse crate::lib::std::mem::transmute;\nuse crate::lib::std::ops::{Range, RangeFrom, RangeTo};\nuse crate::traits::{AsChar, Input, ParseTo};\nuse crate::traits::{Compare, CompareResult, Offset};\n\n#[cfg(test)]\nmod tests;\n\n/// Return the remaining input.\n///\n/// ```rust\n/// # use nom::error::ErrorKind;\n/// use nom::combinator::rest;\n/// assert_eq!(rest::<_,(_, ErrorKind)>(\"abc\"), Ok((\"\", \"abc\")));\n/// assert_eq!(rest::<_,(_, ErrorKind)>(\"\"), Ok((\"\", \"\")));\n/// ```\n#[inline]\npub fn rest>(input: T) -> IResult\nwhere\n T: Input,\n{\n Ok(input.take_split(input.input_len()))\n}\n\n/// Return the length of the remaining input.\n///\n/// ```rust\n/// # use nom::error::ErrorKind;\n/// use nom::combinator::rest_len;\n/// assert_eq!(rest_len::<_,(_, ErrorKind)>(\"abc\"), Ok((\"abc\", 3)));\n/// assert_eq!(rest_len::<_,(_, ErrorKind)>(\"\"), Ok((\"\", 0)));\n/// ```\n#[inline]\npub fn rest_len>(input: T) -> IResult\nwhere\n T: Input,\n{\n let len = input.input_len();\n Ok((input, len))\n}\n\n/// Maps a function on the result of a parser.\n///\n/// ```rust\n/// use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::character::complete::digit1;\n/// use nom::combinator::map;\n/// # fn main() {\n///\n/// let mut parser = map(digit1, |s: &str| s.len());\n///\n/// // the parser will count how many characters were returned by digit1\n/// assert_eq!(parser.parse(\"123456\"), Ok((\"\", 6)));\n///\n/// // this will fail if digit1 fails\n/// assert_eq!(parser.parse(\"abc\"), Err(Err::Error((\"abc\", ErrorKind::Digit))));\n/// # }\n/// ```\npub fn map, F, G>(parser: F, f: G) -> impl Parser\nwhere\n F: Parser,\n G: FnMut(>::Output) -> O,\n{\n parser.map(f)\n}\n\n/// Applies a function returning a `Result` over the result of a parser.\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::character::complete::digit1;\n/// use nom::combinator::map_res;\n/// # fn main() {\n///\n/// let mut parse = map_res(digit1, |s: &str| s.parse::());\n///\n/// // the parser will convert the result of digit1 to a number\n/// assert_eq!(parse.parse(\"123\"), Ok((\"\", 123)));\n///\n/// // this will fail if digit1 fails\n/// assert_eq!(parse.parse(\"abc\"), Err(Err::Error((\"abc\", ErrorKind::Digit))));\n///\n/// // this will fail if the mapped function fails (a `u8` is too small to hold `123456`)\n/// assert_eq!(parse.parse(\"123456\"), Err(Err::Error((\"123456\", ErrorKind::MapRes))));\n/// # }\n/// ```\npub fn map_res + FromExternalError, E2, F, G>(\n parser: F,\n f: G,\n) -> impl Parser\nwhere\n F: Parser,\n G: FnMut(>::Output) -> Result,\n{\n parser.map_res(f)\n}\n\n/// Applies a function returning an `Option` over the result of a parser.\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::character::complete::digit1;\n/// use nom::combinator::map_opt;\n/// # fn main() {\n///\n/// let mut parse = map_opt(digit1, |s: &str| s.parse::().ok());\n///\n/// // the parser will convert the result of digit1 to a number\n/// assert_eq!(parse.parse(\"123\"), Ok((\"\", 123)));\n///\n/// // this will fail if digit1 fails\n/// assert_eq!(parse.parse(\"abc\"), Err(Err::Error((\"abc\", ErrorKind::Digit))));\n///\n/// // this will fail if the mapped function fails (a `u8` is too small to hold `123456`)\n/// assert_eq!(parse.parse(\"123456\"), Err(Err::Error((\"123456\", ErrorKind::MapOpt))));\n/// # }\n/// ```\npub fn map_opt, F, G>(\n parser: F,\n f: G,\n) -> impl Parser\nwhere\n F: Parser,\n G: FnMut(>::Output) -> Option,\n{\n parser.map_opt(f)\n}\n\n/// Applies a parser over the result of another one.\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::character::complete::digit1;\n/// use nom::bytes::complete::take;\n/// use nom::combinator::map_parser;\n/// # fn main() {\n///\n/// let mut parse = map_parser(take(5u8), digit1);\n///\n/// assert_eq!(parse.parse(\"12345\"), Ok((\"\", \"12345\")));\n/// assert_eq!(parse.parse(\"123ab\"), Ok((\"\", \"123\")));\n/// assert_eq!(parse.parse(\"123\"), Err(Err::Error((\"123\", ErrorKind::Eof))));\n/// # }\n/// ```\npub fn map_parser, F, G>(\n parser: F,\n applied_parser: G,\n) -> impl Parser\nwhere\n F: Parser,\n G: Parser<>::Output, Output = O, Error = E>,\n{\n parser.and_then(applied_parser)\n}\n\n/// Creates a new parser from the output of the first parser, then apply that parser over the rest of the input.\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::bytes::complete::take;\n/// use nom::number::complete::u8;\n/// use nom::combinator::flat_map;\n/// # fn main() {\n///\n/// let mut parse = flat_map(u8, take);\n///\n/// assert_eq!(parse.parse(&[2, 0, 1, 2][..]), Ok((&[2][..], &[0, 1][..])));\n/// assert_eq!(parse.parse(&[4, 0, 1, 2][..]), Err(Err::Error((&[0, 1, 2][..], ErrorKind::Eof))));\n/// # }\n/// ```\npub fn flat_map, F, G, H>(\n parser: F,\n applied_parser: G,\n) -> impl Parser\nwhere\n F: Parser,\n G: FnMut(>::Output) -> H,\n H: Parser,\n{\n parser.flat_map(applied_parser)\n}\n\n/// Optional parser, will return `None` on [`Err::Error`].\n///\n/// To chain an error up, see [`cut`].\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::combinator::opt;\n/// use nom::character::complete::alpha1;\n/// # fn main() {\n///\n/// fn parser(i: &str) -> IResult<&str, Option<&str>> {\n/// opt(alpha1).parse(i)\n/// }\n///\n/// assert_eq!(parser(\"abcd;\"), Ok((\";\", Some(\"abcd\"))));\n/// assert_eq!(parser(\"123;\"), Ok((\"123;\", None)));\n/// # }\n/// ```\npub fn opt, F>(\n f: F,\n) -> impl Parser>::Output>, Error = E>\nwhere\n F: Parser,\n{\n Opt { parser: f }\n}\n\n/// Parser implementation for [opt]\npub struct Opt {\n parser: F,\n}\n\nimpl> Parser for Opt\nwhere\n I: Clone,\n{\n type Output = Option<>::Output>;\n\n type Error = >::Error;\n\n #[inline(always)]\n fn process(&mut self, input: I) -> PResult {\n let i = input.clone();\n match self\n .parser\n .process::>(input)\n {\n Ok((i, o)) => Ok((i, OM::Output::map(o, Some))),\n Err(Err::Error(_)) => Ok((i, OM::Output::bind(|| None))),\n Err(Err::Failure(e)) => Err(Err::Failure(e)),\n Err(Err::Incomplete(i)) => Err(Err::Incomplete(i)),\n }\n }\n}\n\n/// Calls the parser if the condition is met.\n///\n/// ```rust\n/// # use nom::{Err, error::{Error, ErrorKind}, IResult, Parser};\n/// use nom::combinator::cond;\n/// use nom::character::complete::alpha1;\n/// # fn main() {\n///\n/// fn parser(b: bool, i: &str) -> IResult<&str, Option<&str>> {\n/// cond(b, alpha1).parse(i)\n/// }\n///\n/// assert_eq!(parser(true, \"abcd;\"), Ok((\";\", Some(\"abcd\"))));\n/// assert_eq!(parser(false, \"abcd;\"), Ok((\"abcd;\", None)));\n/// assert_eq!(parser(true, \"123;\"), Err(Err::Error(Error::new(\"123;\", ErrorKind::Alpha))));\n/// assert_eq!(parser(false, \"123;\"), Ok((\"123;\", None)));\n/// # }\n/// ```\npub fn cond, F>(\n b: bool,\n f: F,\n) -> impl Parser>::Output>, Error = E>\nwhere\n F: Parser,\n{\n Cond {\n parser: if b { Some(f) } else { None },\n }\n}\n\n/// Parser implementation for [cond]\npub struct Cond {\n parser: Option,\n}\n\nimpl Parser for Cond\nwhere\n F: Parser,\n{\n type Output = Option<>::Output>;\n type Error = >::Error;\n\n fn process(&mut self, input: I) -> PResult {\n match &mut self.parser {\n None => Ok((input, OM::Output::bind(|| None))),\n Some(f) => f\n .process::(input)\n .map(|(i, o)| (i, OM::Output::map(o, Some))),\n }\n }\n}\n\n/// Tries to apply its parser without consuming the input.\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::combinator::peek;\n/// use nom::character::complete::alpha1;\n/// # fn main() {\n///\n/// let mut parser = peek(alpha1);\n///\n/// assert_eq!(parser.parse(\"abcd;\"), Ok((\"abcd;\", \"abcd\")));\n/// assert_eq!(parser.parse(\"123;\"), Err(Err::Error((\"123;\", ErrorKind::Alpha))));\n/// # }\n/// ```\npub fn peek(\n parser: F,\n) -> impl Parser>::Output, Error = >::Error>\nwhere\n F: Parser,\n{\n Peek { parser }\n}\n\n/// Parsr implementation for [peek]\npub struct Peek {\n parser: F,\n}\n\nimpl Parser for Peek\nwhere\n I: Clone,\n F: Parser,\n{\n type Output = >::Output;\n type Error = >::Error;\n\n fn process(&mut self, input: I) -> PResult {\n let i = input.clone();\n match self.parser.process::(input) {\n Ok((_, o)) => Ok((i, o)),\n Err(e) => Err(e),\n }\n }\n}\n\n/// returns its input if it is at the end of input data\n///\n/// When we're at the end of the data, this combinator\n/// will succeed\n///\n/// ```\n/// # use std::str;\n/// # use nom::{Err, error::ErrorKind, IResult};\n/// # use nom::combinator::eof;\n///\n/// # fn main() {\n/// let parser = eof;\n/// assert_eq!(parser(\"abc\"), Err(Err::Error((\"abc\", ErrorKind::Eof))));\n/// assert_eq!(parser(\"\"), Ok((\"\", \"\")));\n/// # }\n/// ```\npub fn eof>(input: I) -> IResult {\n if input.input_len() == 0 {\n let clone = input.clone();\n Ok((input, clone))\n } else {\n Err(Err::Error(E::from_error_kind(input, ErrorKind::Eof)))\n }\n}\n\n/// Transforms Incomplete into `Error`.\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::bytes::streaming::take;\n/// use nom::combinator::complete;\n/// # fn main() {\n///\n/// let mut parser = complete(take(5u8));\n///\n/// assert_eq!(parser.parse(\"abcdefg\"), Ok((\"fg\", \"abcde\")));\n/// assert_eq!(parser.parse(\"abcd\"), Err(Err::Error((\"abcd\", ErrorKind::Complete))));\n/// # }\n/// ```\npub fn complete, F>(\n parser: F,\n) -> impl Parser\nwhere\n F: Parser,\n{\n MakeComplete { parser }\n}\n\n/// Parser implementation for [complete]\npub struct MakeComplete {\n parser: F,\n}\n\nimpl Parser for MakeComplete\nwhere\n I: Clone,\n F: Parser,\n{\n type Output = >::Output;\n type Error = >::Error;\n\n fn process(&mut self, input: I) -> PResult {\n let i = input.clone();\n\n match self\n .parser\n .process::>(input)\n {\n Err(Err::Incomplete(_)) => Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(i, ErrorKind::Complete)\n }))),\n Err(e) => Err(e),\n Ok(o) => Ok(o),\n }\n }\n}\n\n/// Succeeds if all the input has been consumed by its child parser.\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::combinator::all_consuming;\n/// use nom::character::complete::alpha1;\n/// # fn main() {\n///\n/// let mut parser = all_consuming(alpha1);\n///\n/// assert_eq!(parser.parse(\"abcd\"), Ok((\"\", \"abcd\")));\n/// assert_eq!(parser.parse(\"abcd;\"),Err(Err::Error((\";\", ErrorKind::Eof))));\n/// assert_eq!(parser.parse(\"123abcd;\"),Err(Err::Error((\"123abcd;\", ErrorKind::Alpha))));\n/// # }\n/// ```\npub fn all_consuming, F>(\n parser: F,\n) -> impl Parser>::Output, Error = E>\nwhere\n I: Input,\n F: Parser,\n{\n AllConsuming { parser }\n}\n\n/// Parser implementation for [all_consuming]\npub struct AllConsuming {\n parser: F,\n}\n\nimpl Parser for AllConsuming\nwhere\n I: Input,\n F: Parser,\n{\n type Output = >::Output;\n type Error = >::Error;\n\n fn process(&mut self, input: I) -> PResult {\n let (input, res) = self.parser.process::(input)?;\n if input.input_len() == 0 {\n Ok((input, res))\n } else {\n Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(input, ErrorKind::Eof)\n })))\n }\n }\n}\n\n/// Returns the result of the child parser if it satisfies a verification function.\n///\n/// The verification function takes as argument a reference to the output of the\n/// parser.\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::combinator::verify;\n/// use nom::character::complete::alpha1;\n/// # fn main() {\n///\n/// let mut parser = verify(alpha1, |s: &str| s.len() == 4);\n///\n/// assert_eq!(parser.parse(\"abcd\"), Ok((\"\", \"abcd\")));\n/// assert_eq!(parser.parse(\"abcde\"), Err(Err::Error((\"abcde\", ErrorKind::Verify))));\n/// assert_eq!(parser.parse(\"123abcd;\"),Err(Err::Error((\"123abcd;\", ErrorKind::Alpha))));\n/// # }\n/// ```\npub fn verify, F, G>(\n first: F,\n second: G,\n) -> impl Parser>::Output, Error = E>\nwhere\n F: Parser,\n G: Fn(&O2) -> bool,\n >::Output: Borrow,\n O2: ?Sized,\n{\n Verify {\n first,\n second,\n o2: PhantomData,\n }\n}\n\n/// Parser iplementation for verify\npub struct Verify {\n first: F,\n second: G,\n o2: PhantomData,\n}\n\nimpl, G, O2> Parser for Verify\nwhere\n I: Clone,\n G: Fn(&O2) -> bool,\n >::Output: Borrow,\n O2: ?Sized,\n{\n type Output = >::Output;\n\n type Error = >::Error;\n\n fn process(&mut self, input: I) -> PResult {\n let (i, o) = self\n .first\n .process::>(input.clone())?;\n\n if (self.second)(o.borrow()) {\n Ok((i, OM::Output::bind(|| o)))\n } else {\n Err(Err::Error(OM::Error::bind(move || {\n let e: ErrorKind = ErrorKind::Verify;\n >::Error::from_error_kind(input, e)\n })))\n }\n }\n}\n\n/// Returns the provided value if the child parser succeeds.\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::combinator::value;\n/// use nom::character::complete::alpha1;\n/// # fn main() {\n///\n/// let mut parser = value(1234, alpha1);\n///\n/// assert_eq!(parser.parse(\"abcd\"), Ok((\"\", 1234)));\n/// assert_eq!(parser.parse(\"123abcd;\"), Err(Err::Error((\"123abcd;\", ErrorKind::Alpha))));\n/// # }\n/// ```\npub fn value, F>(\n val: O1,\n parser: F,\n) -> impl Parser\nwhere\n F: Parser,\n{\n parser.map(move |_| val.clone())\n}\n\n/// Succeeds if the child parser returns an error.\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::combinator::not;\n/// use nom::character::complete::alpha1;\n/// # fn main() {\n///\n/// let mut parser = not(alpha1);\n///\n/// assert_eq!(parser.parse(\"123\"), Ok((\"123\", ())));\n/// assert_eq!(parser.parse(\"abcd\"), Err(Err::Error((\"abcd\", ErrorKind::Not))));\n/// # }\n/// ```\npub fn not, F>(parser: F) -> impl Parser\nwhere\n F: Parser,\n{\n Not { parser }\n}\n\n/// Parser implementation for [not]\npub struct Not {\n parser: F,\n}\n\nimpl Parser for Not\nwhere\n I: Clone,\n F: Parser,\n{\n type Output = ();\n type Error = >::Error;\n\n fn process(&mut self, input: I) -> PResult {\n let i = input.clone();\n match self.parser.process::(input) {\n Ok(_) => Err(Err::Error(OM::Error::bind(|| {\n >::Error::from_error_kind(i, ErrorKind::Not)\n }))),\n Err(Err::Error(_)) => Ok((i, OM::Output::bind(|| ()))),\n Err(e) => Err(e),\n }\n }\n}\n\n/// If the child parser was successful, return the consumed input as produced value.\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::combinator::recognize;\n/// use nom::character::complete::{char, alpha1};\n/// use nom::sequence::separated_pair;\n/// # fn main() {\n///\n/// let mut parser = recognize(separated_pair(alpha1, char(','), alpha1));\n///\n/// assert_eq!(parser.parse(\"abcd,efgh\"), Ok((\"\", \"abcd,efgh\")));\n/// assert_eq!(parser.parse(\"abcd;\"),Err(Err::Error((\";\", ErrorKind::Char))));\n/// # }\n/// ```\npub fn recognize, F>(\n parser: F,\n) -> impl Parser\nwhere\n F: Parser,\n{\n Recognize { parser }\n}\n\n/// Parser implementation for [recognize]\npub struct Recognize {\n parser: F,\n}\n\nimpl Parser for Recognize\nwhere\n I: Clone + Offset + Input,\n F: Parser,\n{\n type Output = I;\n type Error = >::Error;\n\n #[inline(always)]\n fn process(&mut self, input: I) -> PResult {\n let i = input.clone();\n match self\n .parser\n .process::>(i)\n {\n Ok((i, _)) => {\n let index = input.offset(&i);\n Ok((i, OM::Output::bind(|| input.take(index))))\n }\n Err(e) => Err(e),\n }\n }\n}\n\n/// if the child parser was successful, return the consumed input with the output\n/// as a tuple. Functions similarly to [recognize](fn.recognize.html) except it\n/// returns the parser output as well.\n///\n/// This can be useful especially in cases where the output is not the same type\n/// as the input, or the input is a user defined type.\n///\n/// Returned tuple is of the format `(consumed input, produced output)`.\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::combinator::{consumed, value, recognize, map};\n/// use nom::character::complete::{char, alpha1};\n/// use nom::bytes::complete::tag;\n/// use nom::sequence::separated_pair;\n///\n/// fn inner_parser(input: &str) -> IResult<&str, bool> {\n/// value(true, tag(\"1234\")).parse(input)\n/// }\n///\n/// # fn main() {\n///\n/// let mut consumed_parser = consumed(value(true, separated_pair(alpha1, char(','), alpha1)));\n///\n/// assert_eq!(consumed_parser.parse(\"abcd,efgh1\"), Ok((\"1\", (\"abcd,efgh\", true))));\n/// assert_eq!(consumed_parser.parse(\"abcd;\"),Err(Err::Error((\";\", ErrorKind::Char))));\n///\n///\n/// // the first output (representing the consumed input)\n/// // should be the same as that of the `recognize` parser.\n/// let mut recognize_parser = recognize(inner_parser);\n/// let mut consumed_parser = map(consumed(inner_parser), |(consumed, output)| consumed);\n///\n/// assert_eq!(recognize_parser.parse(\"1234\"), consumed_parser.parse(\"1234\"));\n/// assert_eq!(recognize_parser.parse(\"abcd\"), consumed_parser.parse(\"abcd\"));\n/// # }\n/// ```\npub fn consumed(\n parser: F,\n) -> impl Parser>::Output), Error = E>\nwhere\n I: Clone + Offset + Input,\n E: ParseError,\n F: Parser,\n{\n Consumed { parser }\n}\n\n/// Parser implementation for [consumed]\npub struct Consumed {\n parser: F,\n}\n\nimpl Parser for Consumed\nwhere\n I: Clone + Offset + Input,\n F: Parser,\n{\n type Output = (I, >::Output);\n type Error = >::Error;\n\n #[inline(always)]\n fn process(&mut self, input: I) -> PResult {\n let i = input.clone();\n match self.parser.process::(i) {\n Ok((remaining, result)) => {\n let index = input.offset(&remaining);\n\n Ok((\n remaining,\n OM::Output::map(result, |res| {\n let consumed = input.take(index);\n (consumed, res)\n }),\n ))\n }\n Err(e) => Err(e),\n }\n }\n}\n\n/// Transforms an [`Err::Error`] (recoverable) to [`Err::Failure`] (unrecoverable)\n///\n/// This commits the parse result, preventing alternative branch paths like with\n/// [`nom::branch::alt`][crate::branch::alt].\n///\n/// # Example\n///\n/// Without `cut`:\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// # use nom::character::complete::{one_of, digit1};\n/// # use nom::combinator::rest;\n/// # use nom::branch::alt;\n/// # use nom::sequence::preceded;\n/// # fn main() {\n///\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// alt((\n/// preceded(one_of(\"+-\"), digit1),\n/// rest\n/// )).parse(input)\n/// }\n///\n/// assert_eq!(parser(\"+10 ab\"), Ok((\" ab\", \"10\")));\n/// assert_eq!(parser(\"ab\"), Ok((\"\", \"ab\")));\n/// assert_eq!(parser(\"+\"), Ok((\"\", \"+\")));\n/// # }\n/// ```\n///\n/// With `cut`:\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser, error::Error};\n/// # use nom::character::complete::{one_of, digit1};\n/// # use nom::combinator::rest;\n/// # use nom::branch::alt;\n/// # use nom::sequence::preceded;\n/// use nom::combinator::cut;\n/// # fn main() {\n///\n/// fn parser(input: &str) -> IResult<&str, &str> {\n/// alt((\n/// preceded(one_of(\"+-\"), cut(digit1)),\n/// rest\n/// )).parse(input)\n/// }\n///\n/// assert_eq!(parser(\"+10 ab\"), Ok((\" ab\", \"10\")));\n/// assert_eq!(parser(\"ab\"), Ok((\"\", \"ab\")));\n/// assert_eq!(parser(\"+\"), Err(Err::Failure(Error { input: \"\", code: ErrorKind::Digit })));\n/// # }\n/// ```\npub fn cut, F>(\n parser: F,\n) -> impl Parser>::Output, Error = E>\nwhere\n F: Parser,\n{\n Cut { parser }\n}\n\n/// Parser implementation for [cut]\npub struct Cut {\n parser: F,\n}\n\nimpl Parser for Cut\nwhere\n F: Parser,\n{\n type Output = >::Output;\n\n type Error = >::Error;\n\n #[inline(always)]\n fn process(&mut self, input: I) -> PResult {\n match self\n .parser\n .process::>(input)\n {\n Err(Err::Error(e)) => Err(Err::Failure(e)),\n Err(Err::Failure(e)) => Err(Err::Failure(e)),\n Err(Err::Incomplete(i)) => Err(Err::Incomplete(i)),\n Ok((i, o)) => Ok((i, o)),\n }\n }\n}\n\n/// automatically converts the child parser's result to another type\n///\n/// it will be able to convert the output value and the error value\n/// as long as the `Into` implementations are available\n///\n/// ```rust\n/// # use nom::{IResult, Parser};\n/// use nom::combinator::into;\n/// use nom::character::complete::alpha1;\n/// # fn main() {\n///\n/// fn parser1(i: &str) -> IResult<&str, &str> {\n/// alpha1(i)\n/// }\n///\n/// let mut parser2 = into(parser1);\n///\n/// // the parser converts the &str output of the child parser into a Vec\n/// let bytes: IResult<&str, Vec> = parser2.parse(\"abcd\");\n/// assert_eq!(bytes, Ok((\"\", vec![97, 98, 99, 100])));\n/// # }\n/// ```\npub fn into(parser: F) -> impl Parser\nwhere\n O2: From,\n E2: From,\n E1: ParseError,\n E2: ParseError,\n F: Parser,\n{\n parser.into::()\n}\n\n/// Creates an iterator from input data and a parser.\n///\n/// Call the iterator's [ParserIterator::finish] method to get the remaining input if successful,\n/// or the error value if we encountered an error.\n///\n/// On [`Err::Error`], iteration will stop. To instead chain an error up, see [`cut`].\n///\n/// ```rust\n/// use nom::{combinator::iterator, IResult, bytes::complete::tag, character::complete::alpha1, sequence::terminated};\n/// use std::collections::HashMap;\n///\n/// let data = \"abc|defg|hijkl|mnopqr|123\";\n/// let mut it = iterator(data, terminated(alpha1, tag(\"|\")));\n///\n/// let parsed = it.by_ref().map(|v| (v, v.len())).collect::>();\n/// let res: IResult<_,_> = it.finish();\n///\n/// assert_eq!(parsed, [(\"abc\", 3usize), (\"defg\", 4), (\"hijkl\", 5), (\"mnopqr\", 6)].iter().cloned().collect());\n/// assert_eq!(res, Ok((\"123\", ())));\n/// ```\npub fn iterator(input: Input, f: F) -> ParserIterator\nwhere\n F: Parser,\n Error: ParseError,\n{\n ParserIterator {\n iterator: f,\n input,\n state: Some(State::Running),\n }\n}\n\n/// Main structure associated to the [iterator] function.\npub struct ParserIterator {\n iterator: F,\n input: I,\n state: Option>,\n}\n\nimpl ParserIterator {\n /// Returns the remaining input if parsing was successful, or the error if we encountered an error.\n pub fn finish(mut self) -> IResult {\n match self.state.take().unwrap() {\n State::Running | State::Done => Ok((self.input, ())),\n State::Failure(e) => Err(Err::Failure(e)),\n State::Incomplete(i) => Err(Err::Incomplete(i)),\n }\n }\n}\n\nimpl core::iter::Iterator for ParserIterator\nwhere\n F: Parser,\n Input: Clone,\n{\n type Item = Output;\n\n fn next(&mut self) -> Option {\n if let State::Running = self.state.take().unwrap() {\n let input = self.input.clone();\n\n match (self.iterator).parse(input) {\n Ok((i, o)) => {\n self.input = i;\n self.state = Some(State::Running);\n Some(o)\n }\n Err(Err::Error(_)) => {\n self.state = Some(State::Done);\n None\n }\n Err(Err::Failure(e)) => {\n self.state = Some(State::Failure(e));\n None\n }\n Err(Err::Incomplete(i)) => {\n self.state = Some(State::Incomplete(i));\n None\n }\n }\n } else {\n None\n }\n }\n}\n\nenum State {\n Running,\n Done,\n Failure(E),\n Incomplete(Needed),\n}\n\n/// a parser which always succeeds with given value without consuming any input.\n///\n/// It can be used for example as the last alternative in `alt` to\n/// specify the default case.\n///\n/// ```rust\n/// # use nom::{Err,error::ErrorKind, IResult, Parser};\n/// use nom::branch::alt;\n/// use nom::combinator::{success, value};\n/// use nom::character::complete::char;\n/// # fn main() {\n///\n/// let mut parser = success::<_,_,(_,ErrorKind)>(10);\n/// assert_eq!(parser.parse(\"xyz\"), Ok((\"xyz\", 10)));\n///\n/// let mut sign = alt((value(-1, char('-')), value(1, char('+')), success::<_,_,(_,ErrorKind)>(1)));\n/// assert_eq!(sign.parse(\"+10\"), Ok((\"10\", 1)));\n/// assert_eq!(sign.parse(\"-10\"), Ok((\"10\", -1)));\n/// assert_eq!(sign.parse(\"10\"), Ok((\"10\", 1)));\n/// # }\n/// ```\npub fn success>(val: O) -> impl Parser {\n Success {\n val,\n e: PhantomData,\n }\n}\n\n/// Parser implementation for [success]\npub struct Success {\n val: O,\n e: PhantomData,\n}\n\nimpl Parser for Success\nwhere\n O: Clone,\n E: ParseError,\n{\n type Output = O;\n type Error = E;\n\n fn process(&mut self, input: I) -> PResult {\n Ok((input, OM::Output::bind(|| self.val.clone())))\n }\n}\n\n/// A parser which always fails.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, IResult, Parser};\n/// use nom::combinator::fail;\n///\n/// let s = \"string\";\n/// assert_eq!(fail::<_, &str, _>().parse(s), Err(Err::Error((s, ErrorKind::Fail))));\n/// ```\npub fn fail>() -> impl Parser {\n Fail {\n o: PhantomData,\n e: PhantomData,\n }\n}\n\n/// Parser implementation for [fail]\npub struct Fail {\n o: PhantomData,\n e: PhantomData,\n}\n\nimpl Parser for Fail\nwhere\n E: ParseError,\n{\n type Output = O;\n type Error = E;\n\n fn process(&mut self, input: I) -> PResult {\n Err(Err::Error(OM::Error::bind(|| {\n E::from_error_kind(input, ErrorKind::Fail)\n })))\n }\n}"} {"repo": "nom", "lang": "rust", "aspect": "parsers", "file": "mod.rs", "content": "#[cfg(test)]\nmod tests;\n\nuse crate::error::ParseError;\nuse crate::internal::{IResult, Parser};\nuse crate::{Check, OutputM, OutputMode, PResult};\n\n/// Gets an object from the first parser,\n/// then gets another object from the second parser.\n///\n/// # Arguments\n/// * `first` The first parser to apply.\n/// * `second` The second parser to apply.\n///\n/// # Example\n/// ```rust\n/// use nom::sequence::pair;\n/// use nom::bytes::complete::tag;\n/// use nom::{error::ErrorKind, Err, Parser};\n///\n/// let mut parser = pair(tag(\"abc\"), tag(\"efg\"));\n///\n/// assert_eq!(parser.parse(\"abcefg\"), Ok((\"\", (\"abc\", \"efg\"))));\n/// assert_eq!(parser.parse(\"abcefghij\"), Ok((\"hij\", (\"abc\", \"efg\"))));\n/// assert_eq!(parser.parse(\"\"), Err(Err::Error((\"\", ErrorKind::Tag))));\n/// assert_eq!(parser.parse(\"123\"), Err(Err::Error((\"123\", ErrorKind::Tag))));\n/// ```\npub fn pair, F, G>(\n first: F,\n second: G,\n) -> impl Parser\nwhere\n F: Parser,\n G: Parser,\n{\n first.and(second)\n}\n\n/// Matches an object from the first parser and discards it,\n/// then gets an object from the second parser.\n///\n/// # Arguments\n/// * `first` The opening parser.\n/// * `second` The second parser to get object.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::sequence::preceded;\n/// use nom::bytes::complete::tag;\n///\n/// let mut parser = preceded(tag(\"abc\"), tag(\"efg\"));\n///\n/// assert_eq!(parser.parse(\"abcefg\"), Ok((\"\", \"efg\")));\n/// assert_eq!(parser.parse(\"abcefghij\"), Ok((\"hij\", \"efg\")));\n/// assert_eq!(parser.parse(\"\"), Err(Err::Error((\"\", ErrorKind::Tag))));\n/// assert_eq!(parser.parse(\"123\"), Err(Err::Error((\"123\", ErrorKind::Tag))));\n/// ```\npub fn preceded, F, G>(\n first: F,\n second: G,\n) -> impl Parser\nwhere\n F: Parser,\n G: Parser,\n{\n Preceded {\n f: first,\n g: second,\n }\n}\n\n/// a\npub struct Preceded {\n f: F,\n g: G,\n}\n\nimpl, F: Parser, G: Parser> Parser\n for Preceded\n{\n type Output = >::Output;\n type Error = E;\n\n #[inline(always)]\n fn process(&mut self, i: I) -> PResult {\n let (i, _) = self\n .f\n .process::>(i)?;\n let (i, o2) = self.g.process::(i)?;\n\n Ok((i, o2))\n }\n}\n\n/// Gets an object from the first parser,\n/// then matches an object from the second parser and discards it.\n///\n/// # Arguments\n/// * `first` The first parser to apply.\n/// * `second` The second parser to match an object.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::sequence::terminated;\n/// use nom::bytes::complete::tag;\n///\n/// let mut parser = terminated(tag(\"abc\"), tag(\"efg\"));\n///\n/// assert_eq!(parser.parse(\"abcefg\"), Ok((\"\", \"abc\")));\n/// assert_eq!(parser.parse(\"abcefghij\"), Ok((\"hij\", \"abc\")));\n/// assert_eq!(parser.parse(\"\"), Err(Err::Error((\"\", ErrorKind::Tag))));\n/// assert_eq!(parser.parse(\"123\"), Err(Err::Error((\"123\", ErrorKind::Tag))));\n/// ```\npub fn terminated, F, G>(\n first: F,\n second: G,\n) -> impl Parser\nwhere\n F: Parser,\n G: Parser,\n{\n Terminated {\n f: first,\n g: second,\n }\n}\n\n/// a\npub struct Terminated {\n f: F,\n g: G,\n}\n\nimpl, F: Parser, G: Parser> Parser\n for Terminated\n{\n type Output = >::Output;\n type Error = E;\n\n #[inline(always)]\n fn process(&mut self, i: I) -> PResult {\n let (i, o1) = self.f.process::(i)?;\n let (i, _) = self\n .g\n .process::>(i)?;\n\n Ok((i, o1))\n }\n}\n\n/// Gets an object from the first parser,\n/// then matches an object from the sep_parser and discards it,\n/// then gets another object from the second parser.\n///\n/// # Arguments\n/// * `first` The first parser to apply.\n/// * `sep` The separator parser to apply.\n/// * `second` The second parser to apply.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::sequence::separated_pair;\n/// use nom::bytes::complete::tag;\n///\n/// let mut parser = separated_pair(tag(\"abc\"), tag(\"|\"), tag(\"efg\"));\n///\n/// assert_eq!(parser.parse(\"abc|efg\"), Ok((\"\", (\"abc\", \"efg\"))));\n/// assert_eq!(parser.parse(\"abc|efghij\"), Ok((\"hij\", (\"abc\", \"efg\"))));\n/// assert_eq!(parser.parse(\"\"), Err(Err::Error((\"\", ErrorKind::Tag))));\n/// assert_eq!(parser.parse(\"123\"), Err(Err::Error((\"123\", ErrorKind::Tag))));\n/// ```\npub fn separated_pair, F, G, H>(\n first: F,\n sep: G,\n second: H,\n) -> impl Parser\nwhere\n F: Parser,\n G: Parser,\n H: Parser,\n{\n first.and(preceded(sep, second))\n}\n\n/// Matches an object from the first parser and discards it,\n/// then gets an object from the second parser,\n/// and finally matches an object from the third parser and discards it.\n///\n/// # Arguments\n/// * `first` The first parser to apply and discard.\n/// * `second` The second parser to apply.\n/// * `third` The third parser to apply and discard.\n///\n/// ```rust\n/// # use nom::{Err, error::ErrorKind, Needed, Parser};\n/// # use nom::Needed::Size;\n/// use nom::sequence::delimited;\n/// use nom::bytes::complete::tag;\n///\n/// let mut parser = delimited(tag(\"(\"), tag(\"abc\"), tag(\")\"));\n///\n/// assert_eq!(parser.parse(\"(abc)\"), Ok((\"\", \"abc\")));\n/// assert_eq!(parser.parse(\"(abc)def\"), Ok((\"def\", \"abc\")));\n/// assert_eq!(parser.parse(\"\"), Err(Err::Error((\"\", ErrorKind::Tag))));\n/// assert_eq!(parser.parse(\"123\"), Err(Err::Error((\"123\", ErrorKind::Tag))));\n/// ```\npub fn delimited, F, G, H>(\n first: F,\n second: G,\n third: H,\n) -> impl Parser\nwhere\n F: Parser,\n G: Parser,\n H: Parser,\n{\n preceded(first, terminated(second, third))\n}\n\n/// Helper trait for the tuple combinator.\n///\n/// This trait is implemented for tuples of parsers of up to 21 elements.\n#[deprecated(since = \"8.0.0\", note = \"`Parser` is directly implemented for tuples\")]\n#[allow(deprecated)]\npub trait Tuple {\n /// Parses the input and returns a tuple of results of each parser.\n fn parse_tuple(&mut self, input: I) -> IResult;\n}\n\n#[allow(deprecated)]\nimpl, F: Parser>\n Tuple for (F,)\n{\n fn parse_tuple(&mut self, input: Input) -> IResult {\n self.0.parse(input).map(|(i, o)| (i, (o,)))\n }\n}\n\nmacro_rules! tuple_trait(\n ($name1:ident $ty1:ident, $name2: ident $ty2:ident, $($name:ident $ty:ident),*) => (\n tuple_trait!(__impl $name1 $ty1, $name2 $ty2; $($name $ty),*);\n );\n (__impl $($name:ident $ty: ident),+; $name1:ident $ty1:ident, $($name2:ident $ty2:ident),*) => (\n tuple_trait_impl!($($name $ty),+);\n tuple_trait!(__impl $($name $ty),+ , $name1 $ty1; $($name2 $ty2),*);\n );\n (__impl $($name:ident $ty: ident),+; $name1:ident $ty1:ident) => (\n tuple_trait_impl!($($name $ty),+);\n tuple_trait_impl!($($name $ty),+, $name1 $ty1);\n );\n);\n\nmacro_rules! tuple_trait_impl(\n ($($name:ident $ty: ident),+) => (\n #[allow(deprecated)]\n impl<\n Input: Clone, $($ty),+ , Error: ParseError,\n $($name: Parser),+\n > Tuple for ( $($name),+ ) {\n fn parse_tuple(&mut self, input: Input) -> IResult {\n tuple_trait_inner!(0, self, input, (), $($name)+)\n\n }\n }\n );\n);\n\nmacro_rules! tuple_trait_inner(\n ($it:tt, $self:expr, $input:expr, (), $head:ident $($id:ident)+) => ({\n let (i, o) = $self.$it.parse($input)?;\n\n succ!($it, tuple_trait_inner!($self, i, ( o ), $($id)+))\n });\n ($it:tt, $self:expr, $input:expr, ($($parsed:tt)*), $head:ident $($id:ident)+) => ({\n let (i, o) = $self.$it.parse($input)?;\n\n succ!($it, tuple_trait_inner!($self, i, ($($parsed)* , o), $($id)+))\n });\n ($it:tt, $self:expr, $input:expr, ($($parsed:tt)*), $head:ident) => ({\n let (i, o) = $self.$it.parse($input)?;\n\n Ok((i, ($($parsed)* , o)))\n });\n);\n\ntuple_trait!(FnA A, FnB B, FnC C, FnD D, FnE E, FnF F, FnG G, FnH H, FnI I, FnJ J, FnK K, FnL L,\n FnM M, FnN N, FnO O, FnP P, FnQ Q, FnR R, FnS S, FnT T, FnU U);\n\n// Special case: implement `Tuple` for `()`, the unit type.\n// This can come up in macros which accept a variable number of arguments.\n// Literally, `()` is an empty tuple, so it should simply parse nothing.\n#[allow(deprecated)]\nimpl> Tuple for () {\n fn parse_tuple(&mut self, input: I) -> IResult {\n Ok((input, ()))\n }\n}\n\n///Applies a tuple of parsers one by one and returns their results as a tuple.\n///There is a maximum of 21 parsers\n/// ```rust\n/// # use nom::{Err, error::ErrorKind};\n/// use nom::sequence::tuple;\n/// use nom::character::complete::{alpha1, digit1};\n/// let mut parser = tuple((alpha1, digit1, alpha1));\n///\n/// assert_eq!(parser(\"abc123def\"), Ok((\"\", (\"abc\", \"123\", \"def\"))));\n/// assert_eq!(parser(\"123def\"), Err(Err::Error((\"123def\", ErrorKind::Alpha))));\n/// ```\n#[deprecated(since = \"8.0.0\", note = \"`Parser` is directly implemented for tuples\")]\n#[allow(deprecated)]\npub fn tuple, List: Tuple>(\n mut l: List,\n) -> impl FnMut(I) -> IResult {\n move |i: I| l.parse_tuple(i)\n}"}