konst::parsing

Struct Parser

Source
pub struct Parser<'a> { /* private fields */ }
Expand description

For parsing and traversing over strings in const contexts.

If you’re looking for functions to parse some type from an entire string (instead of only part of it), then you want to look in the module for that type, eg: primitive::parse_u64.

§Mutation

Because konst only requires Rust 1.65.0, in order to mutate a parser you must reassign the parser returned by its methods.
eg: parser = parser.trim_start();

To help make this more ergonomic for Result-returning methods, you can use these macros:

  • try_rebind: Like the ? operator, but also reassigns variables and declares new ones with the value in the Ok variant.

  • rebind_if_ok: Like an if let Ok, but also reassigns variables and declares new ones with the value in the Ok variant.

  • parser_method: Parses any of the string literal patterns using a supported Parser method.

§Examples

§Parsing a variable-length array

Parses a variable-length array, requires the length to appear before the array.

This example requires the “parsing_proc” feature (enabled by default) because it uses the parser_method macro.

use konst::{
    parsing::{Parser, ParseValueResult},
    for_range, parser_method, try_, unwrap_ctx,
};

// We need to parse the length into a separate const to use it as the length of the array.
const LEN_AND_PARSER: (usize, Parser<'_>) = {
    let input = "\
        6;
        up, 0, 90, down, left, right,
    ";
     
    let parser = Parser::new(input);
    let (len, parser) = unwrap_ctx!(parser.parse_usize());
    (len, unwrap_ctx!(parser.strip_prefix(';')))
};

const ANGLES: [Angle; LEN_AND_PARSER.0] =
    unwrap_ctx!(Angle::parse_array(LEN_AND_PARSER.1)).0;

fn main() {
    assert_eq!(
        ANGLES,
        [Angle::UP, Angle::UP, Angle::RIGHT, Angle::DOWN, Angle::LEFT, Angle::RIGHT]
    );
}



#[derive(Debug, PartialEq, Eq, Copy, Clone)]
struct Angle(u16);

impl Angle {
    pub const UP: Self = Self(0);
    pub const RIGHT: Self = Self(90);
    pub const DOWN: Self = Self(180);
    pub const LEFT: Self = Self(270);

    pub const fn new(n: u64) -> Angle {
        Angle((n % 360) as u16)
    }

    const fn parse_array<const LEN: usize>(
        mut parser: Parser<'_>
    ) -> ParseValueResult<'_, [Angle; LEN]> {
        let mut ret = [Angle::UP; LEN];
         
        for_range!{i in 0..LEN =>
            (ret[i], parser) = try_!(Angle::parse(parser.trim_start()));
             
            parser = parser.trim_start();
            if !parser.is_empty() {
                parser = try_!(parser.strip_prefix(','));
            }
        }
        Ok((ret, parser))
    }

    pub const fn parse(mut parser: Parser<'_>) -> ParseValueResult<'_, Angle> {
        // this doesn't use the `rebind_if_ok` macro because it returns early.
        if let Ok((angle, parser)) = parser.parse_u64() {
            return Ok((Self::new(angle), parser))
        }
         
        let angle = parser_method!{parser, strip_prefix;
            "up" => Self::UP,
            "right" => Self::RIGHT,
            "down" => Self::DOWN,
            "left" => Self::LEFT,
            _ => return Err(parser.into_other_error(&"could not parse Direction"))
        };
        Ok((angle, parser))
    }
}

Implementations§

Source§

impl<'a> Parser<'a>

Source

pub const fn new(string: &'a str) -> Self

Constructs a Parser from a string.

This parser start with a start_offset of 0, with_start_offset is preferable for parsing after the start of a string.

Source

pub const fn with_start_offset(string: &'a str, start_offset: usize) -> Self

Constructs a Parser from string which is at start_offset inside some other string.

§Example
use konst::parsing::{ErrorKind, Parser};

// indices
//  0   4   8
//  |   |   |
// "foo bar baz"
let substr = konst::string::str_from("foo bar baz", 4);

let parser = Parser::with_start_offset(substr, 4);
assert_eq!(parser.remainder(), "bar baz");

let (bar, parser) = parser.split(' ').unwrap();
assert_eq!(bar, "bar");

let err = parser.split_terminator(' ').unwrap_err();

assert_eq!(parser.remainder(), "baz");
assert_eq!(err.offset(), 8);
assert_eq!(err.kind(), ErrorKind::DelimiterNotFound);
Source

pub const fn skip(self, byte_count: usize) -> Self

Skips byte_count bytes from the parsed string, as well as however many bytes are required to be on a char boundary.

Source

pub const fn skip_back(self, byte_count: usize) -> Self

Skips byte_count bytes from the back of the parsed string, as well as however many bytes are required to be on a char boundary.

Source

pub const fn remainder(self) -> &'a str

Returns the remaining, unparsed string.

Source

pub const fn start_offset(self) -> usize

Gets the byte offset of this parser in the str slice that this was constructed from.

Source

pub const fn end_offset(self) -> usize

Gets the end byte offset of this parser in the str slice that this was constructed from.

Source

pub const fn parse_direction(self) -> ParseDirection

The direction that the parser was last mutated from.

Source

pub const fn into_error(self, kind: ErrorKind) -> ParseError<'a>

Constructs a ParseError for this point in parsing.

Source

pub const fn into_other_error( self, string: &'static &'static str, ) -> ParseError<'a>

Constructs a ParseError for this point in parsing, for an ErrorKind::Other with a custom error message.

Source

pub const fn len(self) -> usize

The amount of unparsed bytes.

Source

pub const fn is_empty(self) -> bool

Whether there are any bytes left to parse.

Source§

impl<'a> Parser<'a>

Source

pub const fn parse_u128(self) -> ParseValueResult<'a, u128>

Parses a u128 until a non-digit is reached.

To parse an integer from an entire string (erroring on non-digit bytes), you can use primitive::parse_u128

You also can use the parse_with macro to parse a u128, and other HasParser types.

§Example
use konst::{
    parsing::{Parser, ParseValueResult},
    unwrap_ctx, try_,
};

{
    let parser = Parser::new("12345");
    let (num, parser) = unwrap_ctx!(parser.parse_u128());
    assert_eq!(num, 12345);
    assert!(parser.is_empty());
}

/// Parses a `[u128; 2]` from a parser starting with `"<number>;<number>", eg: `"100;400"`.
const fn parse_pair(mut parser: Parser<'_>) -> ParseValueResult<'_, [u128; 2]> {
    let mut ret = [0; 2];
     
    (ret[0], parser) = try_!(parser.parse_u128());
     
    // parsing the `;``between the integers.
    //
    // Note that because we don't use `.trim_start()` afterwards,
    // this can't be followed by spaces.
    parser = try_!(parser.strip_prefix(";"));
     
    (ret[1], parser) = try_!(parser.parse_u128());
     
    Ok((ret, parser))
}
const PAIR: ([u128; 2], Parser<'_>) = {
    let parser = Parser::new("1365;6789");
    unwrap_ctx!(parse_pair(parser))
};

assert_eq!(PAIR.0[0], 1365);
assert_eq!(PAIR.0[1], 6789);

assert!(PAIR.1.is_empty());
Source

pub const fn parse_i128(self) -> ParseValueResult<'a, i128>

Parses a i128 until a non-digit is reached.

To parse an integer from an entire string (erroring on non-digit bytes), you can use primitive::parse_i128

You also can use the parse_with macro to parse a i128, and other HasParser types.

§Example
use konst::{Parser, unwrap_ctx, rebind_if_ok};

{
    let parser = Parser::new("12345");
    let (num, parser) = unwrap_ctx!(parser.parse_i128());
    assert_eq!(num, 12345);
    assert!(parser.is_empty());
}
{
    let mut num = 0;
    let mut parser = Parser::new("-54321;6789");
     
    // `rebind_if_ok` stores the return value of `.parse_i128()` in `num` and `parser`,
    // if `.parse_i128()` returned an `Ok((u128, Parser))`.
    rebind_if_ok!{(num, parser) = parser.parse_i128()}
    assert_eq!(num, -54321);
    assert_eq!(parser.remainder(), ";6789");

    rebind_if_ok!{parser = parser.strip_prefix(";")}
    assert_eq!(parser.remainder(), "6789");

    rebind_if_ok!{(num, parser) = parser.parse_i128()}
    assert_eq!(num, 6789);
    assert!(parser.is_empty());
}
Source

pub const fn parse_u64(self) -> ParseValueResult<'a, u64>

Parses a u64 until a non-digit is reached.

To parse an integer from an entire string (erroring on non-digit bytes), you can use primitive::parse_u64

You also can use the parse_with macro to parse a u64, and other HasParser types.

§Example

For an example for how to use this method, you can look at the docs for the Parser::parse_u128 method.

Source

pub const fn parse_i64(self) -> ParseValueResult<'a, i64>

Parses a i64 until a non-digit is reached.

To parse an integer from an entire string (erroring on non-digit bytes), you can use primitive::parse_i64

You also can use the parse_with macro to parse a i64, and other HasParser types.

§Example

For an example for how to use this method, you can look at the docs for the Parser::parse_i128 method.

Source

pub const fn parse_u32(self) -> ParseValueResult<'a, u32>

Parses a u32 until a non-digit is reached.

To parse an integer from an entire string (erroring on non-digit bytes), you can use primitive::parse_u32

You also can use the parse_with macro to parse a u32, and other HasParser types.

§Example

For an example for how to use this method, you can look at the docs for the Parser::parse_u128 method.

Source

pub const fn parse_i32(self) -> ParseValueResult<'a, i32>

Parses a i32 until a non-digit is reached.

To parse an integer from an entire string (erroring on non-digit bytes), you can use primitive::parse_i32

You also can use the parse_with macro to parse a i32, and other HasParser types.

§Example

For an example for how to use this method, you can look at the docs for the Parser::parse_i128 method.

Source

pub const fn parse_u16(self) -> ParseValueResult<'a, u16>

Parses a u16 until a non-digit is reached.

To parse an integer from an entire string (erroring on non-digit bytes), you can use primitive::parse_u16

You also can use the parse_with macro to parse a u16, and other HasParser types.

§Example

For an example for how to use this method, you can look at the docs for the Parser::parse_u128 method.

Source

pub const fn parse_i16(self) -> ParseValueResult<'a, i16>

Parses a i16 until a non-digit is reached.

To parse an integer from an entire string (erroring on non-digit bytes), you can use primitive::parse_i16

You also can use the parse_with macro to parse a i16, and other HasParser types.

§Example

For an example for how to use this method, you can look at the docs for the Parser::parse_i128 method.

Source

pub const fn parse_u8(self) -> ParseValueResult<'a, u8>

Parses a u8 until a non-digit is reached.

To parse an integer from an entire string (erroring on non-digit bytes), you can use primitive::parse_u8

You also can use the parse_with macro to parse a u8, and other HasParser types.

§Example

For an example for how to use this method, you can look at the docs for the Parser::parse_u128 method.

Source

pub const fn parse_i8(self) -> ParseValueResult<'a, i8>

Parses a i8 until a non-digit is reached.

To parse an integer from an entire string (erroring on non-digit bytes), you can use primitive::parse_i8

You also can use the parse_with macro to parse a i8, and other HasParser types.

§Example

For an example for how to use this method, you can look at the docs for the Parser::parse_i128 method.

Source

pub const fn parse_usize(self) -> ParseValueResult<'a, usize>

Parses a usize until a non-digit is reached.

To parse an integer from an entire string (erroring on non-digit bytes), you can use primitive::parse_usize

You also can use the parse_with macro to parse a usize, and other HasParser types.

Source

pub const fn parse_isize(self) -> ParseValueResult<'a, isize>

Parses a isize until a non-digit is reached.

To parse an integer from an entire string (erroring on non-digit bytes), you can use primitive::parse_isize

You also can use the parse_with macro to parse a isize, and other HasParser types.

§Example

For an example for how to use this method, you can look at the docs for the Parser::parse_i128 method.

Source§

impl<'a> Parser<'a>

Source

pub const fn parse_bool(self) -> ParseValueResult<'a, bool>

Parses a bool.

To parse a bool from an entire string (erroring if the string isn’t exactly "true" or "false"), you can use primitive::parse_bool

You also can use the parse_with macro to parse a bool, and other HasParser types.

§Example
use konst::{Parser, unwrap_ctx};

{
    let parser = Parser::new("falsemorestring");
    let (boolean, parser) = unwrap_ctx!(parser.parse_bool());
    assert_eq!(boolean, false);
    assert_eq!(parser.remainder(), "morestring");
}
{
    let parser = Parser::new("truefoo");
    let (boolean, parser) = unwrap_ctx!(parser.parse_bool());
    assert_eq!(boolean, true);
    assert_eq!(parser.remainder(), "foo");
}
Source§

impl<'a> Parser<'a>

Source

pub const fn split_terminator<'p, P>( self, delimiter: P, ) -> Result<(&'a str, Self), ParseError<'a>>
where P: Pattern<'p>,

Gets the string up to (but not including) delimiter.

This is like Parser::split, except that it always requires that the delimiter can be found.

§Return value

If either the string is empty or the delimiter can’t be found, this return an error.

If the delimiter can be found and the string is non-empty. this returns the string before the delimiter, moving the parser to after the delimiter.

§Example
use konst::{
    result::unwrap_ctx,
    Parser,
};

assert_eq!(VARS, ["foo", "bar", "baz"]);

const VARS: [&str; 3] = {
    let parser = Parser::new("foo,bar,baz");
     
    let (foo, parser) = unwrap_ctx!(parser.split_terminator(','));
    let (bar, parser) = unwrap_ctx!(parser.split_terminator(','));
     
    // `.split_terminator(',')` errors here
    // because there's no `,` in the remainder of the string,
    assert!(parser.split_terminator(',').is_err());
     
    [foo, bar, parser.remainder()]
};
Source

pub const fn rsplit_terminator<'p, P>( self, delimiter: P, ) -> Result<(&'a str, Self), ParseError<'a>>
where P: Pattern<'p>,

Gets the string after delimiter.

This is like Parser::rsplit, except that it always requires that the delimiter can be found.

§Return value

If either the string is empty or the delimiter can’t be found, this return an error.

If the delimiter can be found and the string is non-empty. this returns the string after the delimiter, moving the parser to before the delimiter.

§Example
use konst::{
    result::unwrap_ctx,
    Parser,
};

assert_eq!(VARS, ["baz", "bar", "foo"]);

const VARS: [&str; 3] = {
    let parser = Parser::new("foo,bar,baz");
     
    let (baz, parser) = unwrap_ctx!(parser.rsplit_terminator(','));
    let (bar, parser) = unwrap_ctx!(parser.rsplit_terminator(','));
     
    // `.rsplit_terminator(',')` errors here
    // because there's no `,` in the remainder of the string,
    assert!(parser.rsplit_terminator(',').is_err());
     
    [baz, bar, parser.remainder()]
};
Source

pub const fn split<'p, P>( self, delimiter: P, ) -> Result<(&'a str, Self), ParseError<'a>>
where P: Pattern<'p>,

Gets the string up to (but not including) delimiter.

§Return value

If the last delimiter-separated string has already been returned, this return an error.

If the delimiter can’t be found. this returns the remainder of the string.

If the delimiter can be found. this returns the string before the delimiter, moving the parser to after the delimiter.

§Example
use konst::{
    result::unwrap_ctx,
    Parser,
};

assert_eq!(VARS, ["foo", "bar", ""]);

const VARS: [&str; 3] = {
    let parser = Parser::new("foo,bar,");
     
    let (foo, parser) = unwrap_ctx!(parser.split(','));
    let (bar, parser) = unwrap_ctx!(parser.split(','));
    let (empty, parser) = unwrap_ctx!(parser.split(','));
     
    assert!(parser.split(',').is_err());
    assert!(parser.remainder().is_empty());
     
    [foo, bar, empty]
};
Source

pub const fn rsplit<'p, P>( self, delimiter: P, ) -> Result<(&'a str, Self), ParseError<'a>>
where P: Pattern<'p>,

Gets the string after delimiter.

§Return value

If the last delimiter-separated string has already been returned, this return an error.

If the delimiter can’t be found. this returns the remainder of the string.

If the delimiter can be found. this returns the string after the delimiter, moving the parser to before the delimiter.

§Example
use konst::{
    result::unwrap_ctx,
    Parser,
};

assert_eq!(VARS, ["baz", "bar", ""]);

const VARS: [&str; 3] = {
    let parser = Parser::new(",bar,baz");
     
    let (baz, parser) = unwrap_ctx!(parser.rsplit(','));
    let (bar, parser) = unwrap_ctx!(parser.rsplit(','));
    let (empty, parser) = unwrap_ctx!(parser.rsplit(','));
     
    assert!(parser.rsplit(',').is_err());
    assert!(parser.remainder().is_empty());
     
    [baz, bar, empty]
};
Source

pub const fn split_keep<'p, P>( self, delimiter: P, ) -> Result<(&'a str, Self), ParseError<'a>>
where P: Pattern<'p>,

Gets the string up to (but not including) delimiter.

§Return value

This behaves the same as Parser::split, except that it keeps the delimiter in the parser, rather than skip it.

§Example

This example requires the "parsing_proc" feature.


use konst::{
    parsing::{Parser, ParseValueResult},
    eq_str,
    for_range, parser_method, try_rebind, unwrap_ctx,
};

assert_eq!(VALS, [
    Value::Str("hello"),
    Value::U64(3),
    Value::U64(5),
    Value::Str("world"),
]);

const VALS: [Value<'_>; 4] = {
    let mut arr = [Value::Str(""); 4];
    let mut parser = Parser::new("shello,i3,i5,sworld");
     
    for_range!{i in 0..arr.len() =>
        (arr[i], parser) = unwrap_ctx!(parse_value(parser));
        if !parser.is_empty() {
            parser = unwrap_ctx!(parser.strip_prefix(','))
        }
    }
     
    arr
};


#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Value<'a> {
    Str(&'a str),
    U64(u64),
}

pub const fn parse_value(mut parser: Parser<'_>) -> ParseValueResult<'_, Value<'_>> {
    let val = parser_method!{parser, strip_prefix;
        "s" => {
            try_rebind!{(let string, parser) = parser.split_keep(',')}
            Value::Str(string)
        }
        "i" => {
            try_rebind!{(let integer, parser) = parser.parse_u64()}
            Value::U64(integer)
        }
        _ => return Err(parser.into_other_error(&"expected either `s` or `ì`"))
    };
    Ok((val, parser))
}
Source

pub const fn strip_prefix<'p, P>( self, matched: P, ) -> Result<Self, ParseError<'a>>
where P: Pattern<'p>,

Checks that the parsed string starts with matched, returning the remainder of the str.

For calling strip_prefix with multiple alternative matched string literals, you can use the [parser_method] macro, example

§Examples
§Basic
use konst::{Parser, rebind_if_ok};

let mut parser = Parser::new("foo;bar;baz;");

assert!(parser.strip_prefix("aaa").is_err());

rebind_if_ok!{parser = parser.strip_prefix("foo;")}
assert_eq!(parser.remainder(), "bar;baz;");

rebind_if_ok!{parser = parser.strip_prefix("bar;")}
assert_eq!(parser.remainder(), "baz;");

rebind_if_ok!{parser = parser.strip_prefix("baz;")}
assert_eq!(parser.remainder(), "");

§char argument
use konst::{Parser, rebind_if_ok};

let mut parser = Parser::new("abcde");

rebind_if_ok!{parser = parser.strip_prefix('a')}
assert_eq!(parser.remainder(), "bcde");

rebind_if_ok!{parser = parser.strip_prefix('b')}
assert_eq!(parser.remainder(), "cde");

rebind_if_ok!{parser = parser.strip_prefix('c')}
assert_eq!(parser.remainder(), "de");
Source

pub const fn strip_suffix<'p, P>( self, matched: P, ) -> Result<Self, ParseError<'a>>
where P: Pattern<'p>,

Checks that the parsed string ends with matched, returning the remainder of the string.

For calling strip_suffix with multiple alternative matched string literals, you can use the [parser_method] macro.

§Examples
§&str argument
use konst::{Parser, rebind_if_ok};

let mut parser = Parser::new("foo;bar;baz;");

assert!(parser.strip_suffix("aaa").is_err());

rebind_if_ok!{parser = parser.strip_suffix("baz;")}
assert_eq!(parser.remainder(), "foo;bar;");

rebind_if_ok!{parser = parser.strip_suffix("bar;")}
assert_eq!(parser.remainder(), "foo;");

rebind_if_ok!{parser = parser.strip_suffix("foo;")}
assert_eq!(parser.remainder(), "");
§char argument
use konst::{Parser, rebind_if_ok};

let mut parser = Parser::new("edcba");

rebind_if_ok!{parser = parser.strip_suffix('a')}
assert_eq!(parser.remainder(), "edcb");

rebind_if_ok!{parser = parser.strip_suffix('b')}
assert_eq!(parser.remainder(), "edc");

rebind_if_ok!{parser = parser.strip_suffix('c')}
assert_eq!(parser.remainder(), "ed");
Source

pub const fn trim(self) -> Self

Removes whitespace from the start and end of the parsed string.

§Example
use konst::{Parser, unwrap_ctx};

let mut parser = Parser::new("    foo\n\t bar    ");

parser = parser.trim();
assert_eq!(parser.remainder(), "foo\n\t bar");
Source

pub const fn trim_start(self) -> Self

Removes whitespace from the start of the parsed string.

§Example
use konst::{Parser, unwrap_ctx};

let mut parser = Parser::new("    foo\n\t bar");

parser = parser.trim_start();
assert_eq!(parser.remainder(), "foo\n\t bar");

parser = unwrap_ctx!(parser.strip_prefix("foo")).trim_start();
assert_eq!(parser.remainder(), "bar");
Source

pub const fn trim_end(self) -> Self

Removes whitespace from the end of the parsed string.

§Example
use konst::{Parser, unwrap_ctx};

let mut parser = Parser::new("foo,\n    bar,\n    ");

parser = parser.trim_end();
assert_eq!(parser.remainder(), "foo,\n    bar,");

parser = unwrap_ctx!(parser.strip_suffix("bar,")).trim_end();
assert_eq!(parser.remainder(), "foo,");
Source

pub const fn trim_matches<'p, P>(self, needle: P) -> Self
where P: Pattern<'p>,

Repeatedly removes all instances of needle from both the start and end of the parsed string.

§Example
§&str
use konst::Parser;

let mut parser = Parser::new("<><>hello<><>");

parser = parser.trim_matches("<>");
assert_eq!(parser.remainder(), "hello");
§char argument
use konst::Parser;

let mut parser = Parser::new("    world   ");

parser = parser.trim_matches(' ');
assert_eq!(parser.remainder(), "world");
Source

pub const fn trim_start_matches<'p, P>(self, needle: P) -> Self
where P: Pattern<'p>,

Repeatedly removes all instances of needle from the start of the parsed string.

For trimming with multiple needles, you can use the [parser_method] macro, example

§Example
§&str
use konst::Parser;

{
    let mut parser = Parser::new("HelloHelloHello world!");
    parser = parser.trim_start_matches("Hello");
    assert_eq!(parser.remainder(), " world!");
}
{
    let mut parser = Parser::new("        Hi!");
    parser = parser.trim_start_matches("    ");
    assert_eq!(parser.remainder(), "Hi!");
}
{
    let mut parser = Parser::new("------Bye!");
    parser = parser.trim_start_matches("----");
    assert_eq!(parser.remainder(), "--Bye!");
}
§char argument
use konst::Parser;

let mut parser = Parser::new("    ----world");

parser = parser.trim_start_matches(' ');
assert_eq!(parser.remainder(), "----world");

parser = parser.trim_start_matches('-');
assert_eq!(parser.remainder(), "world");

parser = parser.trim_start_matches('-');
assert_eq!(parser.remainder(), "world");
Source

pub const fn trim_end_matches<'p, P>(self, needle: P) -> Self
where P: Pattern<'p>,

Repeatedly removes all instances of needle from the start of the parsed string.

For trimming with multiple needles, you can use the [parser_method] macro, example

§Example
§&str
use konst::Parser;

{
    let mut parser = Parser::new("Hello world!world!world!");
    parser = parser.trim_end_matches("world!");
    assert_eq!(parser.remainder(), "Hello ");
}
{
    let mut parser = Parser::new("Hi!        ");
    parser = parser.trim_end_matches("    ");
    assert_eq!(parser.remainder(), "Hi!");
}
{
    let mut parser = Parser::new("Bye!------");
    parser = parser.trim_end_matches("----");
    assert_eq!(parser.remainder(), "Bye!--");
}
§char argument
use konst::Parser;

let mut parser = Parser::new("world----    ");

parser = parser.trim_end_matches(' ');
assert_eq!(parser.remainder(), "world----");

parser = parser.trim_end_matches('-');
assert_eq!(parser.remainder(), "world");

parser = parser.trim_end_matches('-');
assert_eq!(parser.remainder(), "world");
Source

pub const fn find_skip<'p, P>(self, needle: P) -> Result<Self, ParseError<'a>>
where P: Pattern<'p>,

Skips the parser after the first instance of needle.

For calling find_skip with multiple alternative needle string literals, you can use the [parser_method] macro, example

§Example
§&str argument
use konst::{Parser, unwrap_ctx};

let mut parser = Parser::new("foo--bar,baz--qux");

parser = unwrap_ctx!(parser.find_skip("--"));
assert_eq!(parser.remainder(), "bar,baz--qux");

parser = unwrap_ctx!(parser.find_skip("bar,"));
assert_eq!(parser.remainder(), "baz--qux");

parser = unwrap_ctx!(parser.find_skip("--"));
assert_eq!(parser.remainder(), "qux");

assert!(parser.find_skip("--").is_err());
§char argument
use konst::{Parser, unwrap_ctx};

let mut parser = Parser::new("foo-bar,baz");

parser = unwrap_ctx!(parser.find_skip('-'));
assert_eq!(parser.remainder(), "bar,baz");

parser = unwrap_ctx!(parser.find_skip(','));
assert_eq!(parser.remainder(), "baz");
Source

pub const fn rfind_skip<'p, P>(self, needle: P) -> Result<Self, ParseError<'a>>
where P: Pattern<'p>,

Truncates the parsed string to before the last instance of needle.

For calling rfind_skip with multiple alternative needle string literals, you can use the [parser_method] macro, example

§Example
§&str argument
use konst::{Parser, unwrap_ctx};

let mut parser = Parser::new("foo--bar,baz--qux");

parser = unwrap_ctx!(parser.rfind_skip("--"));
assert_eq!(parser.remainder(), "foo--bar,baz");

parser = unwrap_ctx!(parser.rfind_skip(",baz"));
assert_eq!(parser.remainder(), "foo--bar");

parser = unwrap_ctx!(parser.rfind_skip("--"));
assert_eq!(parser.remainder(), "foo");

assert!(parser.rfind_skip("--").is_err());
§char argument
use konst::{Parser, unwrap_ctx};

let mut parser = Parser::new("foo,bar-baz");

parser = unwrap_ctx!(parser.rfind_skip('-'));
assert_eq!(parser.remainder(), "foo,bar");

parser = unwrap_ctx!(parser.rfind_skip(','));
assert_eq!(parser.remainder(), "foo");

Trait Implementations§

Source§

impl<'a> Clone for Parser<'a>

Source§

fn clone(&self) -> Parser<'a>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a> Debug for Parser<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'a> PartialEq for Parser<'a>

Source§

fn eq(&self, other: &Parser<'a>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a> Copy for Parser<'a>

Source§

impl<'a> Eq for Parser<'a>

Source§

impl<'a> StructuralPartialEq for Parser<'a>

Auto Trait Implementations§

§

impl<'a> Freeze for Parser<'a>

§

impl<'a> RefUnwindSafe for Parser<'a>

§

impl<'a> Send for Parser<'a>

§

impl<'a> Sync for Parser<'a>

§

impl<'a> Unpin for Parser<'a>

§

impl<'a> UnwindSafe for Parser<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.