### Result unwrap Example Source: https://docs.rs/nom/latest/nom/type.IResult.html Shows how to use unwrap to get the Ok value, panicking if the Result is an Err. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### take_till - Streaming Example Source: https://docs.rs/nom/latest/nom/bytes/streaming/fn.take_till.html This example demonstrates how to use the streaming version of take_till to parse a string until a colon is encountered. It shows successful parsing, handling of empty matches, and incomplete input scenarios. ```rust use nom::bytes::streaming::take_till; use nom::IResult; use nom::Err; use nom::Needed; fn till_colon(s: &str) -> IResult<&str, &str> { take_till(|c| c == ':')(s) } assert_eq!(till_colon("latin:123"), Ok((":123", "latin"))); assert_eq!(till_colon(":empty matched"), Ok((":empty matched", ""))); //allowed assert_eq!(till_colon("12345"), Err(Err::Incomplete(Needed::new(1)))); assert_eq!(till_colon(""), Err(Err::Incomplete(Needed::new(1)))); ``` -------------------------------- ### Result iter Example Source: https://docs.rs/nom/latest/nom/type.IResult.html Shows how to use the iter method to get an iterator over the contained value if it's Ok. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); ``` ```rust let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### flat_map Example with u8 and take Source: https://docs.rs/nom/latest/nom/combinator/fn.flat_map.html This example demonstrates using `flat_map` to first parse a `u8` value and then use that value to determine how many bytes to take with the `take` parser. It shows a successful parse and an error case. ```rust use nom::bytes::complete::take; use nom::number::complete::u8; use nom::combinator::flat_map; let mut parse = flat_map(u8, take); assert_eq!(parse.parse(&[2, 0, 1, 2][..]), Ok((&[2][..], &[0, 1][..]))); assert_eq!(parse.parse(&[4, 0, 1, 2][..]), Err(Err::Error((&[0, 1, 2][..], ErrorKind::Eof)))); ``` -------------------------------- ### map_parser usage example Source: https://docs.rs/nom/latest/nom/combinator/fn.map_parser.html This example demonstrates how to use map_parser to first take a fixed number of characters and then parse those characters as digits. ```APIDOC ## Example Usage ```rust use nom::character::complete::digit1; use nom::bytes::complete::take; use nom::combinator::map_parser; let mut parse = map_parser(take(5u8), digit1); assert_eq!(parse.parse("12345"), Ok(("", "12345"))); assert_eq!(parse.parse("123ab"), Ok(("", "123"))); assert_eq!(parse.parse("123"), Err(Err::Error(("123", ErrorKind::Eof)))); ``` ``` -------------------------------- ### take_until1 Example Source: https://docs.rs/nom/latest/nom/bytes/complete/fn.take_until1.html Demonstrates the usage of `take_until1` to parse a string until a specific pattern. It returns the slice before the pattern and the rest of the input starting with the pattern. An error is returned if the pattern is not found. ```rust use nom::bytes::complete::take_until1; use nom::IResult; use nom::error::{Error, ErrorKind}; fn until_eof(s: &str) -> IResult<&str, &str> { take_until1("eof")(s) } assert_eq!(until_eof("hello, worldeof"), Ok(("eof", "hello, world"))); assert_eq!(until_eof("hello, world"), Err(Err::Error(Error::new("hello, world", ErrorKind::TakeUntil)))); assert_eq!(until_eof(""), Err(Err::Error(Error::new("", ErrorKind::TakeUntil)))); assert_eq!(until_eof("1eof2eof"), Ok(("eof2eof", "1"))); assert_eq!(until_eof("eof"), Err(Err::Error(Error::new("eof", ErrorKind::TakeUntil)))); ``` -------------------------------- ### hex_digit1 Example Usage Source: https://docs.rs/nom/latest/nom/character/complete/fn.hex_digit1.html An example demonstrating how to use the hex_digit1 function in a parser and its expected outcomes. ```APIDOC fn parser(input: &str) -> IResult<&str, &str> { hex_digit1(input) } assert_eq!(parser("21cZ"), Ok(("Z", "21c"))); assert_eq!(parser("H2"), Err(Err::Error(Error::new("H2", ErrorKind::HexDigit)))); assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::HexDigit)))); ``` -------------------------------- ### Example without cut Source: https://docs.rs/nom/latest/nom/combinator/fn.cut.html Demonstrates the behavior of `alt` without `cut`, where alternative branches are explored after a partial match. ```rust fn parser(input: &str) -> IResult<&str, &str> { alt(( preceded(one_of("+-"), digit1), rest )).parse(input) } assert_eq!(parser("+10 ab"), Ok((" ab", "10"))); assert_eq!(parser("ab"), Ok(("", "ab"))); assert_eq!(parser("+"), Ok(("", "+"))); ``` -------------------------------- ### take_until Example Source: https://docs.rs/nom/latest/nom/bytes/streaming/fn.take_until.html Demonstrates how to use `take_until` to parse a string until a specific pattern is encountered. It shows cases where the pattern is found, not found, or partially present. ```rust use nom::bytes::streaming::take_until; fn until_eof(s: &str) -> IResult<&str, &str> { take_until("eof")(s) } assert_eq!(until_eof("hello, worldeof"), Ok(("eof", "hello, world"))); assert_eq!(until_eof("hello, world"), Err(Err::Incomplete(Needed::Unknown))); assert_eq!(until_eof("hello, worldeo"), Err(Err::Incomplete(Needed::Unknown))); assert_eq!(until_eof("1eof2eof"), Ok(("eof2eof", "1"))); ``` -------------------------------- ### Into Ok Example (Nightly) Source: https://docs.rs/nom/latest/nom/type.IResult.html Safely extracts the Ok value without panicking, intended for Result types where the error is uninhabitable (!). This API is experimental and nightly-only. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Take Until Pattern Example Source: https://docs.rs/nom/latest/nom/bytes/complete/fn.take_until.html Demonstrates how to use `take_until` to parse a string up to a specific substring. It shows successful parsing and error cases when the pattern is not found. ```rust use nom::bytes::complete::take_until; fn until_eof(s: &str) -> IResult<&str, &str> { take_until("eof")(s) } assert_eq!(until_eof("hello, worldeof"), Ok(("eof", "hello, world"))); assert_eq!(until_eof("hello, world"), Err(Err::Error(Error::new("hello, world", ErrorKind::TakeUntil)))); assert_eq!(until_eof(""), Err(Err::Error(Error::new("", ErrorKind::TakeUntil)))); assert_eq!(until_eof("1eof2eof"), Ok(("eof2eof", "1"))); ``` -------------------------------- ### Example Usage of bytes Source: https://docs.rs/nom/latest/nom/bits/fn.bytes.html This example demonstrates how to use the `bytes` function in conjunction with other `nom` combinators to parse a byte slice as if it were a bit stream, extracting specific bit and byte segments. ```APIDOC ```rust use nom::bits::{bits, bytes, streaming::take}; use nom::combinator::rest; use nom::error::Error; use nom::IResult; fn parse(input: &[u8]) -> IResult<&[u8], (u8, u8, &[u8])> { bits::<_, _, Error<(&[u8], usize)>, _, _>(( take(4usize), take(8usize), bytes::<_, _, Error<&[u8]>, _, _>(rest) ))(input) } let input = &[0x12, 0x34, 0xff, 0xff]; assert_eq!(parse( input ), Ok(( &[][..], (0x01, 0x23, &[0xff, 0xff][..]) ))); ``` ``` -------------------------------- ### Result expect Example Source: https://docs.rs/nom/latest/nom/type.IResult.html Illustrates the use of expect to retrieve the Ok value or panic with a custom message if it's an Err. ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Or Method Example Source: https://docs.rs/nom/latest/nom/type.IResult.html Returns the second Result if the first is Err, otherwise returns the first's Ok value. Arguments are eagerly evaluated. ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### Example Usage of length_value Source: https://docs.rs/nom/latest/nom/multi/fn.length_value.html This example demonstrates how to use `length_value` with `be_u16` to read a 16-bit unsigned integer as the length and `tag` to parse a specific byte sequence of that length. ```APIDOC ```rust use nom::number::complete::be_u16; use nom::multi::length_value; use nom::bytes::complete::tag; use nom::{IResult, Err, Error, ErrorKind, Needed}; fn parser(s: &[u8]) -> IResult<&[u8], &[u8]> { length_value(be_u16, tag("abc")).parse(s) } // Successful parsing: length is 3, followed by "abc" assert_eq!(parser(b"\x00\x03abcefg"), Ok((&b"efg"[..], &b"abc"[..]))); // Error: The tag "abc" does not match "123" assert_eq!(parser(b"\x00\x03123123"), Err(Err::Error(Error::new(&b"123"[..], ErrorKind::Tag)))); // Incomplete: Not enough input to satisfy the length (2 bytes for u16) and the tag assert_eq!(parser(b"\x00\x03a"), Err(Err::Incomplete(Needed::new(2)))); ``` ``` -------------------------------- ### length_count Example Source: https://docs.rs/nom/latest/nom/multi/fn.length_count.html This example demonstrates how to use `length_count` to parse a specific number of 'abc' tags, where the number is determined by a preceding `u8` parser. It shows a successful parse and an unsuccessful one due to incorrect input. ```rust use nom::number::complete::u8; use nom::multi::length_count; use nom::bytes::complete::tag; use nom::combinator::map; fn parser(s: &[u8]) -> IResult<&[u8], Vec<&[u8]>> { length_count(map(u8, |i| { println!("got number: {}", i); i }), tag("abc")).parse(s) } assert_eq!(parser(&b"\x02abcabcabc"[..]), Ok(((&b"abc"[..], vec![&b"abc"[..], &b"abc"[..]])))); assert_eq!(parser(b"\x03123123123"), Err(Err::Error(Error::new(&b"123123123"[..], ErrorKind::Tag)))); ``` -------------------------------- ### all_consuming Example Source: https://docs.rs/nom/latest/nom/combinator/fn.all_consuming.html Demonstrates the usage of `all_consuming` with `alpha1`. It shows successful consumption of the entire input and failure cases where input remains or an incorrect character is encountered. ```rust use nom::combinator::all_consuming; use nom::character::complete::alpha1; let mut parser = all_consuming(alpha1); assert_eq!(parser.parse("abcd"), Ok(("", "abcd"))); assert_eq!(parser.parse("abcd;"),Err(Err::Error((";", ErrorKind::Eof)))); assert_eq!(parser.parse("123abcd;"),Err(Err::Error(("123abcd;", ErrorKind::Alpha)))); ``` -------------------------------- ### take_till Example Source: https://docs.rs/nom/latest/nom/bytes/complete/fn.take_till.html Demonstrates how to use `take_till` to parse a string until a specific character is encountered. It handles cases where the delimiter is not found or is at the beginning of the string. ```rust use nom::bytes::complete::take_till; fn till_colon(s: &str) -> IResult<&str, &str> { take_till(|c| c == ':')(s) } assert_eq!(till_colon("latin:123"), Ok((":123", "latin"))); assert_eq!(till_colon(":empty matched"), Ok((":empty matched", ""))); //allowed assert_eq!(till_colon("12345"), Ok(("", "12345"))); assert_eq!(till_colon(""), Ok(("", ""))); ``` -------------------------------- ### Example with cut Source: https://docs.rs/nom/latest/nom/combinator/fn.cut.html Demonstrates how `cut` changes the error handling of `alt`. A failure within a `cut`-wrapped parser results in `Err::Failure`, preventing further alternatives. ```rust use nom::combinator::cut; fn parser(input: &str) -> IResult<&str, &str> { alt(( preceded(one_of("+-"), cut(digit1)), rest )).parse(input) } assert_eq!(parser("+10 ab"), Ok((" ab", "10"))); assert_eq!(parser("ab"), Ok(("", "ab"))); assert_eq!(parser("+"), Err(Err::Failure(Error { input: "", code: ErrorKind::Digit }))); ``` -------------------------------- ### Using into to convert parser output Source: https://docs.rs/nom/latest/nom/combinator/fn.into.html This example demonstrates how `into` converts the `&str` output of `alpha1` into a `Vec`. Ensure the target type implements `From` for the source type. ```rust use nom::combinator::into; use nom::character::complete::alpha1; fn parser1(i: &str) -> IResult<&str, &str> { alpha1(i) } let mut parser2 = into(parser1); // the parser converts the &str output of the child parser into a Vec let bytes: IResult<&str, Vec> = parser2.parse("abcd"); assert_eq!(bytes, Ok(("", vec![97, 98, 99, 100]))); ``` -------------------------------- ### Result unwrap_or_default Example Source: https://docs.rs/nom/latest/nom/type.IResult.html Demonstrates unwrap_or_default, which returns the Ok value or the default value for the type if it's an Err. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### Result as_deref_mut Example Source: https://docs.rs/nom/latest/nom/type.IResult.html Demonstrates the use of as_deref_mut on Result types for mutable borrowing of the inner value. ```rust let mut s = "HELLO".to_string(); let mut x: Result = Ok("hello".to_string()); let y: Result<&mut str, &mut u32> = Ok(&mut s); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); ``` ```rust let mut i = 42; let mut x: Result = Err(42); let y: Result<&mut str, &mut u32> = Err(&mut i); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); ``` -------------------------------- ### And Method Example Source: https://docs.rs/nom/latest/nom/type.IResult.html Combines two Results, returning the second if the first is Ok, otherwise returning the first's Err. Arguments are eagerly evaluated. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### take_while1 Example Source: https://docs.rs/nom/latest/nom/bytes/complete/fn.take_while1.html Demonstrates how to use `take_while1` to parse a sequence of alphabetic characters. It returns an error if no alphabetic characters are found at the beginning of the input. ```rust use nom::bytes::complete::take_while1; use nom::AsChar; fn alpha(s: &[u8]) -> IResult<&[u8], &[u8]> { take_while1(AsChar::is_alpha)(s) } assert_eq!(alpha(b"latin123"), Ok((&b"123"[..], &b"latin"[..]))); assert_eq!(alpha(b"latin"), Ok((&b""[..], &b"latin"[..]))); assert_eq!(alpha(b"12345"), Err(Err::Error(Error::new(&b"12345"[..], ErrorKind::TakeWhile1)))); ``` -------------------------------- ### Parse Little Endian u64 Source: https://docs.rs/nom/latest/nom/number/complete/fn.le_u64.html This example demonstrates parsing a little-endian u64. It shows a successful parse and an error case where the input is too short. ```rust use nom::number::complete::le_u64; use nom::Err; use nom::error::ErrorKind; let parser = |s| { le_u64(s) }; assert_eq!(parser(&b"\x00\x01\x02\x03\x04\x05\x06\x07abcefg"[..]), Ok((&b"abcefg"[..], 0x0706050403020100))); assert_eq!(parser(&b"\x01"[..]), Err(Err::Error((&[0x01][..], ErrorKind::Eof)))); ``` -------------------------------- ### Recognize Float Example Source: https://docs.rs/nom/latest/nom/number/complete/fn.recognize_float.html Demonstrates the usage of `recognize_float` to parse various floating-point number formats. It shows successful parsing and error cases. ```rust use nom::number::complete::recognize_float; let parser = |s| { recognize_float(s) }; assert_eq!(parser("11e-1"), Ok(("", "11e-1"))); assert_eq!(parser("123E-02"), Ok(("", "123E-02"))); assert_eq!(parser("123K-01"), Ok(("K-01", "123"))); assert_eq!(parser("abc"), Err(Err::Error(("abc", ErrorKind::Char)))); ``` -------------------------------- ### Result unwrap_err Example Source: https://docs.rs/nom/latest/nom/type.IResult.html Shows how to use unwrap_err to get the Err value, panicking if the Result is an Ok. ```rust let x: Result = Err("error message"); assert_eq!(x.unwrap_err(), "error message"); ``` -------------------------------- ### Parse Little Endian f32 Source: https://docs.rs/nom/latest/nom/number/streaming/fn.le_f32.html This example demonstrates how to use `le_f32` to parse a little-endian f32. It shows successful parsing and how the function handles incomplete input. ```rust use nom::number::streaming::le_f32; use nom::Err; use nom::error::ErrorKind; use nom::Needed; let parser = |s| { le_f32::<_, (_, ErrorKind)>(s) }; assert_eq!(parser(&[0x00, 0x00, 0x48, 0x41][..]), Ok((&b""[..], 12.5))); assert_eq!(parser(&[0x01][..]), Err(Err::Incomplete(Needed::new(3)))); ``` -------------------------------- ### Parse Big Endian f64 Source: https://docs.rs/nom/latest/nom/number/streaming/fn.be_f64.html This example demonstrates how to use `be_f64` to parse a big-endian f64. It shows a successful parse and an incomplete parse scenario. ```rust use nom::number::streaming::be_f64; use nom::Err; use nom::error::{ErrorKind, ParseError}; use nom::Needed; let parser = |s| { be_f64::<_, (_, ErrorKind)>(s) }; assert_eq!(parser(&[0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00][..]), Ok((&b""[..], 12.5))); assert_eq!(parser(&[0x01][..]), Err(Err::Incomplete(Needed::new(7)))); ``` -------------------------------- ### Parse a u8 using le_u8 Source: https://docs.rs/nom/latest/nom/number/complete/fn.le_u8.html This example demonstrates parsing a single byte as a `u8`. It shows successful parsing and an error case for empty input. ```rust use nom::number::complete::le_u8; use nom::IResult; use nom::error::{ParseError, ErrorKind}; let parser = |s: &[u8]| { le_u8::<_, ParseError<&[u8]>>(s) }; assert_eq!(parser(&b"\x00\x03abcefg"[..]), Ok((&b"\x03abcefg"[..], 0x00))); assert_eq!(parser(&b""[..]), Err(Err::Error((&[][..], ErrorKind::Eof)))); ``` -------------------------------- ### Recognizing Hexadecimal Digits Source: https://docs.rs/nom/latest/nom/character/streaming/fn.hex_digit0.html This example demonstrates how `hex_digit0` parses a string containing hexadecimal characters. It shows successful parsing and cases where the input is empty or starts with a non-hexadecimal character. ```rust assert_eq!(hex_digit0::<_, (_, ErrorKind)>("21cZ"), Ok(("Z", "21c"))); ``` ```rust assert_eq!(hex_digit0::<_, (_, ErrorKind)>("Z21c"), Ok(("Z21c", ""))); ``` ```rust assert_eq!(hex_digit0::<_, (_, ErrorKind)>(""), Err(Err::Incomplete(Needed::new(1)))); ``` -------------------------------- ### take Source: https://docs.rs/nom/latest/nom/bytes/complete/index.html Returns an input slice containing the first N input elements. ```APIDOC ## take ### Description Returns an input slice containing the first N input elements (Input[..N]). ### Method Not applicable (function signature) ### Endpoint Not applicable (function signature) ### Parameters None explicitly documented. ### Request Example None explicitly documented. ### Response None explicitly documented. ``` -------------------------------- ### many_m_n Example Source: https://docs.rs/nom/latest/nom/multi/fn.many_m_n.html Demonstrates parsing a string with `many_m_n` to match 'abc' between 0 and 2 times. Shows successful matches, partial matches, and no matches. ```rust use nom::multi::many_m_n; use nom::bytes::complete::tag; fn parser(s: &str) -> IResult<&str, Vec<&str>> { many_m_n(0, 2, tag("abc")).parse(s) } assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"]))); assert_eq!(parser("abc123"), Ok(("123", vec!["abc"]))); assert_eq!(parser("123123"), Ok(("123123", vec![]))); assert_eq!(parser(""), Ok(("", vec![]))); assert_eq!(parser("abcabcabc"), Ok(("abc", vec!["abc", "abc"]))); ``` -------------------------------- ### Parse one or more 'abc' tags Source: https://docs.rs/nom/latest/nom/multi/fn.many1.html This example demonstrates using `many1` with `tag("abc")` to parse a string that must start with one or more occurrences of "abc". It shows successful parsing with multiple matches, a single match, and failure cases when the input doesn't start with "abc" or is empty. ```rust use nom::multi::many1; use nom::bytes::complete::tag; use nom::IResult; use nom::error::{Error, ErrorKind, ParseErrorKind}; fn parser(s: &str) -> IResult<&str, Vec<&str>> { many1(tag("abc")).parse(s) } assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"]))); assert_eq!(parser("abc123"), Ok(("123", vec!["abc"]))); assert_eq!(parser("123123"), Err(nom::Err::Error(nom::error::Error::new("123123", nom::error::ErrorKind::Tag)))); assert_eq!(parser(""), Err(nom::Err::Error(nom::error::Error::new("", nom::error::ErrorKind::Tag)))); ``` -------------------------------- ### Using preceded with tag parsers Source: https://docs.rs/nom/latest/nom/sequence/fn.preceded.html This example demonstrates how to use `preceded` to parse a string that starts with "abc" and is followed by "efg". It shows successful parsing and error cases. ```rust use nom::sequence::preceded; use nom::bytes::complete::tag; let mut parser = preceded(tag("abc"), tag("efg")); assert_eq!(parser.parse("abcefg"), Ok(("", "efg"))); assert_eq!(parser.parse("abcefghij"), Ok(("hij", "efg"))); assert_eq!(parser.parse(""), Err(Err::Error(("", ErrorKind::Tag)))); assert_eq!(parser.parse("123"), Err(Err::Error(("123", ErrorKind::Tag)))); ``` -------------------------------- ### take_until1 Example Source: https://docs.rs/nom/latest/nom/bytes/fn.take_until1.html Demonstrates the usage of `take_until1` to parse a string until a specific pattern. It shows successful parsing, incomplete input scenarios, and cases where the pattern is at the beginning. ```rust use nom::bytes::streaming::take_until1; use nom::IResult; use nom::Err; use nom::error::{Error, ErrorKind, ParseError}; use nom::Needed; fn until_eof(s: &str) -> IResult<&str, &str> { take_until1("eof")(s) } assert_eq!(until_eof("hello, worldeof"), Ok(("eof", "hello, world"))); assert_eq!(until_eof("hello, world"), Err(Err::Incomplete(Needed::Unknown))); assert_eq!(until_eof("hello, worldeo"), Err(Err::Incomplete(Needed::Unknown))); assert_eq!(until_eof("1eof2eof"), Ok(("eof2eof", "1"))); assert_eq!(until_eof("eof"), Err(Err::Error(Error::new("eof", ErrorKind::TakeUntil)))); ``` -------------------------------- ### Take Bits Parser Example Source: https://docs.rs/nom/latest/nom/bits/complete/fn.take.html Demonstrates how to use the `take` parser to consume a specific number of bits from an input tuple containing a byte slice and a bit offset. Shows behavior with zero bits, partial bits, and insufficient bits. ```rust // Input is a tuple of (input: I, bit_offset: usize) fn parser(input: (&[u8], usize), count: usize)-> IResult<(&[u8], usize), u8> { take(count)(input) } // Consumes 0 bits, returns 0 assert_eq!(parser(([0b00010010].as_ref(), 0), 0), Ok((([0b00010010].as_ref(), 0), 0))); // Consumes 4 bits, returns their values and increase offset to 4 assert_eq!(parser(([0b00010010].as_ref(), 0), 4), Ok((([0b00010010].as_ref(), 4), 0b00000001))); // Consumes 4 bits, offset is 4, returns their values and increase offset to 0 of next byte assert_eq!(parser(([0b00010010].as_ref(), 4), 4), Ok((([].as_ref(), 0), 0b00000010))); // Tries to consume 12 bits but only 8 are available assert_eq!(parser(([0b00010010].as_ref(), 0), 12), Err(nom::Err::Error(Error{input: ([0b00010010].as_ref(), 0), code: ErrorKind::Eof }))); ``` -------------------------------- ### Parse Alphanumeric Characters Source: https://docs.rs/nom/latest/nom/character/complete/fn.alphanumeric1.html This example demonstrates how to use the alphanumeric1 parser to extract a sequence of alphanumeric characters from a string. It shows successful parsing and error cases, including empty input and input starting with a non-alphanumeric character. ```rust fn parser(input: &str) -> IResult<&str, &str> { alphanumeric1(input) } assert_eq!(parser("21cZ%1"), Ok(("%1", "21cZ"))); assert_eq!(parser("&H2"), Err(Err::Error(Error::new("&H2", ErrorKind::AlphaNumeric)))); assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::AlphaNumeric)))); ``` -------------------------------- ### Using complete to ensure full input consumption Source: https://docs.rs/nom/latest/nom/combinator/fn.complete.html This example demonstrates how `complete` enforces that the inner parser consumes a specific amount of input. If the input is insufficient, it results in an error. ```rust use nom::bytes::streaming::take; use nom::combinator::complete; use nom::error::{Error, ErrorKind}; let mut parser = complete(take(5u8)); assert_eq!(parser.parse("abcdefg"), Ok(("fg", "abcde"))); assert_eq!(parser.parse("abcd"), Err(Err::Error(("abcd", ErrorKind::Complete)))); ``` -------------------------------- ### Take While Alphabetic Characters Source: https://docs.rs/nom/latest/nom/bytes/fn.take_while.html This example demonstrates how to use `take_while` with `is_alphabetic` to parse a sequence of alphabetic characters from a byte slice. It shows successful parsing, cases with no alphabetic characters at the start, and cases where the entire input is alphabetic. ```rust use nom::bytes::complete::take_while; use nom::character::is_alphabetic; fn alpha(s: &[u8]) -> IResult<&[u8], &[u8]> { take_while(is_alphabetic)(s) } assert_eq!(alpha(b"latin123"), Ok((&b"123"[..], &b"latin"[..]))); assert_eq!(alpha(b"12345"), Ok((&b"12345"[..], &b""[..]))); assert_eq!(alpha(b"latin"), Ok((&b""[..], &b"latin"[..]))); assert_eq!(alpha(b"" ), Ok((&b""[..], &b""[..]))); ``` -------------------------------- ### Function pair Source: https://docs.rs/nom/latest/nom/sequence/fn.pair.html Gets an object from the first parser, then gets another object from the second parser. ```APIDOC ## pair nom::sequence ### Summary ``` pub fn pair, F, G>( first: F, second: G, ) -> impl Parser where F: Parser, G: Parser, ``` ### Arguments * `first` The first parser to apply. * `second` The second parser to apply. ### Example ```rust use nom::sequence::pair; use nom::bytes::complete::tag; use nom::{error::ErrorKind, Err, Parser}; let mut parser = pair(tag("abc"), tag("efg")); assert_eq!(parser.parse("abcefg"), Ok(("", ("abc", "efg")))); assert_eq!(parser.parse("abcefghij"), Ok(("hij", ("abc", "efg")))); assert_eq!(parser.parse(""), Err(Err::Error(("", ErrorKind::Tag)))); assert_eq!(parser.parse("123"), Err(Err::Error(("123", ErrorKind::Tag)))); ``` ``` -------------------------------- ### Get Error Cause (Deprecated) Source: https://docs.rs/nom/latest/nom/enum.Err.html Deprecated method for getting the cause of the error. Replaced by Error::source. ```rust fn cause(&self) -> Option<&dyn Error> ``` -------------------------------- ### Fill a slice with parser results Source: https://docs.rs/nom/latest/nom/multi/fn.fill.html This example demonstrates how to use `fill` to parse a string and populate a fixed-size array with the results. It shows successful parsing and expected error cases. ```rust use nom::multi::fill; use nom::bytes::complete::tag; fn parser(s: &str) -> IResult<&str, [&str; 2]> { let mut buf = ["", ""]; let (rest, ()) = fill(tag("abc"), &mut buf).parse(s)?; Ok((rest, buf)) } assert_eq!(parser("abcabc"), Ok(("", ["abc", "abc"]))); assert_eq!(parser("abc123"), Err(Err::Error(Error::new("123", ErrorKind::Tag)))); assert_eq!(parser("123123"), Err(Err::Error(Error::new("123123", ErrorKind::Tag)))); assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::Tag)))); assert_eq!(parser("abcabcabc"), Ok(("abc", ["abc", "abc"]))); ``` -------------------------------- ### separated_pair Source: https://docs.rs/nom/latest/nom/sequence/index.html Gets an object from the first parser, then matches an object from the sep_parser and discards it, then gets another object from the second parser. ```APIDOC ## separated_pair ### Description Gets an object from the first parser, then matches an object from the sep_parser and discards it, then gets another object from the second parser. ### Function Signature ```rust fn separated_pair(first: P1, sep: Psep, second: P2) -> impl FnMut(I) -> IResult ``` ### Parameters - `first`: The first parser. - `sep`: The separator parser to match and discard. - `second`: The second parser. ``` -------------------------------- ### Using map_parser with take and digit1 Source: https://docs.rs/nom/latest/nom/combinator/fn.map_parser.html This example demonstrates how to use map_parser to first take a fixed number of characters and then parse those characters as digits. It shows successful parsing and cases where parsing fails due to insufficient input or incorrect format. ```rust use nom::character::complete::digit1; use nom::bytes::complete::take; use nom::combinator::map_parser; let mut parse = map_parser(take(5u8), digit1); assert_eq!(parse.parse("12345"), Ok(("", "12345"))); assert_eq!(parse.parse("123ab"), Ok(("", "123"))); assert_eq!(parse.parse("123"), Err(Err::Error(("123", ErrorKind::Eof)))); ``` -------------------------------- ### Get Error Description (Deprecated) Source: https://docs.rs/nom/latest/nom/enum.Err.html Deprecated method for getting a string description of the error. Use the Display implementation or to_string() instead. ```rust fn description(&self) -> &str ``` -------------------------------- ### Get Remaining Input Length - Rust Source: https://docs.rs/nom/latest/nom/combinator/fn.rest_len.html Use rest_len to get the length of the remaining input. This combinator does not consume any input. It returns the length as a usize. ```rust use nom::combinator::rest_len; use nom::error::ErrorKind; assert_eq!(rest_len::<_,(_, ErrorKind)>("abc"), Ok(("abc", 3))); assert_eq!(rest_len::<_,(_, ErrorKind)>(""), Ok(("", 0))); ``` -------------------------------- ### Combinator Methods for TakeUntil1 Source: https://docs.rs/nom/latest/nom/bytes/struct.TakeUntil1.html Provides documentation for combinator methods available on `TakeUntil1`, allowing for functional composition and transformation of parser results. ```APIDOC ### Combinator Methods #### fn map(self, g: G) -> Map where G: FnMut(Self::Output) -> O2, Self: Sized, Maps a function over the result of a parser #### fn map_res(self, g: G) -> MapRes where G: FnMut(Self::Output) -> Result, Self::Error: FromExternalError, Self: Sized, Applies a function returning a `Result` over the result of a parser. #### fn map_opt(self, g: G) -> MapOpt where G: FnMut(Self::Output) -> Option, Self: Sized, Applies a function returning an `Option` over the result of a parser. #### fn flat_map(self, g: G) -> FlatMap where G: FnMut(Self::Output) -> H, H: Parser, Self: Sized, Creates a second parser from the output of the first one, then apply over the rest of the input #### fn and_then(self, g: G) -> AndThen where G: Parser, Self: Sized, Applies a second parser over the output of the first one #### fn and(self, g: G) -> And where G: Parser, Self: Sized, Applies a second parser after the first one, return their results as a tuple #### fn or(self, g: G) -> Or where G: Parser, Self: Sized, Applies a second parser over the input if the first one failed #### fn into, E2: From>( self, ) -> Into where Self: Sized, automatically converts the parser’s output and error values to another type, as long as they implement the `From` trait ``` -------------------------------- ### alphanumeric1 Examples Source: https://docs.rs/nom/latest/nom/character/streaming/fn.alphanumeric1.html These examples demonstrate the behavior of alphanumeric1 with different inputs. It successfully parses alphanumeric strings, returns an error for non-alphanumeric characters, and indicates incomplete input when necessary. ```rust assert_eq!(alphanumeric1::<_, (_, ErrorKind)>("21cZ%1"), Ok(("%1", "21cZ"))); assert_eq!(alphanumeric1::<_, (_, ErrorKind)>("&H2"), Err(Err::Error(("&H2", ErrorKind::AlphaNumeric)))); assert_eq!(alphanumeric1::<_, (_, ErrorKind)>(""), Err(Err::Incomplete(Needed::new(1)))); ``` -------------------------------- ### take Source: https://docs.rs/nom/latest/nom/bytes/fn.take.html Returns an input slice containing the first N input elements (Input[..N]). For streaming inputs, if there are less than N elements, it returns `Err::Incomplete`. ```APIDOC ## take nom::bytes ### Summary ``` pub fn take>( count: C, ) -> impl Parser where I: Input, C: ToUsize, ``` ### Description Returns an input slice containing the first N input elements (Input[..N]). ## §Streaming Specific _Streaming version_ if the input has less than N elements, `take` will return a `Err::Incomplete(Needed::new(M))` where M is the number of additional bytes the parser would need to succeed. It is well defined for `&[u8]` as the number of elements is the byte size, but for types like `&str`, we cannot know how many bytes correspond for the next few chars, so the result will be `Err::Incomplete(Needed::Unknown)` ## §Example ``` use nom::bytes::streaming::take; fn take6(s: &str) -> IResult<&str, &str> { take(6usize)(s) } assert_eq!(take6("1234567"), Ok(("7", "123456"))); assert_eq!(take6("things"), Ok(("", "things"))); assert_eq!(take6("short"), Err(Err::Incomplete(Needed::Unknown))); ``` ``` -------------------------------- ### Match newline character Source: https://docs.rs/nom/latest/nom/character/complete/fn.newline.html Use this function to parse a newline character. It expects the input to start with '\n'. If the input is empty or starts with a different character (like '\r\n'), it will return an error. ```rust fn parser(input: &str) -> IResult<&str, char> { newline(input) } assert_eq!(parser("\nc"), Ok(("c", '\n'))); assert_eq!(parser("\r\nc"), Err(Err::Error(Error::new("\r\nc", ErrorKind::Char)))); assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::Char)))); ``` -------------------------------- ### take_till1 Example Source: https://docs.rs/nom/latest/nom/bytes/complete/fn.take_till1.html Demonstrates how to use `take_till1` to parse a string until a colon is encountered. It also shows error cases for empty input or when the predicate matches the first character. ```rust use nom::bytes::complete::take_till1; fn till_colon(s: &str) -> IResult<&str, &str> { take_till1(|c| c == ':')(s) } assert_eq!(till_colon("latin:123"), Ok((":123", "latin"))); assert_eq!(till_colon(":empty matched"), Err(Err::Error(Error::new(":empty matched", ErrorKind::TakeTill1)))); assert_eq!(till_colon("12345"), Ok(("", "12345"))); assert_eq!(till_colon(""), Err(Err::Error(Error::new("", ErrorKind::TakeTill1)))); ``` -------------------------------- ### type_id Source: https://docs.rs/nom/latest/nom/enum.Err.html Gets the `TypeId` of `self`. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters - `self` (*self*) - Description not available ``` -------------------------------- ### Combine two parsers with pair Source: https://docs.rs/nom/latest/nom/sequence/fn.pair.html This example demonstrates how to use `pair` to combine `tag` parsers. It shows successful parsing of the full input, partial input, and various error cases. ```rust use nom::sequence::pair; use nom::bytes::complete::tag; use nom::{error::ErrorKind, Err, Parser}; let mut parser = pair(tag("abc"), tag("efg")); assert_eq!(parser.parse("abcefg"), Ok(("", ("abc", "efg")))); assert_eq!(parser.parse("abcefghij"), Ok(("hij", ("abc", "efg")))); assert_eq!(parser.parse(""), Err(Err::Error(("", ErrorKind::Tag)))); assert_eq!(parser.parse("123"), Err(Err::Error(("123", ErrorKind::Tag)))); ``` -------------------------------- ### try_from Source: https://docs.rs/nom/latest/nom/enum.Err.html Performs the conversion. ```APIDOC ## fn try_from(value: U) -> Result>::Error> ### Description Performs the conversion. ### Method `try_from` ### Parameters - `value` (*U*) - Description not available ``` -------------------------------- ### nom::character::streaming::alpha0 Usage Examples Source: https://docs.rs/nom/latest/nom/character/streaming/fn.alpha0.html These examples demonstrate the usage of the streaming alpha0 parser. It correctly parses sequences of alphabetic characters and handles cases with leading non-alphabetic characters or empty input, returning Ok or Err(Err::Incomplete) as appropriate. ```rust assert_eq!(alpha0::<_, (_, ErrorKind)>("ab1c"), Ok(("1c", "ab"))); assert_eq!(alpha0::<_, (_, ErrorKind)>("1c"), Ok(("1c", ""))); assert_eq!(alpha0::<_, (_, ErrorKind)>(""), Err(Err::Incomplete(Needed::new(1)))); ``` -------------------------------- ### Example of using nom::bytes::escaped Source: https://docs.rs/nom/latest/nom/bytes/fn.escaped.html This example demonstrates how to use the `escaped` parser to parse a string containing digits, with backslash as the escape character and specific characters like '"', 'n', and '\' as escapable. It shows successful parsing of both normal digits and escaped sequences. ```rust use nom::bytes::streaming::escaped; use nom::character::streaming::one_of; fn esc(s: &str) -> IResult<&str, &str> { escaped(digit1, '\\', one_of("\"n\\"))(s) } assert_eq!(esc("123;"), Ok((";", "123"))); assert_eq!(esc("12\\\"34;"), Ok((";", "12\\\"34"))); ``` -------------------------------- ### Streaming take_until Example Source: https://docs.rs/nom/latest/nom/bytes/fn.take_until.html Demonstrates using `take_until` to parse a string until 'eof'. It shows successful parsing, incomplete parsing due to missing pattern, and parsing when the pattern is present multiple times. ```rust use nom::bytes::streaming::take_until; use nom::IResult; use nom::Err; use nom::Needed; fn until_eof(s: &str) -> IResult<&str, &str> { take_until("eof")(s) } assert_eq!(until_eof("hello, worldeof"), Ok(("eof", "hello, world"))); assert_eq!(until_eof("hello, world"), Err(Err::Incomplete(Needed::Unknown))); assert_eq!(until_eof("hello, worldeo"), Err(Err::Incomplete(Needed::Unknown))); assert_eq!(until_eof("1eof2eof"), Ok(("eof2eof", "1"))); ``` -------------------------------- ### take_while1 Example Source: https://docs.rs/nom/latest/nom/bytes/fn.take_while1.html Demonstrates how to use `take_while1` with a predicate function to parse alphabetic characters from a byte slice. It shows successful parsing, incomplete input, and a case where the pattern is not met. ```rust use nom::bytes::streaming::take_while1; use nom::character::is_alphabetic; fn alpha(s: &[u8]) -> IResult<&[u8], &[u8]> { take_while1(is_alphabetic)(s) } assert_eq!(alpha(b"latin123"), Ok((&b"123"[..], &b"latin"[..]))); assert_eq!(alpha(b"latin"), Err(Err::Incomplete(Needed::new(1)))); assert_eq!(alpha(b"12345"), Err(Err::Error(Error::new(&b"12345"[..], ErrorKind::TakeWhile1)))); ```