### Example Usage (Complete) Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/binary/fn.i16.html Examples demonstrating the usage of the i16 parser with complete input streams. ```APIDOC ## Example (Complete) ```rust use winnow::binary::i16; use winnow::prelude::*; // Assuming ModalResult and other necessary traits are here fn be_i16(input: &mut &[u8]) -> ModalResult { i16(winnow::binary::Endianness::Big).parse_next(input) }; assert_eq!(be_i16.parse_peek(&b"\x00\x03abcefg"[..]), Ok((&b"abcefg"[..], 0x0003))); assert!(be_i16.parse_peek(&b"\x01"[..]).is_err()); fn le_i16(input: &mut &[u8]) -> ModalResult { i16(winnow::binary::Endianness::Little).parse_next(input) }; assert_eq!(le_i16.parse_peek(&b"\x00\x03abcefg"[..]), Ok((&b"abcefg"[..], 0x0300))); assert!(le_i16.parse_peek(&b"\x01"[..]).is_err()); ``` ``` -------------------------------- ### Example Usage (Complete) Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/binary/fn.u64.html Examples demonstrating the usage of `u64` with `winnow::binary::Endianness::Big` and `winnow::binary::Endianness::Little` for complete parsing. ```APIDOC ## §Example ``` use winnow::binary::u64; fn be_u64(input: &mut &[u8]) -> ModalResult { u64(winnow::binary::Endianness::Big).parse_next(input) }; assert_eq!(be_u64.parse_peek(&b"\x00\x01\x02\x03\x04\x05\x06\x07abcefg"[..]), Ok((&b"abcefg"[..], 0x0001020304050607))); assert!(be_u64.parse_peek(&b"\x01"[..]).is_err()); fn le_u64(input: &mut &[u8]) -> ModalResult { u64(winnow::binary::Endianness::Little).parse_next(input) }; assert_eq!(le_u64.parse_peek(&b"\x00\x01\x02\x03\x04\x05\x06\x07abcefg"[..]), Ok((&b"abcefg"[..], 0x0706050403020100))); assert!(le_u64.parse_peek(&b"\x01"[..]).is_err()); ``` ``` -------------------------------- ### Example: Consuming 4 bits from the start Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/binary/bits/fn.take.html Shows consuming the first 4 bits from a bit stream. The offset increases to 4, and the returned value represents the consumed bits. ```rust assert_eq!(take::<_, usize, _, ContextError>(4usize).parse_peek(Bits(stream(&[0b00010010]), 0)), Ok((Bits(stream(&[0b00010010]), 4), 0b00000001))); ``` -------------------------------- ### Example Usage (Partial) Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/binary/fn.i16.html Examples demonstrating the usage of the i16 parser with partial input streams, showing incomplete data handling. ```APIDOC ## Example (Partial) ```rust use winnow::binary::i16; use winnow::error::{ErrMode, Needed}; use winnow::stream::Partial; use winnow::prelude::*; // Assuming ModalResult and other necessary traits are here fn be_i16(input: &mut Partial<&[u8]>) -> ModalResult { i16(winnow::binary::Endianness::Big).parse_next(input) }; assert_eq!(be_i16.parse_peek(Partial::new(&b"\x00\x03abcefg"[..])), Ok((Partial::new(&b"abcefg"[..]), 0x0003))); assert_eq!(be_i16.parse_peek(Partial::new(&b"\x01"[..])), Err(ErrMode::Incomplete(Needed::new(1)))); fn le_i16(input: &mut Partial<&[u8]>) -> ModalResult { i16(winnow::binary::Endianness::Little).parse_next(input) }; assert_eq!(le_i16.parse_peek(Partial::new(&b"\x00\x03abcefg"[..])), Ok((Partial::new(&b"abcefg"[..]), 0x0300))); assert_eq!(le_i16.parse_peek(Partial::new(&b"\x01"[..])), Err(ErrMode::Incomplete(Needed::new(1)))); ``` ``` -------------------------------- ### Include Arithmetic Parser Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/_topic/arithmetic.rs.html Includes the Rust code for the arithmetic parser example. Ensure the example file exists at the specified path. ```rust #![doc = include_str!("../../examples/arithmetic/parser.rs")] ``` -------------------------------- ### HTTP Parser Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/_topic/http.rs.html Includes an example parser for HTTP, demonstrating Winnow's capabilities. This code is directly embedded from an external file. ```rust #![doc = include_str!("../../examples/http/parser.rs")] ``` -------------------------------- ### Example Usage Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/binary/fn.u128.html Examples demonstrating how to use the `u128` parser for both big-endian and little-endian parsing with complete and partial input modes. ```APIDOC ## §Example ```rust use winnow::binary::u128; fn be_u128(input: &mut &[u8]) -> ModalResult { u128(winnow::binary::Endianness::Big).parse_next(input) }; assert_eq!(be_u128.parse_peek(&b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07abcefg"[..]), Ok((&b"abcefg"[..], 0x00010203040506070001020304050607))); assert!(be_u128.parse_peek(&b"\x01"[..]).is_err()); fn le_u128(input: &mut &[u8]) -> ModalResult { u128(winnow::binary::Endianness::Little).parse_next(input) }; assert_eq!(le_u128.parse_peek(&b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07abcefg"[..]), Ok((&b"abcefg"[..], 0x07060504030201000706050403020100))); assert!(le_u128.parse_peek(&b"\x01"[..]).is_err()); ``` ```rust use winnow::binary::u128; fn be_u128(input: &mut Partial<&[u8]>) -> ModalResult { u128(winnow::binary::Endianness::Big).parse_next(input) }; assert_eq!(be_u128.parse_peek(Partial::new(&b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07abcefg"[..])), Ok((Partial::new(&b"abcefg"[..]), 0x00010203040506070001020304050607))); assert_eq!(be_u128.parse_peek(Partial::new(&b"\x01"[..])), Err(ErrMode::Incomplete(Needed::new(15)))); fn le_u128(input: &mut Partial<&[u8]>) -> ModalResult { u128(winnow::binary::Endianness::Little).parse_next(input) }; assert_eq!(le_u128.parse_peek(Partial::new(&b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07abcefg"[..])), Ok((Partial::new(&b"abcefg"[..]), 0x07060504030201000706050403020100))); assert_eq!(le_u128.parse_peek(Partial::new(&b"\x01"[..])), Err(ErrMode::Incomplete(Needed::new(15)))); ``` ``` -------------------------------- ### Example Usage of pattern Parser Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/binary/bits/fn.pattern.html Demonstrates how to use the `pattern` parser to compare specific bit patterns within a byte stream. It includes setup for a bit stream and assertions for matching and non-matching cases. ```rust use winnow::binary::bits::pattern; type Stream<'i> = &'i Bytes; fn stream(b: &[u8]) -> Stream<'_> { Bytes::new(b) } /// Compare the lowest `count` bits of `input` against the lowest `count` bits of `pattern`. /// Return Ok and the matching section of `input` if there's a match. /// Return Err if there's no match. fn parser(bits: u8, count: u8, input: &mut Bits>) -> ModalResult { pattern(bits, count).parse_next(input) } // The lowest 4 bits of 0b00001111 match the lowest 4 bits of 0b11111111. assert_eq!( pattern::<_, usize, _, ContextError>(0b0000_1111, 4usize).parse_peek(Bits(stream(&[0b1111_1111]), 0)), Ok((Bits(stream(&[0b1111_1111]), 4), 0b0000_1111)) ); // The lowest bit of 0b00001111 matches the lowest bit of 0b11111111 (both are 1). assert_eq!( pattern::<_, usize, _, ContextError>(0b00000001, 1usize).parse_peek(Bits(stream(&[0b11111111]), 0)), Ok((Bits(stream(&[0b11111111]), 1), 0b00000001)) ); // The lowest 2 bits of 0b11111111 and 0b00000001 are different. assert!(pattern::<_, usize, _, ContextError>(0b000000_01, 2usize).parse_peek(Bits(stream(&[0b111111_11]), 0)).is_err()); // The lowest 8 bits of 0b11111111 and 0b11111110 are different. assert!(pattern::<_, usize, _, ContextError>(0b11111110, 8usize).parse_peek(Bits(stream(&[0b11111111]), 0)).is_err()); ``` -------------------------------- ### Example CSS Parser Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/lib.rs.html This snippet demonstrates a basic CSS parser example. It requires the 'alloc' and 'parser' features to be enabled. ```rust # #[cfg(all(feature = "alloc", feature = "parser"))] { #![doc = include_str!("../examples/css/parser.rs")] # } ``` -------------------------------- ### multispace0 Example Usage Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/fn.multispace0.html Examples demonstrating how to use the multispace0 function with different input scenarios. ```APIDOC ## §Example ```rust fn parser<'s>(input: &mut &'s str) -> ModalResult<&'s str> { multispace0.parse_next(input) } assert_eq!(parser.parse_peek(" \t\n\r21c"), Ok(("21c", " \t\n\r"))); assert_eq!(parser.parse_peek("Z21c"), Ok(("Z21c", ""))); assert_eq!(parser.parse_peek(""), Ok(("", ""))); ``` ```rust assert_eq!(multispace0::<_, ErrMode>.parse_peek(Partial::new(" \t\n\r21c")), Ok((Partial::new("21c"), " \t\n\r"))); assert_eq!(multispace0::<_, ErrMode>.parse_peek(Partial::new("Z21c")), Ok((Partial::new("Z21c"), ""))); assert_eq!(multispace0::<_, ErrMode>.parse_peek(Partial::new("")), Err(ErrMode::Incomplete(Needed::new(1)))); ``` ``` -------------------------------- ### Example Usage with &str (Full Stream) Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/token/fn.take_till.html Example demonstrating the usage of take_till with a `&str` stream where the stream is not partial. ```APIDOC ## §Example ```rust use winnow::token::take_till; fn till_colon<'i>(s: &mut &'i str) -> ModalResult<&'i str> { take_till(0.., |c| c == ':').parse_next(s) } assert_eq!(till_colon.parse_peek("latin:123"), Ok((":123", "latin"))); assert_eq!(till_colon.parse_peek(":empty matched"), Ok((":empty matched", ""))); //allowed assert_eq!(till_colon.parse_peek("12345"), Ok(("", "12345"))); assert_eq!(till_colon.parse_peek(""), Ok(("", ""))); ``` ``` -------------------------------- ### Example Usage (Partial) Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/binary/fn.u64.html Examples demonstrating the usage of `u64` with `winnow::binary::Endianness::Big` and `winnow::binary::Endianness::Little` for partial parsing, including handling incomplete input. ```APIDOC ``` use winnow::binary::u64; fn be_u64(input: &mut Partial<&[u8]>) -> ModalResult { u64(winnow::binary::Endianness::Big).parse_next(input) }; assert_eq!(be_u64.parse_peek(Partial::new(&b"\x00\x01\x02\x03\x04\x05\x06\x07abcefg"[..])), Ok((Partial::new(&b"abcefg"[..]), 0x0001020304050607))); assert_eq!(be_u64.parse_peek(Partial::new(&b"\x01"[..])), Err(ErrMode::Incomplete(Needed::new(7)))); fn le_u64(input: &mut Partial<&[u8]>) -> ModalResult { u64(winnow::binary::Endianness::Little).parse_next(input) }; assert_eq!(le_u64.parse_peek(Partial::new(&b"\x00\x01\x02\x03\x04\x05\x06\x07abcefg"[..])), Ok((Partial::new(&b"abcefg"[..]), 0x0706050403020100))); assert_eq!(le_u64.parse_peek(Partial::new(&b"\x01"[..])), Err(ErrMode::Incomplete(Needed::new(7)))); ``` ``` -------------------------------- ### INI Parser Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/_topic/ini.rs.html Includes a complete example of an INI parser implemented using Winnow. This can be used as a reference for parsing INI-formatted data. ```rust #![doc = include_str!("../../examples/ini/parser.rs")] ``` -------------------------------- ### Example Usage with &str (Partial Stream) Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/token/fn.take_till.html Example demonstrating the usage of take_till with a `&str` stream where the stream is partial, showing incomplete results. ```APIDOC ```rust use winnow::token::take_till; fn till_colon<'i>(s: &mut Partial<&'i str>) -> ModalResult<&'i str> { take_till(0.., |c| c == ':').parse_next(s) } assert_eq!(till_colon.parse_peek(Partial::new("latin:123")), Ok((Partial::new(":123"), "latin"))); assert_eq!(till_colon.parse_peek(Partial::new(":empty matched")), Ok((Partial::new(":empty matched"), ""))); //allowed assert_eq!(till_colon.parse_peek(Partial::new("12345")), Err(ErrMode::Incomplete(Needed::new(1)))); assert_eq!(till_colon.parse_peek(Partial::new("")), Err(ErrMode::Incomplete(Needed::new(1)))); ``` ``` -------------------------------- ### CSS Parser Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/_topic/fromstr.rs.html This example demonstrates how to use Winnow to implement a parser for CSS properties, showcasing the library's capabilities for string parsing and implementing the `FromStr` trait. ```rust #![doc = include_str!("../../examples/css/parser.rs")] ``` -------------------------------- ### Range Construction Examples Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct.Range.html Demonstrates various ways to construct a Range using different range syntaxes with the `repeat` combinator. These examples show how to specify fixed counts, open-ended ranges, and specific start/end points. ```rust let parser: Vec<_> = repeat(5, inner).parse_next(input).unwrap(); ``` ```rust let parser: Vec<_> = repeat(.., inner).parse_next(input).unwrap(); ``` ```rust let parser: Vec<_> = repeat(1.., inner).parse_next(input).unwrap(); ``` ```rust let parser: Vec<_> = repeat(5..8, inner).parse_next(input).unwrap(); ``` ```rust let parser: Vec<_> = repeat(5..=8, inner).parse_next(input).unwrap(); ``` -------------------------------- ### Expression Parsing Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/combinator/expression.rs.html Example demonstrating how to use expression combinators with prefix and infix operators for parsing arithmetic expressions. ```APIDOC ## Expression Parsing Example ### Description This example shows how to construct an expression parser using `expression()`, defining prefix and infix operators with their respective binding powers and folding functions. ### Code ```rust use crate::combinator::expression; use crate::token::any; use crate::dispatch; use crate::combinator::fail; use crate::error::ContextError; use crate::Parser; use crate::Stream; fn parser<'i>() -> impl Parser<&'i str, i32, ContextError> { move |i: &mut &str| { use Infix::*; expression(digit1.parse_to::()) .current_precedence_level(0) .prefix(dispatch! {any; '+' => Prefix(12, |_, a| Ok(a)), '-' => Prefix(12, |_, a: i32| Ok(-a)), _ => fail }) .infix(dispatch! {any; '+' => Left(5, |_, a, b| Ok(a + b)), '-' => Left(5, |_, a, b| Ok(a - b)), '*' => Left(7, |_, a, b| Ok(a * b)), }) .parse_next(i) } } ``` ``` -------------------------------- ### multispace1 parser example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/fn.multispace1.html Demonstrates how to use `multispace1` with a `&str` stream in a complete parsing context. It shows successful parsing of leading whitespace and expected errors for non-whitespace starting input or empty input. ```rust fn parser<'s>(input: &mut &'s str) -> ModalResult<&'s str> { multispace1.parse_next(input) } assert_eq!(parser.parse_peek(" 21c"), Ok(("21c", " "))); assert!(parser.parse_peek("H2").is_err()); assert!(parser.parse_peek("").is_err()); ``` -------------------------------- ### JSON Parser Dispatch Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/_topic/json.rs.html Illustrates how to dispatch to different JSON parsers based on input. This example is ignored by default and intended for documentation purposes. ```rust #![doc = include_str!("../../examples/json/parser_dispatch.rs")] ``` -------------------------------- ### length_take Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/binary/fn.length_take.html Demonstrates how to use `length_take` with `be_u16` to parse a length-prefixed byte slice. The example shows successful parsing and handling of incomplete data. ```rust use winnow::Bytes; use winnow::binary::be_u16; use winnow::binary::length_take; type Stream<'i> = Partial<&'i Bytes>; fn stream(b: &[u8]) -> Stream<'_> { Partial::new(Bytes::new(b)) } fn parser<'i>(s: &mut Stream<'i>) -> ModalResult<&'i [u8]> { length_take(be_u16).parse_next(s) } assert_eq!(parser.parse_peek(stream(b"\x00\x03abcefg")), Ok((stream(&b"efg"[..]), &b"abc"[..]))); assert_eq!(parser.parse_peek(stream(b"\x00\x03a")), Err(ErrMode::Incomplete(Needed::new(2)))); ``` -------------------------------- ### Caseless<&str> Parser Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/struct.Caseless.html Demonstrates how to use the Caseless struct with string slices for case-insensitive parsing. It shows examples of successful and failed parsing attempts. ```APIDOC ## §Example ``` 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()); ``` ``` -------------------------------- ### space0 Parsing Examples Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/fn.space0.html These examples demonstrate the behavior of `space0` with different input strings, including cases with leading spaces/tabs, no leading spaces, and empty input, showing both successful parses and incomplete errors. ```rust assert_eq!(space0::<_, ErrMode>.parse_peek(Partial::new(" \t21c")), Ok((Partial::new("21c"), " \t"))); ``` ```rust assert_eq!(space0::<_, ErrMode>.parse_peek(Partial::new("Z21c")), Ok((Partial::new("Z21c"), ""))); ``` ```rust assert_eq!(space0::<_, ErrMode>.parse_peek(Partial::new("")), Err(ErrMode::Incomplete(Needed::new(1)))); ``` -------------------------------- ### Example of using `empty` with `alt` Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/combinator/fn.empty.html Demonstrates how `empty` can be used as the last alternative in `alt` to provide a default success value. This specific example parses a sign character, defaulting to positive if no sign is present. ```rust use winnow::combinator::alt; use winnow::combinator::empty; fn sign(input: &mut &str) -> ModalResult { alt(( '-'.value(-1), '+'.value(1), empty.value(1) )).parse_next(input) } assert_eq!(sign.parse_peek("+10"), Ok(("10", 1))); assert_eq!(sign.parse_peek("-10"), Ok(("10", -1))); assert_eq!(sign.parse_peek("10"), Ok(("10", 1))); ``` -------------------------------- ### C-style Expression Parser Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/_topic/language/index.html This example demonstrates building an abstract syntax tree for C-style expressions using the `expression()` parser. It highlights the core `pratt_parser()` function and provides tests for input/output validation. Helper functions for identifiers and printing ASTs are also included. ```rust //! Main points of the `c_expression` example: //! //! 1. [`Expr`], representing the AST of C-style expressions //! 2. [`pratt_parser()`], the core parser. //! 3. The [`test`]s, which demonstrate the expected input/outputs. //! //! There is one [`parse_example()`] function in this file, but the //! associated test module for this example shows the other inputs/outputs. //! //! # Errata: //! - There is a helper parser, [`identifier()`] //! - Two print implementations: [`Expr::fmt_ast_with_indent()`] and [`Expr::fmt_delimited()`] //! - For operator precedence, `1` has a low binding power while `13` has a high binding power. //! //! ## Printing //! //! `fmt_delimited()` is essentially prefix-notation. //! //! A short visual about the differences in printing, for parsing `1 + 1`: //! //! `fmt_ast_with_indent()` = //! ~~~text //! ADD //! VAL 1 //! VAL 1 //! ~~~ //! //! `fmt_delimited()` = //! ~~~text //! (+ 1 1) //! ~~~ //! //! ## Precedences //! //! Values uses an *inverted form* of the [C language operator precedence](c-precedence). //! //! In our implementation, a precedence of `1` is a very low precedence compared //! to a value of `13`. //! //! In the linked C operator page, the table shows precedence in *descending precedence order*, //! so `1` is the highest precedence, while `13` is a low precedence. //! //! The precedence levels you have to choose for your grammar depend on the language's //! semantics. //! //! [c-precedence]: https://en.cppreference.com/w/c/language/operator_precedence.html //! //! ### Precedence Table //! //! An overview of the different operators for this C-style expression language. //! //! Note: this does not include the operands themselves, such as literals or //! parenthesized expressions like: `(x)` //! //! Legend: //! - Kind: one of Prefix, Postfix, or Infix //! - Example: input text example //! - Name: the [`Expr`] variant it corresponds to //! - Power: the binding power/precedence of the operator //! - Assoc: infix-only, represents the left/right associativity of an operator //! - Recursive: only "TRUE" if parsing the operand invokes the parser again //! //! | Kind | Example | Name | Power | Assoc | Recursive | //! |---------|------------|------------------|-------|---------|-----------| //! | Prefix | `++x` | PreIncr | 18 | | | //! | Prefix | `+x` | Positive (no-op) | 18 | | | //! | Prefix | `--x` | PreDecr | 18 | | | //! | Prefix | `-x` | Neg | 18 | | | //! | Prefix | `&x` | Addr | 18 | | | //! | Prefix | `*x` | Deref | 18 | | | //! | Prefix | `!x` | Not | 18 | | | //! | Prefix | `~x` | BitwiseNot | 18 | | | //! | Postfix | `x!` | Fac | 19 | | | //! | Postfix | `x?` | Ternary | 3 | | TRUE | //! | Postfix | `[x]` | Index | 20 | | TRUE | //! | Postfix | `(x)` | Function call | 20 | | TRUE | //! | Postfix | `x++` | PostIncr | 20 | | | //! | Postfix | `x--` | PostDecr | 20 | | | //! | Infix | `a ** b` | Pow | 28 | Right | | //! | Infix | `a * b` | Mul | 16 | Left | | //! | Infix | `a / b` | Div | 16 | Left | | //! | Infix | `a % b` | Rem | 16 | Left | | //! | Infix | `a + b` | Add | 14 | Left | | //! | Infix | `a -ne b` | NotEq | 10 | Neither | | //! | Infix | `a -eq b` | Eq | 10 | Neither | | //! | Infix | `a -gt b` | Greater | 12 | Neither | | //! | Infix | `a -ge b` | GreaterEq | 12 | Neither | | //! | Infix | `a -lt b` | Less | 12 | Neither | | //! | Infix | `a -le b` | LessEqual | 12 | Neither | | //! | Infix | `a->b` | ArrowOp | 20 | Left | | //! | Infix | `a - b` | Sub | 14 | Left | | //! | Infix | `a.b` | Dot | 20 | Left | | //! | Infix | `a && b` | And | 6 | Left | | //! | Infix | `a & b` | BitAnd | 12 | Left | | //! | Infix | `a ^ b` | BitXor | 8 | Left | | //! | Infix | `a == b` | Eq | 10 | Neither | | ``` -------------------------------- ### Example without cut_err Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/combinator/fn.cut_err.html Demonstrates the behavior of `alt` with recoverable errors, allowing backtracking. ```rust fn parser<'i>(input: &mut &'i str) -> ModalResult<&'i str> { alt(( preceded(one_of(['+', '-']), digit1), rest )).parse_next(input) } assert_eq!(parser.parse_peek("+10 ab"), Ok((" ab", "10"))); assert_eq!(parser.parse_peek("ab"), Ok(("", "ab"))); assert_eq!(parser.parse_peek("+"), Ok(("", "+"))); ``` -------------------------------- ### Get Current Token Start Offset Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct.LocatingSlice.html Retrieves the byte offset corresponding to the start of the current token within the input stream. ```rust fn current_token_start(&self) -> usize ``` -------------------------------- ### Get the start of the current token Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/stream/token.rs.html Retrieves the byte offset corresponding to the start of the current token. Requires the token type `T` to implement the `Location` trait. ```rust fn current_token_start(&self) -> Option { self.input.first().map(|t| t.current_token_start()) } ``` -------------------------------- ### Range `RangeBounds` Implementation Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct.Range.html Implements the `RangeBounds` trait for the Range struct, providing methods to get the start and end bounds of the range. ```rust fn start_bound(&self) -> Bound<&usize> ``` ```rust fn end_bound(&self) -> Bound<&usize> ``` -------------------------------- ### Location Implementation for TokenSlice Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/stream/token.rs.html Implements the Location trait for TokenSlice, providing methods to get the end of the previous token and the start of the current token. ```rust impl Location for TokenSlice<'_, T> where T: Location, { #[inline(always)] fn previous_token_end(&self) -> usize { self.previous_token_end() .or_else(|| self.current_token_start()) .unwrap_or(0) } #[inline(always)] fn current_token_start(&self) -> usize { self.current_token_start() .or_else(|| self.previous_token_end()) .unwrap_or(0) } } ``` -------------------------------- ### Example Usage (Complete Parser) Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/binary/fn.i8.html Demonstrates how to use the i8 function with a complete parser, showing successful parsing and error handling for insufficient input. ```APIDOC ## §Example ```rust use winnow::binary::i8; fn parser(s: &mut &[u8]) -> ModalResult { i8.parse_next(s) } assert_eq!(parser.parse_peek(&b"\x00\x03abcefg"[..]), Ok((&b"\x03abcefg"[..], 0x00))); assert!(parser.parse_peek(&b""[..]).is_err()); ``` ``` -------------------------------- ### Example Usage (Partial Parser) Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/binary/fn.i8.html Demonstrates how to use the i8 function with a partial parser, showing successful parsing and handling of incomplete input. ```APIDOC ```rust use winnow::binary::i8; fn parser(s: &mut Partial<&[u8]>) -> ModalResult { i8.parse_next(s) } assert_eq!(parser.parse_peek(Partial::new(&b"\x00\x03abcefg"[..])), Ok((Partial::new(&b"\x03abcefg"[..]), 0x00))); assert_eq!(parser.parse_peek(Partial::new(&b""[..])), Err(ErrMode::Incomplete(Needed::new(1)))); ``` ``` -------------------------------- ### Range Bounds Implementation Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct.Range.html Implements the RangeBounds trait for Range, providing methods to get start and end bounds, check for containment, and determine if the range is empty. ```APIDOC ### impl RangeBounds for Range #### fn start_bound(&self) -> Bound<&usize> Start index bound. Read more #### fn end_bound(&self) -> Bound<&usize> End index bound. Read more #### fn contains(&self, item: &U) -> bool where T: PartialOrd, U: PartialOrd + ?Sized, Returns `true` if `item` is contained in the range. Read more #### fn is_empty(&self) -> bool where T: PartialOrd, Returns `true` if the range contains no items. One-sided ranges (`RangeFrom`, etc) always return `false`. ``` -------------------------------- ### Parse escaped characters with Partial input Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/fn.escaped.html This example shows how to use `escaped` with a `Partial` input type, which is useful for incremental parsing. The setup is similar to the string slice example, handling normal characters, the escape character '\', and specific escaped sequences. The output reflects the remaining `Partial` input after parsing. ```rust use winnow::token::literal; use winnow::ascii::escaped; use winnow::ascii::alpha1; use winnow::combinator::alt; fn parser<'s>(input: &mut Partial<&'s str>) -> ModalResult { escaped( alpha1, '\', alt(( "\\".value("\\"), "\"".value("\""), "n".value("\n"), )) ).parse_next(input) } assert_eq!(parser.parse_peek(Partial::new("ab\"cd"")), Ok((Partial::new("""), String::from("ab\"cd")))); ``` -------------------------------- ### Example Usage of take with Partial Mode Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/token/fn.take.html Shows how to use the `take` function with a `Partial` input type, demonstrating its behavior when the input is incomplete and the exact number of needed elements is unknown. ```rust use winnow::token::take; fn take6<'i>(s: &mut Partial<&'i str>) -> ModalResult<&'i str> { take(6usize).parse_next(s) } assert_eq!(take6.parse_peek(Partial::new("1234567")), Ok((Partial::new("7"), "123456"))); assert_eq!(take6.parse_peek(Partial::new("things")), Ok((Partial::new(""), "things"))); // `Unknown` as we don't know the number of bytes that `count` corresponds to assert_eq!(take6.parse_peek(Partial::new("short")), Err(ErrMode::Incomplete(Needed::Unknown))); ``` -------------------------------- ### Parse a literal string Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/token/fn.literal.html This example shows how to parse a literal string. It returns the matched string if successful, or an error if the input does not start with the literal. It works with both complete and partial input streams. ```rust fn parser<'i>(s: &mut &'i str) -> ModalResult<&'i str> { "Hello".parse_next(s) } assert_eq!(parser.parse_peek("Hello, World!"), Ok((", World!", "Hello"))); assert!(parser.parse_peek("Something").is_err()); assert!(parser.parse_peek("").is_err()); ``` ```rust fn parser<'i>(s: &mut Partial<&'i str>) -> ModalResult<&'i str> { "Hello".parse_next(s) } assert_eq!(parser.parse_peek(Partial::new("Hello, World!")), Ok((Partial::new(", World!"), "Hello"))); assert!(parser.parse_peek(Partial::new("Something")).is_err()); assert!(parser.parse_peek(Partial::new("S")).is_err()); assert_eq!(parser.parse_peek(Partial::new("H")), Err(ErrMode::Incomplete(Needed::Unknown))); ``` -------------------------------- ### Example: Consuming 4 bits with an existing offset Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/binary/bits/fn.take.html Illustrates consuming 4 bits when the stream already has an offset of 4. The offset is updated to the start of the next byte, and the correct bits are returned. ```rust assert_eq!(take::<_, usize, _, ContextError>(4usize).parse_peek(Bits(stream(&[0b00010010]), 4)), Ok((Bits(stream(&[]), 0), 0b00000010))); ``` -------------------------------- ### Example Usage of space1 with &str Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/fn.space1.html Demonstrates parsing a string slice with `space1`. It successfully parses leading spaces and tabs, fails if the input starts with a non-space character, and fails on empty input. ```rust fn parser<'s>(input: &mut &'s str) -> ModalResult<&'s str> { space1.parse_next(input) } assert_eq!(parser.parse_peek(" 21c"), Ok(("21c", " "))); assert!(parser.parse_peek("H2").is_err()); assert!(parser.parse_peek("").is_err()); ``` -------------------------------- ### Parse line ending from &str Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/ascii/fn.line_ending.html This example demonstrates parsing a line ending from a string slice. It uses `parse_next` for consumption and `parse_peek` for non-consuming checks. Note that `parse_peek` returns an error if the input does not start with a line ending. ```rust fn parser<'s>(input: &mut &'s str) -> ModalResult<&'s str> { line_ending.parse_next(input) } assert_eq!(parser.parse_peek("\r\nc"), Ok(("c", "\r\n"))); assert!(parser.parse_peek("ab\r\nc").is_err()); assert!(parser.parse_peek("").is_err()); ``` -------------------------------- ### Iterate subslices separated by elements matching a predicate (rsplit) Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct.TokenSlice.html Use `rsplit` to get an iterator over subslices separated by elements that match the predicate, starting from the end of the slice. The matched element is not included. An empty slice is returned if the first or last element matches the predicate. ```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); ``` -------------------------------- ### Calculate Offset from Start of Slice Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/stream/mod.rs.html Calculates the byte offset of a slice relative to a starting slice. Asserts that the start slice is before or at the same position as the current slice. ```rust impl Offset for &[T] { #[inline] fn offset_from(&self, start: &Self) -> usize { let fst = (*start).as_ptr(); let snd = (*self).as_ptr(); debug_assert!( fst <= snd, "`Offset::offset_from({snd:?}, {fst:?})` only accepts slices of `self`" ); (snd as usize - fst as usize) / core::mem::size_of::() } } ``` -------------------------------- ### Preload prelude for parsing Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/lib.rs.html This example shows how to use the prelude for parsing. It imports necessary traits and types for parsing operations, including `StreamIsPartial`, `Parser`, and `ModalResult`. ```rust # #[cfg(feature = "ascii")] { use winnow::prelude::*; fn parse_data(input: &mut &str) -> ModalResult { // ... # winnow::ascii::dec_uint(input) } fn main() { let result = parse_data.parse("100"); assert_eq!(result, Ok(100)); } # } ``` -------------------------------- ### Example usage of `take` for bit parsing Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/binary/bits/mod.rs.html Demonstrates consuming varying numbers of bits from a byte stream using the `take` parser. Shows how to handle zero bits, partial byte consumption, and cases where insufficient bits are available. ```rust use winnow::prelude::*; use winnow::Bytes; use winnow::error::ContextError; use winnow::binary::bits::{Bits, take}; type Stream<'i> = &'i Bytes; fn stream(b: &[u8]) -> Stream<'_> { Bytes::new(b) } // Consumes 0 bits, returns 0 assert_eq!(take::<_, usize, _, ContextError>(0usize).parse_peek(Bits(stream(&[0b00010010]), 0)), Ok((Bits(stream(&[0b00010010]), 0), 0))); // Consumes 4 bits, returns their values and increase offset to 4 assert_eq!(take::<_, usize, _, ContextError>(4usize).parse_peek(Bits(stream(&[0b00010010]), 0)), Ok((Bits(stream(&[0b00010010]), 4), 0b00000001))); // Consumes 4 bits, offset is 4, returns their values and increase offset to 0 of next byte assert_eq!(take::<_, usize, _, ContextError>(4usize).parse_peek(Bits(stream(&[0b00010010]), 4)), Ok((Bits(stream(&[]), 0), 0b00000010))); // Tries to consume 12 bits but only 8 are available assert!(take::<_, usize, _, ContextError>(12usize).parse_peek(Bits(stream(&[0b00010010]), 0)).is_err()); ``` -------------------------------- ### Get Remaining Input Length Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/token/fn.rest_len.html Use `rest_len` to get the length of the remaining input. This does not consume any input. ```rust use winnow::token::rest_len; use winnow::error::ContextError; assert_eq!(rest_len::<_,ContextError>.parse_peek("abc"), Ok(("abc", 3))); assert_eq!(rest_len::<_,ContextError>.parse_peek(""), Ok(("", 0))); ``` -------------------------------- ### Example Usage of `alt` Combinator Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/combinator/branch.rs.html Demonstrates how to use `alt` with `alpha1` and `digit1` parsers. Shows cases where the first parser succeeds, the second parser succeeds after the first fails, and when both fail. ```rust # #[cfg(feature = "ascii")] { # use winnow::{error::ErrMode, error::Needed}; # use winnow::prelude::*; use winnow::ascii::{alpha1, digit1}; use winnow::combinator::alt; fn parser<'i>(input: &mut &'i str) -> ModalResult<&'i str> { alt((alpha1, digit1)).parse_next(input) }; // the first parser, alpha1, takes the input assert_eq!(parser.parse_peek("abc"), Ok(("", "abc"))); // the first parser returns an error, so alt tries the second one assert_eq!(parser.parse_peek("123456"), Ok(("", "123456"))); // both parsers failed, and with the default error type, alt will return the last error assert!(parser.parse_peek(" ").is_err()); # } ``` -------------------------------- ### Stateful Example Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/stream/struct.Stateful.html Demonstrates how to use the Stateful struct with a custom state to track parser calls. ```APIDOC ## Example ```rust #[derive(Debug)] struct State<'s>(&'s mut u32); impl<'s> State<'s> { fn count(&mut self) { *self.0 += 1; } } type Stream<'is> = Stateful<&'is str, State<'is>>; fn word<'s>(i: &mut Stream<'s>) -> ModalResult<&'s str> { i.state.count(); alpha1.parse_next(i) } let data = "Hello"; let mut state = 0; let input = Stream { input: data, state: State(&mut state) }; let output = word.parse(input).unwrap(); assert_eq!(state, 1); ``` ``` -------------------------------- ### Reset TokenSlice stream to the start Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/src/winnow/stream/token.rs.html Resets the stream to the beginning of the input. Useful for formats where addresses are relative to the start. ```rust pub fn reset_to_start(&mut self) { let start = self.initial.checkpoint(); self.input.reset(&start); } ``` -------------------------------- ### Example Usage of take with &str (Complete Mode) Source: https://docs.rs/winnow/latest/x86_64-pc-windows-msvc/winnow/token/fn.take.html Demonstrates how to use the `take` function to parse a fixed number of characters from a string slice in complete parsing mode. It shows successful parses and error cases for insufficient input. ```rust use winnow::token::take; fn take6<'i>(s: &mut &'i str) -> ModalResult<&'i str> { take(6usize).parse_next(s) } assert_eq!(take6.parse_peek("1234567"), Ok(("7", "123456"))); assert_eq!(take6.parse_peek("things"), Ok(("", "things"))); assert!(take6.parse_peek("short").is_err()); assert!(take6.parse_peek("").is_err()); ```