Separate slice finding from printing

This commit is contained in:
Ryan Geary 2019-09-17 22:30:10 -04:00
parent 5703ed02a1
commit 4afdc50158

View file

@ -78,8 +78,6 @@ mod tests {
//} //}
} }
} }
use regex::Regex; use regex::Regex;
@ -125,6 +123,10 @@ pub enum Choice {
impl Choice { impl Choice {
pub fn print_choice(&self, line: &String, opt: &Opt) { pub fn print_choice(&self, line: &String, opt: &Opt) {
print!("{}", self.get_choice_slice(line, opt).join(" "));
}
fn get_choice_slice<'a>(&self, line: &'a String, opt: &Opt) -> Vec<&'a str> {
let re = Regex::new(match &opt.field_separator { let re = Regex::new(match &opt.field_separator {
Some(s) => s, Some(s) => s,
None => "[[:space:]]", None => "[[:space:]]",
@ -142,39 +144,26 @@ impl Choice {
.enumerate(); .enumerate();
match self { match self {
Choice::Field(i) => { Choice::Field(i) => words
print!(
"{} ",
words
.filter(|x| x.0 == *i as usize) .filter(|x| x.0 == *i as usize)
.map(|x| x.1) .map(|x| x.1)
.collect::<String>() .collect::<Vec<&str>>(),
);
}
Choice::FieldRange(r) => match r { Choice::FieldRange(r) => match r {
(None, None) => print!("{}", words.map(|x| x.1).collect::<String>()), (None, None) => words.map(|x| x.1).collect::<Vec<&str>>(),
(Some(start), None) => print!( (Some(start), None) => words
"{} ",
words
.filter(|x| x.0 >= (*start).try_into().unwrap()) .filter(|x| x.0 >= (*start).try_into().unwrap())
.map(|x| x.1) .map(|x| x.1)
.collect::<Vec<&str>>() .collect::<Vec<&str>>(),
.join(" ")
),
(None, Some(end)) => { (None, Some(end)) => {
let e: usize = if opt.inclusive { let e: usize = if opt.inclusive {
(end + 1).try_into().unwrap() (end + 1).try_into().unwrap()
} else { } else {
(*end).try_into().unwrap() (*end).try_into().unwrap()
}; };
print!(
"{} ",
words words
.filter(|x| x.0 < e) .filter(|x| x.0 < e)
.map(|x| x.1) .map(|x| x.1)
.collect::<Vec<&str>>() .collect::<Vec<&str>>()
.join(" ")
)
} }
(Some(start), Some(end)) => { (Some(start), Some(end)) => {
let e: usize = if opt.inclusive { let e: usize = if opt.inclusive {
@ -182,17 +171,13 @@ impl Choice {
} else { } else {
(*end).try_into().unwrap() (*end).try_into().unwrap()
}; };
print!(
"{} ",
words words
.filter(|x| x.0 < e && x.0 >= (*start).try_into().unwrap()) .filter(|x| x.0 < e && x.0 >= (*start).try_into().unwrap())
.map(|x| x.1) .map(|x| x.1)
.collect::<Vec<&str>>() .collect::<Vec<&str>>()
.join(" ")
)
} }
}, },
}; }
} }
pub fn parse_choice(src: &str) -> Result<Choice, ParseIntError> { pub fn parse_choice(src: &str) -> Result<Choice, ParseIntError> {