Parser

Struct Parser 

Source
pub struct Parser<'a> { /* private fields */ }
Available on crate feature parsing only.
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.

§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, ParseError, parser_method},
    result,
    for_range, try_,
};

// 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 mut parser = Parser::new(input);
    let len = result::unwrap!(parser.parse_usize());
    result::unwrap!(parser.strip_prefix(';'));
    (len, parser)
};

const ANGLES: [Angle; LEN_AND_PARSER.0] =
    result::unwrap!(Angle::parse_array(&mut LEN_AND_PARSER.1));

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<'p, const LEN: usize>(
        parser: &mut Parser<'p>
    ) -> Result<[Angle; LEN], ParseError<'p>> {
        let mut ret = [Angle::UP; LEN];
         
        for_range!{i in 0..LEN =>
            ret[i] = try_!(Angle::parse(parser.trim_start()));
             
            parser.trim_start();
            if !parser.is_empty() {
                try_!(parser.strip_prefix(','));
            }
        }
        Ok(ret)
    }

    pub const fn parse<'p>(parser: &mut Parser<'p>) -> Result<Angle, ParseError<'p>> {
        if let Ok(angle) = parser.parse_u64() {
            return Ok(Self::new(angle))
        }
         
        let angle = parser_method!{parser, strip_prefix;
            "up" => Self::UP,
            "right" => Self::RIGHT,
            "down" => Self::DOWN,
            "left" => Self::LEFT,
            _ => return Err(parser.to_other_error(&"could not parse Direction"))
        };
        Ok(angle)
    }
}

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 mut parser = Parser::with_start_offset(substr, 4);
assert_eq!(parser.remainder(), "bar baz");

let bar = 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(&mut self, byte_count: usize) -> &mut Self

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

This method mutates the parser in place.

Source

pub const fn skip_back(&mut self, byte_count: usize) -> &mut 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.

This method mutates the parser in place.

Source

pub const fn copy(&self) -> Self

Returns a bytewise copy of Self

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 to_error(&self, kind: ErrorKind) -> ParseError<'a>

Constructs a ParseError for this point in parsing.

Source

pub const fn to_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(&mut self) -> Result<u128, ParseError<'a>>

Parses a u128 until a non-digit is reached.

This method mutates the parser in place on success, leaving it unmodified on error.

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

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

§Example
use konst::{
    parsing::{Parser, ParseError},
    result, try_,
};

{
    let mut parser = Parser::new("12345");
    let num = result::unwrap!(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<'a>(parser: &mut Parser<'a>) -> Result<[u128; 2], ParseError<'a>> {
    let mut ret = [0; 2];
     
    ret[0] = 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.
    try_!(parser.strip_prefix(";"));
     
    ret[1] = try_!(parser.parse_u128());
     
    Ok(ret)
}
const PAIR: [u128; 2] = {
    let parser = &mut Parser::new("1365;6789");
    result::unwrap!(parse_pair(parser))
};

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

Source

pub const fn parse_i128(&mut self) -> Result<i128, ParseError<'a>>

Parses a i128 until a non-digit is reached.

This method mutates the parser in place on success, leaving it unmodified on error.

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

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

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

{
    let mut parser = Parser::new("12345");
    let num = result::unwrap!(parser.parse_i128());
    assert_eq!(num, 12345);
    assert!(parser.is_empty());
}
{
    let mut parser = Parser::new("-54321;6789");
     
    assert_eq!(result::unwrap!(parser.parse_i128()), -54321);
    assert_eq!(parser.remainder(), ";6789");

    _ = parser.strip_prefix(";");
    assert_eq!(parser.remainder(), "6789");

    assert_eq!(result::unwrap!(parser.parse_i128()), 6789);
    assert!(parser.is_empty());
}
Source

pub const fn parse_u64(&mut self) -> Result<u64, ParseError<'a>>

Parses a u64 until a non-digit is reached.

This method mutates the parser in place on success, leaving it unmodified on error.

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

You also can use the parse_type 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(&mut self) -> Result<i64, ParseError<'a>>

Parses a i64 until a non-digit is reached.

This method mutates the parser in place on success, leaving it unmodified on error.

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

You also can use the parse_type 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(&mut self) -> Result<u32, ParseError<'a>>

Parses a u32 until a non-digit is reached.

This method mutates the parser in place on success, leaving it unmodified on error.

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

You also can use the parse_type 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(&mut self) -> Result<i32, ParseError<'a>>

Parses a i32 until a non-digit is reached.

This method mutates the parser in place on success, leaving it unmodified on error.

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

You also can use the parse_type 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(&mut self) -> Result<u16, ParseError<'a>>

Parses a u16 until a non-digit is reached.

This method mutates the parser in place on success, leaving it unmodified on error.

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

You also can use the parse_type 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(&mut self) -> Result<i16, ParseError<'a>>

Parses a i16 until a non-digit is reached.

This method mutates the parser in place on success, leaving it unmodified on error.

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

You also can use the parse_type 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(&mut self) -> Result<u8, ParseError<'a>>

Parses a u8 until a non-digit is reached.

This method mutates the parser in place on success, leaving it unmodified on error.

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

You also can use the parse_type 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(&mut self) -> Result<i8, ParseError<'a>>

Parses a i8 until a non-digit is reached.

This method mutates the parser in place on success, leaving it unmodified on error.

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

You also can use the parse_type 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(&mut self) -> Result<usize, ParseError<'a>>

Parses a usize until a non-digit is reached.

This method mutates the parser in place on success, leaving it unmodified on error.

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

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

Source

pub const fn parse_isize(&mut self) -> Result<isize, ParseError<'a>>

Parses a isize until a non-digit is reached.

This method mutates the parser in place on success, leaving it unmodified on error.

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

You also can use the parse_type 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(&mut self) -> Result<bool, ParseError<'a>>

Parses a bool.

This method mutates the parser in place on success, leaving it unmodified on error.

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_type macro to parse a bool, and other HasParser types.

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

{
    let mut parser = Parser::new("falsemorestring");
    let boolean = result::unwrap!(parser.parse_bool());
    assert_eq!(boolean, false);
    assert_eq!(parser.remainder(), "morestring");
}
{
    let mut parser = Parser::new("truefoo");
    let boolean = result::unwrap!(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>( &mut self, delimiter: P, ) -> Result<&'a str, ParseError<'a>>
where P: Pattern<'p>,

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

This method mutates the parser in place on success, leaving it unmodified on error.

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::{Parser, result};

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

const VARS: [&str; 3] = {
    let mut parser = Parser::new("foo,bar,baz");
     
    let foo = result::unwrap!(parser.split_terminator(','));
    let bar = result::unwrap!(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>( &mut self, delimiter: P, ) -> Result<&'a str, ParseError<'a>>
where P: Pattern<'p>,

Gets the string after delimiter.

This method mutates the parser in place on success, leaving it unmodified on error.

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::{Parser, result};

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

const VARS: [&str; 3] = {
    let mut parser = Parser::new("foo,bar,baz");
     
    let baz = result::unwrap!(parser.rsplit_terminator(','));
    let bar = result::unwrap!(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>( &mut self, delimiter: P, ) -> Result<&'a str, 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::{Parser, result};

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

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

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

Gets the string after delimiter.

This method mutates the parser in place on success, leaving it unmodified on error.

§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::{Parser, result};

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

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

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

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

This method mutates the parser in place on success, leaving it unmodified on error.

§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, ParseError, parser_method},
    result,
    eq_str, for_range, try_,
};

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 parser = &mut Parser::new("shello,i3,i5,sworld");
     
    for_range!{i in 0..arr.len() =>
        arr[i] = result::unwrap!(parse_value(parser));
        if !parser.is_empty() {
            result::unwrap!(parser.strip_prefix(','));
        }
    }
     
    arr
};


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

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

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

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

This method mutates the parser in place on success, leaving it unmodified on error.

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

§Examples
§Basic
use konst::Parser;

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

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

_ = parser.strip_prefix("foo;");
assert_eq!(parser.remainder(), "bar;baz;");

_ = parser.strip_prefix("bar;");
assert_eq!(parser.remainder(), "baz;");

_ = parser.strip_prefix("baz;");
assert_eq!(parser.remainder(), "");

§char argument
use konst::Parser;

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

_ = parser.strip_prefix('a');
assert_eq!(parser.remainder(), "bcde");

_ = parser.strip_prefix('b');
assert_eq!(parser.remainder(), "cde");

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

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

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

This method mutates the parser in place on success, leaving it unmodified on error.

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

§Examples
§&str argument
use konst::Parser;

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

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

_ = parser.strip_suffix("baz;");
assert_eq!(parser.remainder(), "foo;bar;");

_ = parser.strip_suffix("bar;");
assert_eq!(parser.remainder(), "foo;");

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

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

_ = parser.strip_suffix('a');
assert_eq!(parser.remainder(), "edcb");

_ = parser.strip_suffix('b');
assert_eq!(parser.remainder(), "edc");

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

pub const fn trim(&mut self) -> &mut Self

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

This method mutates the parser in place.

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

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

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

pub const fn trim_start(&mut self) -> &mut Self

Removes whitespace from the start of the parsed string.

This method mutates the parser in place.

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

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

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

result::unwrap!(parser.strip_prefix("foo")).trim_start();
assert_eq!(parser.remainder(), "bar");
Source

pub const fn trim_end(&mut self) -> &mut Self

Removes whitespace from the end of the parsed string.

This method mutates the parser in place.

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

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

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

result::unwrap!(parser.strip_suffix("bar,")).trim_end();
assert_eq!(parser.remainder(), "foo,");
Source

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

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

This method mutates the parser in place.

§Example
§&str
use konst::Parser;

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

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

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

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

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

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

This method mutates the parser in place.

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.trim_start_matches("Hello");
    assert_eq!(parser.remainder(), " world!");
}
{
    let mut parser = Parser::new("        Hi!");
    parser.trim_start_matches("    ");
    assert_eq!(parser.remainder(), "Hi!");
}
{
    let mut parser = Parser::new("------Bye!");
    parser.trim_start_matches("----");
    assert_eq!(parser.remainder(), "--Bye!");
}
§char argument
use konst::Parser;

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

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

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

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

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

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

This method mutates the parser in place.

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

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

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

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

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

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

Skips the parser after the first instance of needle.

This method mutates the parser in place on success, leaving it unmodified on error.

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

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

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

result::unwrap!(parser.find_skip("--"));
assert_eq!(parser.remainder(), "bar,baz--qux");

result::unwrap!(parser.find_skip("bar,"));
assert_eq!(parser.remainder(), "baz--qux");

result::unwrap!(parser.find_skip("--"));
assert_eq!(parser.remainder(), "qux");

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

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

result::unwrap!(parser.find_skip('-'));
assert_eq!(parser.remainder(), "bar,baz");

result::unwrap!(parser.find_skip(','));
assert_eq!(parser.remainder(), "baz");
Source

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

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

This method mutates the parser in place on success, leaving it unmodified on error.

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

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

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

result::unwrap!(parser.rfind_skip("--"));
assert_eq!(parser.remainder(), "foo--bar,baz");

result::unwrap!(parser.rfind_skip(",baz"));
assert_eq!(parser.remainder(), "foo--bar");

result::unwrap!(parser.rfind_skip("--"));
assert_eq!(parser.remainder(), "foo");

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

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

result::unwrap!(parser.rfind_skip('-'));
assert_eq!(parser.remainder(), "foo,bar");

result::unwrap!(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 duplicate 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> 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, dest: *mut u8)

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

impl<T> DropFlavorWrapper<T> for T

Source§

type Flavor = MayDrop

The DropFlavor that wraps T into Self
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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.