Crate prse

source ·
Expand description

githubcrates-iodocs-rs


This crate provides the parse! macro to easily parse strings using a format args like syntax.

Prse is a no-std compatible small string parsing library with an emphasis on speed and ease of use.

The parse! and try_parse! macros can parse anything in the standard library that implements FromStr, or any type that implements LendingFromStr.


Examples

let input = "Person 5: Hello Bob!";
let mut name = "";

// Calls try_parse and unwraps the result.
let five: u32 = parse!(input, "Person {}: Hello {name}!");

assert_eq!(five, 5);
assert_eq!(name, "Bob");
let input = "I hate apples!\nI love apricots!";

for fruit in input.lines().map(|l| try_parse!(l, "I love {}!")) {
    match fruit {
        Ok::<&str, _>(fruit) => assert_eq!(fruit, "apricots"),
        Err(e) => println!("{e:?}")
    }
}

Repetition

You can parse multiple parts of a string using one of the following methods:

Array

You can parse a string into an array of parsed elements using the following syntax {<var>:<sep>:<count>}.

let input = "My farm contains exactly 3 animals: Beatrice, Betsy, Callum";

// var = nothing, sep = ", " and count = 3
let array: [&str; 3] = parse!(input, "My farm contains exactly 3 animals: {:, :3}");

assert_eq!(array, ["Beatrice", "Betsy", "Callum"]);

Vec

You can parse a string into a Vec of parsed elements using the following syntax {<var>:<sep>:}. This way of parsing is only available if the alloc feature has been enabled.

let input = "My farm contains some amount of booleans: true || false || true || false";
let mut many: Vec<bool> = vec![];

// var = many and sep = " || "
parse!(input, "My farm contains some amount of booleans: {many: || :}");

assert_eq!(many, vec![true, false, true, false]);

Iterator

Alternatively if you are unable to allocate anything then you can use a lazy iterator by using the following syntax {<var>:<sep>:0}. One important note is that since the iterator is evaluated lazily it will always return an iterator of Results.

let input = "My farm has this many animals: [5,23,42,1,3,5]";

// var = nothing and sep = ","
let animal_count: u32 = parse!(input, "My farm has this many animals: [{:,:0}]")
    .flat_map(|c: Result<u32, _>| c.ok())
    .sum();

assert_eq!(animal_count, 79);

Macros

The parse macro allows you to parse a string into any type that implements LendingFromStr.
Returns a Result instead of unwrapping like parse!. The Result has ParseError as an error type.

Enums

The error returned when trying to parse a type using try_parse or LendingFromStr.

Traits

An str extension trait to allow you to call the from_str from LendingFromStr without specifying the type.
Parse a string into the implemented type, unlike FromStr this trait allows you to borrow the string.