From 33b3d303a0d3d6c91f390811a8e355bbe5d83928 Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Thu, 2 Dec 2021 00:48:01 -0500 Subject: [PATCH] Avoid unneeded heap allocation in day 2 --- day2/src/main.rs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/day2/src/main.rs b/day2/src/main.rs index 99d963c..dee8949 100644 --- a/day2/src/main.rs +++ b/day2/src/main.rs @@ -113,18 +113,21 @@ fn parse_line(line: &str) -> IResult<&str, Direction> { fn main() { let input_file_name = env::args().nth(1).expect("No input filename specified"); let input_file = File::open(input_file_name).expect("Could not open input file"); - let lines = BufReader::new(input_file) + let directions = BufReader::new(input_file) .lines() .map(|res| res.expect("Failed to read line")) - .collect::>(); - - let directions = lines - .iter() .map(|line| { - parse_line(line) - .unwrap_or_else(|err| panic!("Failed to parse line '{}': {}", line, err)) + let (remaining, direction) = parse_line(&line) + .unwrap_or_else(|err| panic!("Failed to parse line '{}': {}", line, err)); + + assert!( + remaining.is_empty(), + "Input remained after parsing: {}", + remaining + ); + + direction }) - .map(|(_, direction)| direction) .collect::>(); println!("Part 1: {}", simulate(&directions, &Part::Part1));