Macro strp::try_parse

source ·
try_parse!() { /* proc-macro */ }
Expand description

Attempts to parse a single variable from an iterator on a type that implements the TryParse trait.

Accepts a source expression which results in a type that implements AsRef<[u8]>, which is then matched against a string literal in order to match a single value from the source.

For more details read the documentation of the strp crate.

Examples.

// The whole source string will be parsed into a u32.
let source = "20".to_string();
let v = try_parse!(source => "{}");
assert_eq!(v, Ok(20u32));

// Only "world" will be parsed into `v`, since the rest
// of the `source` string won't be matched into a value.
let source = "hello world!".to_string();
let v = try_parse!(source => "hello {}!");
assert_eq!(v, Ok("world".to_string()));

// An error is returned, since `source` doesn't match the
// matching string.
let source = "abcd".to_string();
let v: Result<String, _> = try_parse!(source => "123{}");
assert!(matches!(v, Err(_)));

// `source` does match the matching string, but fails to
// parse 'd' as a u32.
let source = "123d".to_string();
let v: Result<u32, _> = try_parse!(source => "123{}");
assert!(matches!(v, Err(_)));

// `try_parse` also works well on a literal.
let v = try_parse!("abcd" => "{}");
assert_eq!(v, Ok("abcd".to_string()));

// Inlines the matched value. This causes `parse` to return Result<(),_>
// where the error type is deduced. If the parsing was successful, the
// successfully parsed value will be put into v.
let v = 0;
try_parse!("u32:5" => "u32:{v}");
assert_eq!(v, 5);

Using stdin instead of a source string.

// Only available with the `std` feature.
let v: f64 = parse!("{}");
println!("{v}");

Parsing hexadecimal or binary values.

let hex: u64 /* Need to specify 'u64' here, since otherwise the value will be too large. */ =
    try_parse!("input hex: 0x0123456789ABCDEF" => "input hex: 0x{:x}");
assert_eq!(hex, 0x0123456789ABCDEF);

let bin = try_parse!("input bin: 0b11110001" => "input bin: 0b{:b}");
assert_eq!(bin, 0b11110001);

// You may also inline parsed values into `try_parse`.
let bin = 0;
try_parse!("input bin: 0b1111" => "input bin: {bin:b}").unwrap();
assert_eq!(bin, 0b1111);