refactor Assignments::next

This commit is contained in:
Christian Ulrich 2022-12-04 17:17:42 +01:00
parent ea681859bd
commit df20baa31b
No known key found for this signature in database
GPG Key ID: 8241BE099775A097
1 changed files with 20 additions and 15 deletions

View File

@ -31,21 +31,7 @@ impl Iterator for Assignments {
if let Some(line) = io::stdin().lines().next() {
let line = line.unwrap();
if line.len() > 0 {
if let Some((left, right)) = line.split_once(',') {
if let (Some((s1, e1)), Some((s2, e2))) =
(left.split_once('-'), right.split_once('-'))
{
if let (Ok(s1), Ok(e1), Ok(s2), Ok(e2)) = (
s1.parse::<u8>(),
e1.parse::<u8>(),
s2.parse::<u8>(),
e2.parse::<u8>(),
) {
return Some(Ok(Assignment::new(s1..=e1, s2..=e2)));
}
}
}
return Some(Err("input file contains invalid line"));
return Some(Assignment::from_str(&line));
}
}
None
@ -60,6 +46,25 @@ impl Assignment {
}
}
fn parse_range(input: &str) -> Result<RangeInclusive<u8>, &'static str> {
if let Some((start, end)) = input.split_once('-') {
if let (Ok(start), Ok(end)) = (start.parse::<u8>(), end.parse::<u8>()) {
return Ok(start..=end);
}
}
Err("invalid range string")
}
pub fn from_str(input: &str) -> Result<Self, &'static str> {
if let Some((left, right)) = input.split_once(',') {
return Ok(Assignment::new(
Self::parse_range(left)?,
Self::parse_range(right)?,
));
}
Err("invalid assignment string")
}
pub fn has_obsolete_range(&self) -> bool {
self.range1.contains(self.range2.start()) && self.range1.contains(self.range2.end())
|| self.range2.contains(self.range1.start()) && self.range2.contains(self.range1.end())