### Winnow Re-export Example in Rust Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_tutorial/chapter_0/index Shows how winnow re-exports modules and items. This example demonstrates re-exporting the 'chapter_1' module as 'next' and the '_tutorial' module as 'table_of_contents'. ```Rust pub use super::chapter_1 as next; pub use crate::_tutorial as table_of_contents; ``` -------------------------------- ### Rust ok() Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/error/type Demonstrates the ok() method, which converts a Result into an Option, discarding the error if present. Examples show conversion for both Ok and Err variants. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### Rust is_ok() Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/error/type Illustrates the use of the is_ok() method, which returns true if the Result is Ok and false otherwise. Examples show checking both Ok and Err variants. ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` -------------------------------- ### Rust is_ok_and() Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/error/type Demonstrates the is_ok_and() method, which checks if a Result is Ok and if the contained value satisfies a given predicate. Examples cover Ok values matching and not matching the predicate, and Err values. ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Caseless Parser Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/struct Demonstrates the usage of the `Caseless` parser for case-insensitive matching of byte slices. It shows how to use `alt` with `Caseless` and `take`. ```Rust use winnow::ascii::Caseless; fn parser<'s>(s: &mut &'s [u8]) -> ModalResult<&'s [u8]> { alt((Caseless(b"hello"), take(5usize))).parse_next(s) } assert_eq!(parser.parse_peek(&b"Hello, World!"[..]), Ok((&b", World!"[..], &b"Hello"[..]))); assert_eq!(parser.parse_peek(&b"hello, World!"[..]), Ok((&b", World!"[..], &b"hello"[..]))); assert_eq!(parser.parse_peek(&b"HeLlo, World!"[..]), Ok((&b", World!"[..], &b"HeLlo"[..]))); assert_eq!(parser.parse_peek(&b"Something"[..]), Ok((&b"hing"[..], &b"Somet"[..]))); assert!(parser.parse_peek(&b"Some"[..]).is_err()); assert!(parser.parse_peek(&b""[..]).is_err()); ``` -------------------------------- ### Rust Slice as_rchunks Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct Demonstrates the `as_rchunks` method, which splits a slice into chunks starting from the end, returning the remainder and the chunks. ```Rust let slice = ['l', 'o', 'r', 'e', 'm']; let (remainder, chunks) = slice.as_rchunks(); assert_eq!(remainder, &['l']); assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]); ``` -------------------------------- ### Rust as_ref() Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/error/type Illustrates the as_ref() method, which converts a reference to a Result (&Result) into a Result containing references (&Result<&T, &E>). Examples show usage with Ok and Err variants. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Rust Slice array_windows Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct Provides an example of using the nightly-only `array_windows` method to create an iterator over overlapping windows of a specified size within a slice. ```Rust #![feature(array_windows)] let slice = [0, 1, 2, 3]; let mut iter = slice.array_windows(); assert_eq!(iter.next().unwrap(), &[0, 1]); assert_eq!(iter.next().unwrap(), &[1, 2]); assert_eq!(iter.next().unwrap(), &[2, 3]); assert!(iter.next().is_none()); ``` -------------------------------- ### Winnow Parsing Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/prelude/index Demonstrates a basic parsing scenario using the winnow crate's prelude. It defines a function `parse_data` to parse a u64 from a string slice and shows how to use the `parse` method in `main`. ```Rust use winnow::prelude::*; fn parse_data(input: &mut &str) -> ModalResult { // ... } fn main() { let result = parse_data.parse("100"); assert_eq!(result, Ok(100)); } ``` -------------------------------- ### Rust is_err() Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/error/type Shows the usage of the is_err() method, which returns true if the Result is Err and false if it is Ok. Examples include checking both Err and Ok variants. ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### Rust transpose() Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/error/type Demonstrates the usage of the transpose() method on a Result containing an Option, converting between Result, E> and Option>. ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result, SomeErr> = Ok(Some(5)); let y: Option> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### Rust Slice Chunks Exact Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct Demonstrates the use of `chunks_exact` to split a slice into exact-sized chunks, showing how to access the chunks and the remainder. ```Rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.chunks_exact(2); assert_eq!(iter.next().unwrap(), &['l', 'o']); assert_eq!(iter.next().unwrap(), &['r', 'e']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['m']); ``` -------------------------------- ### Example Usage of Caseless Parser in Rust Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/struct Demonstrates how to use the Caseless parser to match case-insensitive strings. It includes assertions to verify successful and failed parsing attempts with different input strings. ```Rust fn parser<'s>(s: &mut &'s str) -> ModalResult<&'s str> { Caseless("hello").parse_next(s) } assert_eq!(parser.parse_peek("Hello, World!"), Ok(((", World!", "Hello")))); assert_eq!(parser.parse_peek("hello, World!"), Ok(((", World!", "hello")))); assert_eq!(parser.parse_peek("HeLlo, World!"), Ok(((", World!", "HeLlo")))); assert!(parser.parse_peek("Some").is_err()); assert!(parser.parse_peek("").is_err()); ``` -------------------------------- ### Rust: Parsing with trace and mutable input reference Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_topic/nom/index Provides an example of a parser function that uses `trace` for debugging and operates on a mutable reference to the input stream (`&mut &str`). It demonstrates how to parse the input using `parse_next`. ```Rust fn foo(i: &mut &str) -> ModalResult { trace("foo", |i: &mut _| { // ... parser logic ... }).parse_next(i) } ``` -------------------------------- ### Rust err() Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/error/type Shows the err() method, which converts a Result into an Option, discarding the success value if present. Examples cover conversion for both Ok and Err variants. ```rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` -------------------------------- ### Rust: Case-Insensitive String Parsing Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/struct Demonstrates parsing a string case-insensitively using the `Caseless` type and the `alt` combinator. Includes assertions to verify correct parsing of various cases. ```Rust fn parser<'s>(s: &mut &'s str) -> ModalResult<&'s str> { alt((Caseless("hello"), take(5usize))).parse_next(s) } assert_eq!(parser.parse_peek("Hello, World!"), Ok(((", World!", "Hello")))); assert_eq!(parser.parse_peek("hello, World!"), Ok(((", World!", "hello")))); assert_eq!(parser.parse_peek("HeLlo, World!"), Ok(((", World!", "HeLlo")))); assert_eq!(parser.parse_peek("Something"), Ok(("hing", "Somet"))); assert!(parser.parse_peek("Some").is_err()); assert!(parser.parse_peek("").is_err()) ``` -------------------------------- ### Repeat Parsers Multiple Times (Rust) Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/combinator/index Demonstrates how to use `repeat` and `repeat_till` combinators to apply a parser a specified number of times or until a condition is met. Includes examples for basic repetition and repetition with a delimiter. ```Rust use winnow::combinator::repeat; use winnow::prelude::*; fn main() { let mut input = "ababc"; let parser = repeat(1..=3, "ab"); let result = parser.parse(&mut input); println!("Result: {:?}, Remaining Input: \"{}\"", result, input); } ``` ```Rust use winnow::combinator::repeat_till; use winnow::prelude::*; fn main() { let mut input = "ababefg"; let parser = repeat_till(0.., "ab", "ef"); let result = parser.parse(&mut input); println!("Result: {:?}, Remaining Input: \"{}\"", result, input); } ``` ```Rust use winnow::combinator::separated; use winnow::prelude::*; fn main() { let mut input = "ab,ab,ab."; let parser = separated(1..=3, "ab", ","); let result = parser.parse(&mut input); println!("Result: {:?}, Remaining Input: \"{}\"", result, input); } ``` -------------------------------- ### Winnow ASCII Caseless Parsing Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/struct Demonstrates using `winnow::ascii::Caseless` with `alt` and `take` for case-insensitive parsing of byte slices. It includes assertions to verify the parser's behavior with different input strings. ```rust use winnow::ascii::Caseless; fn parser<'s>(s: &mut &'s [u8]) -> ModalResult<&'s [u8]> { alt((Caseless(&"hello"[..]), take(5usize))).parse_next(s) } assert_eq!(parser.parse_peek(&b"Hello, World!"[..]), Ok((&b", World!"[..], &b"Hello"[..]))); assert_eq!(parser.parse_peek(&b"hello, World!"[..]), Ok((&b", World!"[..], &b"hello"[..]))); assert_eq!(parser.parse_peek(&b"HeLlo, World!"[..]), Ok((&b", World!"[..], &b"HeLlo"[..]))); assert_eq!(parser.parse_peek(&b"Something"[..]), Ok((&b"hing"[..], &b"Somet"[..]))); assert!(parser.parse_peek(&b"Some"[..]).is_err()); assert!(parser.parse_peek(&b""[..]).is_err()); ``` -------------------------------- ### Rust Slice as_chunks Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct Shows how to use `as_chunks` to divide a slice into a specified number of chunks and a remainder slice. It also demonstrates using `let`-`else` for slices expected to have an exact multiple of chunks. ```Rust let slice = ['l', 'o', 'r', 'e', 'm']; let (chunks, remainder) = slice.as_chunks(); assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]); assert_eq!(remainder, &['m']); ``` ```Rust let slice = ['R', 'u', 's', 't']; let (chunks, []) = slice.as_chunks::<2>() else { panic!("slice didn\'t have even length") }; assert_eq!(chunks, &[['R', 'u'], ['s', 't']]); ``` -------------------------------- ### Rust Result Iteration Examples Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/error/type Demonstrates how to use the iter() method on a Rust Result to iterate over its contained value if it's Ok, or yield nothing if it's Err. ```Rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Rust map() Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/error/type Shows the map() method, which applies a function to the `Ok` value of a Result, returning a new Result with the transformed value. If the original Result is `Err`, it is returned unchanged. ```rust let x: Result = Ok(2); assert_eq!(x.map(|x| x * 2), Ok(4)); let x: Result = Err("Error"); assert_eq!(x.map(|x| x * 2), Err("Error")); ``` -------------------------------- ### Get TokenSlice Location Offsets Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct Provides methods to get the offsets of the previous token's end and the current token's start. This is part of the Location trait implementation. ```rust fn previous_token_end(&self) -> usize Previous token’s end offset ``` ```rust fn current_token_start(&self) -> usize Current token’s start offset ``` -------------------------------- ### Fold Results of Repeated Parsers (Rust) Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/combinator/index Shows how to use the `fold` method on repeated parsers to aggregate results. This example demonstrates summing the integer outputs of a parser applied multiple times. ```Rust use winnow::combinator::repeat; use winnow::prelude::*; fn main() { let mut input = [1, 2, 3]; let parser = repeat(1..=2, be_u8); let folded_parser = parser.fold(|| 0, |acc, item| acc + item); let result = folded_parser.parse(&mut input); println!("Result: {:?}, Remaining Input: {:?}", result, input); } ``` -------------------------------- ### Winnow Tutorial - Chapter 7: Error Reporting Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_tutorial/chapter_7/index Provides documentation for Chapter 7 of the winnow tutorial, focusing on error reporting. This section covers context, error cuts, and error adaptation and rendering. It is available only with the 'unstable-doc' feature. ```Rust ## Module chapter_7 ### Sections * Chapter 7: Error Reporting * Context * Error Cuts * Error Adaptation and Rendering ``` -------------------------------- ### Rust Result Mutable Iteration Examples Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/error/type Shows how to use iter_mut() on a Rust Result to get a mutable reference to the contained value if it's Ok, allowing modification. ```Rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### Get Element Offset in Rust Slice Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct Returns the index of an element within a slice. Returns `None` if the element is not at the start of an element in the slice. This method uses pointer arithmetic and does not compare elements. It panics if `T` is zero-sized. ```Rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```Rust #![feature(substr_range)] let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Winnow Crate Dependencies Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_topic/json/index Lists the direct and development dependencies for the winnow crate version 0.7.13. Includes optional dependencies like 'anstream' and 'anstyle', and development dependencies such as 'criterion' and 'proptest'. ```Rust anstream ^0.3.2 anstyle ^1.0.1 is_terminal_polyfill ^1.48.0 memchr ^2.5 terminal_size ^0.4.0 annotate-snippets ^0.11.3 anyhow ^1.0.86 automod ^1.0.14 circular ^0.3.0 criterion ^0.5.1 lexopt ^0.3.0 proptest ^1.2.0 rustc-hash ^1.1.0 snapbox ^0.6.21 term-transcript ^0.2.0 ``` -------------------------------- ### Rust: Get Type ID Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct Gets the `TypeId` of `self`. This method is part of the `Any` trait implementation. ```Rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Rust: Get Type ID Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/struct Gets the `TypeId` of `self`. This is a standard method available through blanket implementations. ```Rust fn type_id(&self) -> TypeId ``` -------------------------------- ### winnow Use Cases Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_topic/why/index This describes scenarios where using winnow is particularly beneficial. It's recommended for prototyping parsers that might later become hand-written, for situations where the format evolves frequently, or when the grammar is too complex for manual implementation without dedicated parsing expertise. ```Rust /* This works well for: * Prototyping for what will be a hand-written parser * When you want to minimize the work to evolve your format * When you don’t have contributors focused solely on parsing and your grammar is large enough to be unwieldy to hand write. */ ``` -------------------------------- ### Get Byte Representation of Caseless Value in Rust Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/struct Provides a method to get the byte representation of a Caseless value. This is useful when working with ASCII case-insensitive byte slices. ```Rust pub fn as_bytes(&self) -> Caseless<&[u8]> ``` -------------------------------- ### Sequence Parsers with Tuple in Rust Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_tutorial/chapter_3/index Demonstrates sequencing two parsers, `parse_prefix` and `parse_digits`, using a tuple. The `parse_next` method is called on the tuple, executing the parsers sequentially and returning their results. This is a concise way to combine multiple parsing steps. ```Rust fn main() { let mut input = "0x1a2b Hello"; let (prefix, digits) = ( parse_prefix, parse_digits ).parse_next(&mut input).unwrap(); assert_eq!(prefix, "0x"); assert_eq!(digits, "1a2b"); assert_eq!(input, " Hello"); } ``` -------------------------------- ### Winnow Supported Platforms Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_tutorial/chapter_7/index Details the various platforms for which the winnow crate has been compiled and tested. This includes different Windows and Linux architectures, as well as macOS. ```Rust i686-pc-windows-msvc i686-unknown-linux-gnu x86_64-apple-darwin x86_64-pc-windows-msvc x86_64-unknown-linux-gnu ``` -------------------------------- ### Rust: Prefix-Based Dispatching with `dispatch` Macro Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_tutorial/chapter_3/index Uses the `dispatch` macro to parse based on a prefix of a specified length. It maps different prefixes to corresponding parsers, offering an efficient alternative to long `alt` chains when prefixes are unique. ```Rust use winnow::combinator::dispatch; use winnow::token::take; use winnow::combinator::fail; fn parse_digits<'s>(input: &mut &'s str) -> Result<&'s str> { dispatch!(take(2usize); "0b" => parse_bin_digits, "0o" => parse_oct_digits, "0d" => parse_dec_digits, "0x" => parse_hex_digits, _ => fail, ).parse_next(input) } ``` -------------------------------- ### Winnow Crate Dependencies Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_tutorial/chapter_7/index Lists the dependencies required for the winnow crate, categorized into normal, optional, and development dependencies. Some dependencies are specific to certain features. ```Rust anstream ^0.3.2 anstyle ^1.0.1 is_terminal_polyfill ^1.48.0 memchr ^2.5 terminal_size ^0.4.0 annotate-snippets ^0.11.3 anyhow ^1.0.86 automod ^1.0.14 circular ^0.3.0 criterion ^0.5.1 lexopt ^0.3.0 proptest ^1.2.0 rustc-hash ^1.1.0 snapbox ^0.6.21 term-transcript ^0.2.0 ``` -------------------------------- ### Iterator Combinator Example in Rust Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_tutorial/chapter_0/index Demonstrates the use of combinators with Rust's Iterator trait, similar to how winnow uses parser combinators. This example filters a vector of numbers to count the even ones. ```Rust let data = vec![1, 2, 3, 4, 5]; let even_count = data.iter() .copied() // combinator .filter(|d| d % 2 == 0) // combinator .count(); // combinator ``` -------------------------------- ### Winnow Choice Combinators Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/combinator/index Illustrates the use of choice combinators in winnow, which allow for trying multiple parsers and returning the result of the first successful one. This includes `alt`, `dispatch`, and `permutation`. ```Rust use winnow::combinator::alt; use winnow::combinator::permutation; // Example usage (assuming a parser context) // alt((literal("ab"), literal("cd"))).parse("cdef") -> Ok("cd") // permutation((literal("ab"), literal("cd"), take(1))).parse("cd12abc") -> Ok(("ab", "cd", "1")) ``` -------------------------------- ### Rust is_err_and() Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/error/type Illustrates the is_err_and() method, which checks if a Result is Err and if the contained error value satisfies a given predicate. Examples include checking Err values matching and not matching the predicate, and Ok values. ```rust use std::io::{Error, ErrorKind}; let x: Result = Err(Error::new(ErrorKind::NotFound, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true); let x: Result = Err(Error::new(ErrorKind::PermissionDenied, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Ok(123); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Err("ownership".to_string()); assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### When to Use Hand-written Parsers Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_topic/why/index This provides guidance on when the hand-written parser approach is most suitable. It suggests this method is effective for small, stable formats or for large formats where a dedicated team can focus on parsing development and maintenance, citing the complexity of maintaining such code. ```Rust /* This approach works well if: * Your format is small and is unlikely to change * Your format is large but you have people who can focus solely on parsing, like with large programming languages */ ``` -------------------------------- ### Rust: Sequential Alternatives with `alt` Combinator Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_tutorial/chapter_3/index Employs the `alt` combinator to define a sequence of alternative parsers. The `alt` combinator tries each parser in order until one succeeds, providing a concise way to handle if/else-if logic. ```Rust use winnow::combinator::alt; fn parse_digits<'s>(input: &mut &'s str) -> Result<(&'s str, &'s str)> { alt(( ("0b", parse_bin_digits), ("0o", parse_oct_digits), ("0d", parse_dec_digits), ("0x", parse_hex_digits), )).parse_next(input) } ``` -------------------------------- ### Parse One or More Alphabetic/Hex Tokens with Winnow Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/token/fn This example demonstrates parsing one or more alphabetic characters or hexadecimal characters using `take_while`. It includes examples with both string and byte slice inputs, and handles complete and partial input scenarios. ```Rust use winnow::token::take_while; use winnow::stream::AsChar; fn alpha<'i>(s: &mut &'i [u8]) -> ModalResult<&'i [u8]> { take_while(1.., AsChar::is_alpha).parse_next(s) } assert_eq!(alpha.parse_peek(b"latin123"), Ok((&b"123"[..], &b"latin"[..]))); assert_eq!(alpha.parse_peek(b"latin"), Ok((&b""[..], &b"latin"[..]))); assert!(alpha.parse_peek(b"12345").is_err()); fn hex<'i>(s: &mut &'i str) -> ModalResult<&'i str> { take_while(1.., ('0'..='9', 'A'..='F')).parse_next(s) } assert_eq!(hex.parse_peek("123 and voila"), Ok((" and voila", "123"))); assert_eq!(hex.parse_peek("DEADBEEF and others"), Ok((" and others", "DEADBEEF"))); assert_eq!(hex.parse_peek("BADBABEsomething"), Ok(("something", "BADBABE"))); assert_eq!(hex.parse_peek("D15EA5E"), Ok(("", "D15EA5E"))); assert!(hex.parse_peek("").is_err()); ``` ```Rust use winnow::token::take_while; use winnow::stream::AsChar; fn alpha<'i>(s: &mut Partial<&'i [u8]>) -> ModalResult<&'i [u8]> { take_while(1.., AsChar::is_alpha).parse_next(s) } assert_eq!(alpha.parse_peek(Partial::new(b"latin123")), Ok((Partial::new(&b"123"[..]), &b"latin"[..]))); assert_eq!(alpha.parse_peek(Partial::new(b"latin")), Err(ErrMode::Incomplete(Needed::new(1)))); assert!(alpha.parse_peek(Partial::new(b"12345")).is_err()); fn hex<'i>(s: &mut Partial<&'i str>) -> ModalResult<&'i str> { take_while(1.., ('0'..='9', 'A'..='F')).parse_next(s) } assert_eq!(hex.parse_peek(Partial::new("123 and voila")), Ok((Partial::new(" and voila"), "123"))); assert_eq!(hex.parse_peek(Partial::new("DEADBEEF and others")), Ok((Partial::new(" and others"), "DEADBEEF"))); assert_eq!(hex.parse_peek(Partial::new("BADBABEsomething")), Ok((Partial::new("something"), "BADBABE"))); assert_eq!(hex.parse_peek(Partial::new("D15EA5E")), Err(ErrMode::Incomplete(Needed::new(1)))); assert_eq!(hex.parse_peek(Partial::new("")), Err(ErrMode::Incomplete(Needed::new(1)))); ``` -------------------------------- ### Rust: Reverse Split Slice by Predicate Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct Splits a slice into subslices starting from the end and working backwards, based on a predicate. The delimiter elements are not included. Handles edge cases like delimiters at the start or end, resulting in empty subslices. ```rust let slice = [11, 22, 33, 0, 44, 55]; let mut iter = slice.rsplit(|num| *num == 0); assert_eq!(iter.next().unwrap(), &[44, 55]); assert_eq!(iter.next().unwrap(), &[11, 22, 33]); assert_eq!(iter.next(), None); ``` ```rust let v = &[0, 1, 1, 2, 3, 5, 8]; let mut it = v.rsplit(|n| *n % 2 == 0); assert_eq!(it.next().unwrap(), &[]); assert_eq!(it.next().unwrap(), &[3, 5]); assert_eq!(it.next().unwrap(), &[1, 1]); assert_eq!(it.next().unwrap(), &[]); assert_eq!(it.next(), None); ``` -------------------------------- ### winnow::ascii::take_escaped Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/fn Demonstrates the usage of `take_escaped` to parse digits followed by an escape character and specific escapable characters like quotes, 'n', or backslashes. The example shows how to parse a string with and without escaped characters, asserting the expected output. ```rust use winnow::ascii::take_escaped; use winnow::token::one_of; fn esc<'i>(input: &mut &'i str) -> winnow::combinator::ParseResult<&'i str> { take_escaped(winnow::combinator::digit1, '\\', one_of(['"', 'n', '\\'])).parse_next(input) } assert_eq!(esc.parse_peek("123;"), Ok((";", "123"))); assert_eq!(esc.parse_peek(r#"12\"34;"#), Ok((";", r#"12\"34"#))); ``` ```rust use winnow::ascii::take_escaped; use winnow::token::one_of; use winnow::stream::Partial; fn esc<'i>(input: &mut Partial<&'i str>) -> winnow::combinator::ParseResult<&'i str> { take_escaped(winnow::combinator::digit1, '\\', one_of(['"', 'n', '\\'])).parse_next(input) } assert_eq!(esc.parse_peek(Partial::new("123;")), Ok((Partial::new(";"), "123"))); assert_eq!(esc.parse_peek(Partial::new("12\\\"34;")), Ok((Partial::new(";"), "12\\\"34"))); ``` -------------------------------- ### Get Default TokenSlice Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct Returns the default value for a TokenSlice. This is part of the Default trait implementation. ```rust fn default() -> Self ``` -------------------------------- ### Get Slice Length Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct Returns the number of elements in the slice. This method is part of the Deref implementation. ```Rust pub fn len(&self) -> usize ``` -------------------------------- ### Get TokenSlice Length Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct Calculates the length of the input stream represented by the TokenSlice. This is part of the SliceLen trait implementation. ```rust fn slice_len(&self) -> usize Calculates the input length, as indicated by its name, and the name of the trait itself ``` -------------------------------- ### Winnow Supported Platforms Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_topic/json/index Details the target platforms for which the winnow crate is compiled and supported. This includes various configurations for Windows, Linux, and macOS. ```Rust i686-pc-windows-msvc i686-unknown-linux-gnu x86_64-apple-darwin x86_64-pc-windows-msvc x86_64-unknown-linux-gnu ``` -------------------------------- ### Rust Generic TypeId Method Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/error/enum Gets the `TypeId` of a generic type `T`. This is a fundamental method for runtime type identification. ```Rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Rust: Get Last Element of Slice Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct Retrieves a reference to the last element of a slice. Returns None if the slice is empty. ```Rust pub fn last(&self) -> Option<&T> Returns the last element of the slice, or `None` if it is empty. ``` let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` ```