macro_rules! create_parse_fn {
    ($name: ident, $re: expr, $($res: ty),*) => { ... };
    (@body $str: expr, $re: expr, $($res: ty),*) => { ... };
}
Expand description

Creates function for parsing tuple of values from strings corresponding to given template.

usage: create_parse_fn!{function_name, re, types..}

where:

  • function_name – Name of function to be created.
  • re – Format string for matching arguments. Format string is regular expression, preprocessed by macro, and rules simular to regexprs applies to it. In order to macro work properly usage of capture groups should be avoided. Non capturing (:?groups) are fine.
  • types.. – sequence of types expected as function output. Each type must implement trait ParsePrimitive. Default implementors:
    • unsigned integers: u8, u16, u32, u64, u128, usize
    • signed integers: i8, i16, i16, i64, i128, isize
    • floating point numbers: f32, f64,
    • String
use reformation::create_parse_fn;

// "\(" and "\)" are escaped, since they are special characters in
// regular expression syntax
create_parse_fn!{parse_vec, r"^Vec\({}, {}\)$", i32, i32}


fn main(){
    let (x, y) = parse_vec("Vec(-16, 8)").unwrap();
    assert_eq!(x, -16i32);
    assert_eq!(y, 8i32);
}
use reformation::create_parse_fn;

// "\{{" and "\}}" is the way to use symbols {, } in format string,
// since { is special symbol for formatting and also special symbol for
// regular expressions, so it needs to be escaped twice.
create_parse_fn!{parse_curly, r"^Vec\{{{}, {}, {}\}}$", i32, i32, usize}

fn main(){
    let (x, y, z) = parse_curly("Vec{-16, 8, 800}").unwrap();
    assert_eq!(x, -16i32);
    assert_eq!(y, 8i32);
    assert_eq!(z, 800usize);
}

You can use features of regular expression

use reformation::create_parse_fn;

// Ignore spaces between coordinates
create_parse_fn!{parse_vec, r"^Vec\({}, {}\)$", f32, f32}

fn main(){
    let (x, y) = parse_vec("Vec(-16, 8e-3)").unwrap();
    assert_eq!(x, -16.0);
    assert_eq!(y, 0.008);
}