This commit is contained in:
Frederik Palmø 2021-10-21 16:07:28 +02:00
commit 34267f6939
5 changed files with 102 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target

7
Cargo.lock generated Normal file
View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "eyes"
version = "0.1.0"

6
Cargo.toml Normal file
View file

@ -0,0 +1,6 @@
[package]
name = "eyes"
version = "0.1.0"
edition = "2018"
[dependencies]

71
src/lib.rs Normal file
View file

@ -0,0 +1,71 @@
pub struct Parser<'a> {
_input: &'a str,
_pattern: &'a str,
captures: Vec<&'a str>,
}
impl<'a> Parser<'a> {
pub fn new(input: &'a str, pattern: &'a str) -> Self {
let splits = pattern
.split("{}")
.filter(|pat| pat != &"")
.collect::<Vec<_>>();
let mut captures = vec![input];
println!("splits: {:?}", splits);
for pat in splits {
captures = captures
.iter()
.map(|sub| sub.split(pat))
.flatten()
.collect();
}
Self {
_input: input,
_pattern: pattern,
captures: captures[1..].to_vec(),
}
}
pub fn captures(&self) -> Vec<&'a str> {
self.captures.to_owned()
}
}
#[macro_export]
macro_rules! parse {
($input: expr, $pattern: tt, $($type:ty),*) => {
{
let mut parser = eyes::Parser::new($input, $pattern);
let mut captures = parser.captures();
captures.reverse();
println!("caps: {:?}", captures);
(
$({
captures.pop().unwrap().parse::<$type>().unwrap()
},)*
)
}
};
}
#[macro_export]
macro_rules! try_parse {
($input: expr, $pattern: tt, $($type:ty),*) => {
{
let mut parser = eyes::Parser::new($input, $pattern);
let mut captures = parser.captures();
captures.reverse();
println!("caps: {:?}", captures);
(
$({
captures.pop().unwrap().parse::<$type>()
},)*
)
}
};
}

17
src/main.rs Normal file
View file

@ -0,0 +1,17 @@
use eyes::*;
fn main() {
let input = "#1 @ 338,764: 20x24";
let pattern = "#{} @ {},{}: {}x{}";
println!("input: {}", input);
println!("pattern: {}", pattern);
let (id, x, y, w, h) = parse!(input, pattern, usize, isize, isize, usize, usize);
println!("id: {:?}", id);
println!("x: {:?}", x);
println!("y: {:?}", y);
println!("w: {:?}", w);
println!("h: {:?}", h);
}