|
31 | 31 | fn from(value: I) -> Self { |
32 | 32 | let shape = value |
33 | 33 | .map(|line| { |
34 | | - line.as_ref() |
35 | | - .chars() |
36 | | - .map(|c| c == '#') |
37 | | - .collect_array() |
38 | | - .unwrap() |
| 34 | + let line = line.as_ref(); |
| 35 | + line.bytes().map(|c| c == b'#').collect_array().unwrap() |
39 | 36 | }) |
40 | 37 | .collect_array() |
41 | 38 | .unwrap(); |
@@ -83,46 +80,37 @@ fn parse_input<I, S>(input: I) -> (Vec<Present>, Vec<Region>) |
83 | 80 | where |
84 | 81 | I: IntoIterator<Item = S>, |
85 | 82 | <I as IntoIterator>::IntoIter: Clone, |
86 | | - S: AsRef<str> + Clone, |
| 83 | + S: AsRef<str>, |
87 | 84 | { |
88 | 85 | static INDEX_REGEX: OnceLock<Regex> = OnceLock::new(); |
89 | 86 | let index_re = INDEX_REGEX.get_or_init(|| Regex::new(r"^(?<idx>\d+):\s*$").unwrap()); |
90 | 87 |
|
91 | | - let mut it = input.into_iter().peekable(); |
| 88 | + let it = input.into_iter(); |
| 89 | + |
| 90 | + let mut present_it = it |
| 91 | + .clone() |
| 92 | + .take_while(|line| line.as_ref().parse::<Region>().is_err()); |
92 | 93 | let mut presents = Vec::new(); |
93 | 94 | let mut i = 0; |
94 | 95 | loop { |
95 | | - // if let Some(line) = it.peek() && line.as_ref().trim_ascii().is_empty() { |
96 | | - // |
97 | | - // } |
98 | | - |
99 | | - let index_s = it.next().expect("end of data before regions!"); |
100 | | - let index_s = index_s.as_ref(); |
101 | | - if index_s.trim_ascii().is_empty() { |
102 | | - continue; |
103 | | - } |
104 | | - |
105 | | - match index_re.captures(index_s) { |
| 96 | + match present_it.next() { |
106 | 97 | None => break, |
107 | | - Some(index_cap) => { |
| 98 | + Some(s) if s.as_ref().trim_ascii().is_empty() => continue, |
| 99 | + Some(s) => { |
| 100 | + let index_cap = index_re.captures(s.as_ref()).unwrap(); |
108 | 101 | let index: usize = index_cap.ez_get("idx"); |
109 | 102 | if index != i { |
110 | 103 | panic!("expected present #{i}, found present #{index}"); |
111 | 104 | } |
112 | 105 |
|
113 | | - let present: Present = it.clone().take(3).into(); |
| 106 | + let present: Present = present_it.by_ref().take(3).into(); |
114 | 107 | presents.push(present); |
115 | | - |
116 | | - it = it.dropping(3); |
117 | 108 | i += 1; |
118 | 109 | }, |
119 | 110 | } |
120 | 111 | } |
121 | 112 |
|
122 | | - let regions = it |
123 | | - .skip_while(|l| l.as_ref().trim_ascii().is_empty()) |
124 | | - .map(|l| l.as_ref().parse().unwrap()) |
125 | | - .collect(); |
| 113 | + let regions = it.filter_map(|l| l.as_ref().parse().ok()).collect(); |
126 | 114 |
|
127 | 115 | (presents, regions) |
128 | 116 | } |
0 commit comments