summaryrefslogtreecommitdiffstats
path: root/src/lib.rs
blob: 71a0ec5754452b969f02324a75df9720e94e9da4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use std::env;
use std::str::{self, FromStr};

pub trait Parsable {
    fn parse(s: &str) -> Self;
}

impl<T: Parsable> Parsable for Vec<T> {
    fn parse(s: &str) -> Vec<T> {
        let mut depth = 0;
        let mut sep = Vec::new();
        let s = s
            .trim()
            .strip_prefix("[")
            .expect("Missing [")
            .strip_suffix("]")
            .expect("Missing ]");
        let mut last = 0;
        for (i, c) in s.chars().enumerate() {
            if c == '[' {
                depth += 1;
            } else if c == ']' {
                if depth == 0 {
                    panic!("Invalid array format");
                }
                depth -= 1;
            } else if c == ',' && depth == 0 {
                sep.push((last, i));
                last = i + 1;
            }
        }
        if last != s.len() {
            sep.push((last, s.len()));
        }
        let mut out = Vec::new();
        for (start, end) in sep {
            out.push(parse(s[start..end].trim()));
        }
        out
    }
}

impl Parsable for i32 {
    fn parse(s: &str) -> i32 {
        i32::from_str(s).unwrap_or_else(|_| panic!("Failed to parse integer ({s})"))
    }
}

impl Parsable for char {
    fn parse(s: &str) -> char {
        s.chars()
            .next()
            .unwrap_or_else(|| panic!("Parsing empty string"))
    }
}

pub fn parse<T: Parsable>(s: &str) -> T {
    <T as Parsable>::parse(s)
}

pub fn vc(s: &str) -> Vec<char> {
    parse(s)
}

pub fn vvc(s: &str) -> Vec<Vec<char>> {
    parse(s)
}

pub fn vi(s: &str) -> Vec<i32> {
    parse(s)
}

pub fn vvi(s: &str) -> Vec<Vec<i32>> {
    parse(s)
}

pub fn arg(n: usize) -> String {
    env::args()
        .nth(n)
        .unwrap_or_else(|| panic!("Failed to get argument ({n})"))
}

pub fn arg_into<T: Parsable>(n: usize) -> T {
    <T as Parsable>::parse(arg(n).as_str())
}