summaryrefslogtreecommitdiffstats
path: root/src/choice.rs
blob: 2fb0974305b84ced28e2c1dd4aa7e4dcc2fb57d9 (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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
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(" "));
    }

    pub fn is_reverse_range(&self) -> bool {
        match self {
            Choice::Field(_) => false,
            Choice::FieldRange(r) => match r {
                (Some(start), Some(end)) => end < start,
                _ => false,
            },
        }
    }

    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();

        let mut slices = 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.exclusive {
                        (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.exclusive {
                        (end - 1).try_into().unwrap()
                    } else {
                        (*end).try_into().unwrap()
                    };
                    words
                        .filter(|x| {
                            (x.0 <= e && x.0 >= (*start).try_into().unwrap())
                                || self.is_reverse_range()
                                    && (x.0 >= e && x.0 <= (*start).try_into().unwrap())
                        })
                        .map(|x| x.1)
                        .collect::<Vec<&str>>()
                }
            },
        };

    if self.is_reverse_range() {
        slices.reverse();
    }

    return slices;

}
}

#[cfg(test)]
mod 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));
        }
    }

    mod get_choice_slice_tests {
        use super::*;

        #[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_out_of_order() {
            let config = Config::from_iter(vec!["choose", "3", "1"]);
            assert_eq!(
                vec!["cool"],
                config.opt.choice[0]
                    .get_choice_slice(&String::from("rust is pretty cool"), &config)
            );
            assert_eq!(
                vec!["is"],
                config.opt.choice[1]
                    .get_choice_slice(&String::from("rust is pretty cool"), &config)
            );
        }

        #[test]
        fn print_1_to_3_exclusive() {
            let config = Config::from_iter(vec!["choose", "1:3", "-x"]);
            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() {
            let config = Config::from_iter(vec!["choose", "1:3" ]);
            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", "cool"],
                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_exclusive() {
            let config = Config::from_iter(vec!["choose", "1:3", "-f", "#", "-x"]);
            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", "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_exclusive() {
            let config = Config::from_iter(vec!["choose", "1:3", "-f", "[aeiou]", "-x"]);
            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() {
            let config = Config::from_iter(vec!["choose", "1:3", "-f", "[aeiou]"]);
            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
                )
            );
        }

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

    }

    mod is_reverse_range_tests {
        use super::*;

        #[test]
        fn is_field_reversed() {
            let config = Config::from_iter(vec!["choose", "0"]);
            assert_eq!(false, config.opt.choice[0].is_reverse_range());
        }

        #[test]
        fn is_field_range_no_star