summaryrefslogtreecommitdiffstats
path: root/src/choice.rs
blob: d3485a4c2321eacc269aa4104fe390635390dcf9 (plain)
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
use crate::io::{BufWriter, Write};
use std::convert::TryInto;

use crate::config::Config;

pub type Range = (Option<u32>, Option<u32>);

#[derive(Debug)]
pub enum Choice {
    Field(u32),
    FieldRange(Range),
}

impl Choice {
    pub fn print_choice(
        &self,
        line: &String,
        config: &Config,
        handle: &mut BufWriter<std::io::StdoutLock>,
    ) {
        write!(handle, "{}", self.get_choice_slice(line, config).join(" "));
    }

    fn get_choice_slice<'a>(&self, line: &'a String, config: &Config) -> Vec<&'a str> {
        let words = config
            .separator
            .split(line)
            .into_iter()
            .filter(|s| !s.is_empty())
            .enumerate();

        match self {
            Choice::Field(i) => words
                .filter(|x| x.0 == *i as usize)
                .map(|x| x.1)
                .collect::<Vec<&str>>(),
            Choice::FieldRange(r) => match r {
                (None, None) => words.map(|x| x.1).collect::<Vec<&str>>(),
                (Some(start), None) => words
                    .filter(|x| x.0 >= (*start).try_into().unwrap())
                    .map(|x| x.1)
                    .collect::<Vec<&str>>(),
                (None, Some(end)) => {
                    let e: usize = if config.opt.inclusive {
                        (end + 1).try_into().unwrap()
                    } else {
                        (*end).try_into().unwrap()
                    };
                    words
                        .filter(|x| x.0 < e)
                        .map(|x| x.1)
                        .collect::<Vec<&str>>()
                }
                (Some(start), Some(end)) => {
                    let e: usize = if config.opt.inclusive {
                        (end + 1).try_into().unwrap()
                    } else {
                        (*end).try_into().unwrap()
                    };
                    words
                        .filter(|x| x.0 < e && x.0 >= (*start).try_into().unwrap())
                        .map(|x| x.1)
                        .collect::<Vec<&str>>()
                }
            },
        }
    }
}

#[cfg(test)]
mod tests {

    mod get_choice_slice_tests {
        use crate::config::{Config, Opt};
        use std::ffi::OsString;
        use structopt::StructOpt;

        impl Config {
            pub fn from_iter<I>(iter: I) -> Self
            where
                I: IntoIterator,
                I::Item: Into<OsString> + Clone,
            {
                return Config::new(Opt::from_iter(iter));
            }
        }

        #[test]
        fn print_0() {
            let config = Config::from_iter(vec!["choose", "0"]);
            assert_eq!(
                vec!["rust"],
                config.opt.choice[0]
                    .get_choice_slice(&String::from("rust is pretty cool"), &config)
            );
        }

        #[test]
        fn print_after_end() {
            let config = Config::from_iter(vec!["choose", "10"]);
            assert_eq!(
                Vec::<&str>::new(),
                config.opt.choice[0]
                    .get_choice_slice(&String::from("rust is pretty cool"), &config)
            );
        }

        #[test]
        fn print_1_to_3() {
            let config = Config::from_iter(vec!["choose", "1:3"]);
            assert_eq!(
                vec!["is", "pretty"],
                config.opt.choice[0]
                    .get_choice_slice(&String::from("rust is pretty cool"), &config)
            );
        }

        #[test]
        fn print_1_to_3_inclusive() {
            let config = Config::from_iter(vec!["choose", "1:3", "-n"]);
            assert_eq!(
                vec!["is", "pretty", "cool"],
                config.opt.choice[0]
                    .get_choice_slice(&String::from("rust is pretty cool"), &config)
            );
        }

        #[test]
        fn print_1_to_3_separated_by_hashtag() {
            let config = Config::from_iter(vec!["choose", "1:3", "-f", "#"]);
            assert_eq!(
                vec!["is", "pretty"],
                config.opt.choice[0]
                    .get_choice_slice(&String::from("rust#is#pretty#cool"), &config)
            );
        }

        #[test]
        fn print_1_to_3_separated_by_varying_multiple_hashtag() {
            let config = Config::from_iter(vec!["choose", "1:3", "-f", "#"]);
            assert_eq!(
                vec!["is", "pretty"],
                config.opt.choice[0]
                    .get_choice_slice(&String::from("rust##is###pretty####cool"), &config)
            );
        }

        #[test]
        fn print_1_to_3_separated_by_varying_multiple_hashtag_inclusive() {
            let config = Config::from_iter(vec!["choose", "1:3", "-f", "#", "-n"]);
            assert_eq!(
                vec!["is", "pretty", "cool"],
                config.opt.choice[0]
                    .get_choice_slice(&String::from("rust##is###pretty####cool"), &config)
            );
        }

        #[test]
        fn print_1_to_3_separated_by_regex_group_vowels() {
            let config = Config::from_iter(vec!["choose", "1:3", "-f", "[aeiou]"]);
            assert_eq!(
                vec![" q", "ck br"],
                config.opt.choice[0].get_choice_slice(
                    &String::from("the quick brown fox jumped over the lazy dog"),
                    &config
                )
            );
        }

        #[test]
        fn print_1_to_3_separated_by_regex_group_vowels_inclusive() {
            let config = Config::from_iter(vec!["choose", "1:3", "-f", "[aeiou]", "-n"]);
            assert_eq!(
                vec![" q", "ck br", "wn f"],
                config.opt.choice[0].get_choice_slice(
                    &String::from("the quick brown fox jumped over the lazy dog"),
                    &config
                )
            );
        }

    }

}