fix some pedantic clippy lints that make sense

- clippy::redundant-closure-for-method-calls
- clippy::explicit-iter-loop
This commit is contained in:
Antoine Martin 2020-12-17 01:23:10 +01:00
parent 449cdc0157
commit e25bc47f8f
20 changed files with 59 additions and 66 deletions

View file

@ -8,10 +8,7 @@ const INPUT: &str = include_str!("../input/day02.txt");
pub fn run() -> Result<String> { pub fn run() -> Result<String> {
let mut res = String::with_capacity(128); let mut res = String::with_capacity(128);
let presents: Vec<Present> = INPUT let presents: Vec<Present> = INPUT.lines().map(str::parse).collect::<Result<_>>()?;
.lines()
.map(|line| line.parse())
.collect::<Result<_>>()?;
writeln!(res, "part 1: {}", part1(&presents))?; writeln!(res, "part 1: {}", part1(&presents))?;
writeln!(res, "part 2: {}", part2(&presents))?; writeln!(res, "part 2: {}", part2(&presents))?;
@ -104,7 +101,7 @@ mod tests {
fn part1_real() { fn part1_real() {
let presents: Vec<Present> = INPUT let presents: Vec<Present> = INPUT
.lines() .lines()
.map(|line| line.parse()) .map(str::parse)
.collect::<Result<_>>() .collect::<Result<_>>()
.unwrap(); .unwrap();
@ -121,7 +118,7 @@ mod tests {
fn part2_real() { fn part2_real() {
let presents: Vec<Present> = INPUT let presents: Vec<Present> = INPUT
.lines() .lines()
.map(|line| line.parse()) .map(str::parse)
.collect::<Result<_>>() .collect::<Result<_>>()
.unwrap(); .unwrap();

View file

@ -16,7 +16,7 @@ pub fn run() -> Result<String> {
fn part1(input: &str) -> usize { fn part1(input: &str) -> usize {
input input
.lines() .lines()
.map(|line| line.trim_end()) .map(str::trim_end)
.filter(|line| { .filter(|line| {
let mut vowel_count = 0; let mut vowel_count = 0;
for c in line.chars() { for c in line.chars() {
@ -51,7 +51,7 @@ fn part1(input: &str) -> usize {
fn part2(input: &str) -> usize { fn part2(input: &str) -> usize {
input input
.lines() .lines()
.map(|line| line.trim_end()) .map(str::trim_end)
.filter(|line| { .filter(|line| {
for i in 0..(line.chars().count() - 3) { for i in 0..(line.chars().count() - 3) {
let seq = &line[i..(i + 2)]; let seq = &line[i..(i + 2)];

View file

@ -61,8 +61,8 @@ impl FromStr for Date {
type Err = anyhow::Error; type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> { fn from_str(s: &str) -> Result<Self> {
let lbracket = s.find('[').context("`[` not found")?; let l_bracket = s.find('[').context("`[` not found")?;
let s = &s[(lbracket + 1)..]; let s = &s[(l_bracket + 1)..];
let dash = s.find('-').context("`-` not found")?; let dash = s.find('-').context("`-` not found")?;
let year = s[..dash].parse()?; let year = s[..dash].parse()?;
@ -79,9 +79,9 @@ impl FromStr for Date {
let hour = s[..colon].parse()?; let hour = s[..colon].parse()?;
let s = &s[(colon + 1)..]; let s = &s[(colon + 1)..];
let rbracket = s.find(']').context("`]` not found")?; let r_bracket = s.find(']').context("`]` not found")?;
let minute = s[..rbracket].parse()?; let minute = s[..r_bracket].parse()?;
Ok(Date { Ok(Date {
year, year,

View file

@ -20,7 +20,7 @@ fn fuel_needed(module_weight: u64) -> u64 {
fn part1(input: &str) -> Result<u64> { fn part1(input: &str) -> Result<u64> {
input input
.lines() .lines()
.map(|line| line.parse::<u64>()) .map(str::parse)
.map(|w| w.map(fuel_needed).map_err(anyhow::Error::new)) .map(|w| w.map(fuel_needed).map_err(anyhow::Error::new))
.sum() .sum()
} }
@ -40,7 +40,7 @@ fn cumulated_fuel_needed(module_weight: u64) -> u64 {
fn part2(input: &str) -> Result<u64> { fn part2(input: &str) -> Result<u64> {
input input
.lines() .lines()
.map(|line| line.parse::<u64>()) .map(str::parse)
.map(|w| w.map(cumulated_fuel_needed).map_err(anyhow::Error::new)) .map(|w| w.map(cumulated_fuel_needed).map_err(anyhow::Error::new))
.sum() .sum()
} }

View file

@ -33,9 +33,8 @@ fn part1(first_wire: &Wire, second_wire: &Wire) -> Result<u64> {
}) })
.filter_map(|(f, s)| match f.intersection(s) { .filter_map(|(f, s)| match f.intersection(s) {
Some(Point { x: 0, y: 0 }) | None => None, Some(Point { x: 0, y: 0 }) | None => None,
Some(p) => Some(p), Some(p) => Some(manhattan_distance(&p, &Point { x: 0, y: 0 })),
}) })
.map(|inter| manhattan_distance(&inter, &Point { x: 0, y: 0 }))
.min() .min()
.context("wire was empty") .context("wire was empty")
} }
@ -45,10 +44,10 @@ fn part2(first_wire: &Wire, second_wire: &Wire) -> Result<u64> {
let mut first_length = 0; let mut first_length = 0;
for seg1 in first_wire.0.iter() { for seg1 in &first_wire.0 {
let mut second_length = 0; let mut second_length = 0;
for seg2 in second_wire.0.iter() { for seg2 in &second_wire.0 {
if let Some(inter) = seg1.intersection(&seg2) { if let Some(inter) = seg1.intersection(&seg2) {
if inter.x == 0 && inter.y == 0 { if inter.x == 0 && inter.y == 0 {
continue; continue;

View file

@ -37,7 +37,7 @@ fn count_orbits(
fn part1(input: &str) -> Result<u64> { fn part1(input: &str) -> Result<u64> {
let orbits = input let orbits = input
.lines() .lines()
.map(|line| line.trim_end()) .map(str::trim_end)
.map(|line| { .map(|line| {
let paren = line let paren = line
.find(')') .find(')')
@ -56,7 +56,7 @@ fn part1(input: &str) -> Result<u64> {
fn part2(input: &str) -> Result<usize> { fn part2(input: &str) -> Result<usize> {
let orbits = input let orbits = input
.lines() .lines()
.map(|line| line.trim_end()) .map(str::trim_end)
.map(|line| { .map(|line| {
let paren = line let paren = line
.find(')') .find(')')

View file

@ -48,7 +48,7 @@ fn part1(input: &str) -> Result<i64> {
let mut res = 0; let mut res = 0;
for combination in combinations { for combination in combinations {
let mut output = 0; let mut output = 0;
for phase in combination.iter() { for phase in &combination {
let mut intcode = Intcode::with_memory(memory.clone()); let mut intcode = Intcode::with_memory(memory.clone());
intcode.add_input(*phase); intcode.add_input(*phase);
@ -95,7 +95,7 @@ fn part2(input: &str) -> Result<i64> {
intcode.run_and_wait()?; intcode.run_and_wait()?;
for out in intcode.output.iter() { for out in &intcode.output {
next.add_input(*out); next.add_input(*out);
} }
intcode.output.clear(); intcode.output.clear();
@ -116,7 +116,7 @@ fn part2(input: &str) -> Result<i64> {
None => bail!("last amplifier halted without output"), None => bail!("last amplifier halted without output"),
}; };
} else { } else {
for out in last.output.iter() { for out in &last.output {
first.add_input(*out); first.add_input(*out);
} }
last.output.clear(); last.output.clear();

View file

@ -96,7 +96,7 @@ impl FromStr for Image {
let mut result = vec![vec![2; IMG_WIDTH]; IMG_HEIGHT]; let mut result = vec![vec![2; IMG_WIDTH]; IMG_HEIGHT];
// overlap layers // overlap layers
for layer in layers.iter() { for layer in &layers {
for (src_row, dst_row) in layer.pixels.iter().zip(result.iter_mut()) { for (src_row, dst_row) in layer.pixels.iter().zip(result.iter_mut()) {
for (src_pixel, dst_pixel) in src_row.iter().zip(dst_row.iter_mut()) { for (src_pixel, dst_pixel) in src_row.iter().zip(dst_row.iter_mut()) {
if let 2 = *dst_pixel { if let 2 = *dst_pixel {

View file

@ -48,10 +48,10 @@ fn part1(input: &str) -> Result<usize> {
} }
let mut best = None; let mut best = None;
for a in asteroids.iter() { for a in &asteroids {
let mut set = HashSet::new(); let mut set = HashSet::new();
for b in asteroids.iter() { for b in &asteroids {
if a == b { if a == b {
continue; continue;
} }

View file

@ -40,7 +40,7 @@ fn generate_pairs(n: usize) -> Vec<(usize, usize)> {
} }
fn parse_planets(input: &str) -> Result<Vec<Planet>> { fn parse_planets(input: &str) -> Result<Vec<Planet>> {
input.lines().map(|l| l.parse()).collect() input.lines().map(str::parse).collect()
} }
fn part1(mut planets: Vec<Planet>, steps: usize) -> Result<u64> { fn part1(mut planets: Vec<Planet>, steps: usize) -> Result<u64> {
@ -91,12 +91,12 @@ fn part1(mut planets: Vec<Planet>, steps: usize) -> Result<u64> {
} }
// update position // update position
for planet in planets.iter_mut() { for planet in &mut planets {
planet.update_pos(); planet.update_pos();
} }
} }
Ok(planets.iter().map(|p| p.total_energy()).sum()) Ok(planets.iter().map(Planet::total_energy).sum())
} }
fn gcd(a: usize, b: usize) -> usize { fn gcd(a: usize, b: usize) -> usize {
@ -165,7 +165,7 @@ fn part2(mut planets: Vec<Planet>) -> Result<usize> {
} }
// update position // update position
for planet in planets.iter_mut() { for planet in &mut planets {
planet.update_pos(); planet.update_pos();
} }

View file

@ -79,7 +79,7 @@ fn get_ore_cost(
let needed = quantity - in_stock; let needed = quantity - in_stock;
let num_reactions = (needed + recipe.produced - 1) / recipe.produced; let num_reactions = (needed + recipe.produced - 1) / recipe.produced;
for elem in recipe.elems.iter() { for elem in &recipe.elems {
total += get_ore_cost( total += get_ore_cost(
elem.name.clone(), elem.name.clone(),
elem.amount * num_reactions, elem.amount * num_reactions,

View file

@ -203,10 +203,10 @@ impl Intcode {
bail!("dst must be a valid address: {}", dst); bail!("dst must be a valid address: {}", dst);
} }
if val != 0 { if val == 0 {
self.ip = dst as usize;
} else {
self.ip += 3; self.ip += 3;
} else {
self.ip = dst as usize;
} }
} }
Opcode::JumpFalse(test, dst) => { Opcode::JumpFalse(test, dst) => {

View file

@ -92,7 +92,7 @@ pub fn run() -> Result<String> {
fn part1(input: &str) -> Result<usize> { fn part1(input: &str) -> Result<usize> {
let policies = input let policies = input
.lines() .lines()
.map(|line| line.parse::<PassPolicy>()) .map(str::parse::<PassPolicy>)
.collect::<Result<Vec<PassPolicy>>>()?; .collect::<Result<Vec<PassPolicy>>>()?;
Ok(policies Ok(policies
@ -104,7 +104,7 @@ fn part1(input: &str) -> Result<usize> {
fn part2(input: &str) -> Result<usize> { fn part2(input: &str) -> Result<usize> {
let policies = input let policies = input
.lines() .lines()
.map(|line| line.parse::<PassPolicy>()) .map(str::parse::<PassPolicy>)
.collect::<Result<Vec<PassPolicy>>>()?; .collect::<Result<Vec<PassPolicy>>>()?;
Ok(policies Ok(policies

View file

@ -48,8 +48,8 @@ fn part2(input: &str) -> Result<usize> {
Ok(passports Ok(passports
.into_iter() .into_iter()
.filter_map(|p| p.complete()) .filter_map(Passport::complete)
.filter(|p| p.is_valid()) .filter(CompletePassport::is_valid)
.count()) .count())
} }

View file

@ -17,12 +17,12 @@ pub fn run() -> Result<String> {
fn part1(input: &str) -> Result<usize> { fn part1(input: &str) -> Result<usize> {
let seats = input let seats = input
.lines() .lines()
.map(|line| line.parse()) .map(str::parse)
.collect::<Result<Vec<Seat>>>()?; .collect::<Result<Vec<Seat>>>()?;
seats seats
.iter() .iter()
.map(|seat| seat.id()) .map(Seat::id)
.max() .max()
.context("0 seats processed") .context("0 seats processed")
} }
@ -30,7 +30,7 @@ fn part1(input: &str) -> Result<usize> {
fn part2(input: &str) -> Result<usize> { fn part2(input: &str) -> Result<usize> {
let mut seats = input let mut seats = input
.lines() .lines()
.map(|line| line.parse()) .map(str::parse)
.collect::<Result<Vec<Seat>>>()?; .collect::<Result<Vec<Seat>>>()?;
// Seats will be sorted by lexicographical order of fields thanks to `derive(PartialOrd, Ord)`, // Seats will be sorted by lexicographical order of fields thanks to `derive(PartialOrd, Ord)`,
@ -39,7 +39,7 @@ fn part2(input: &str) -> Result<usize> {
seats.sort_unstable(); seats.sort_unstable();
let mut prev_id = None; let mut prev_id = None;
for id in seats.iter().map(|s| s.id()) { for id in seats.iter().map(Seat::id) {
match prev_id { match prev_id {
Some(pid) if pid == (id - 1) => prev_id = Some(id), Some(pid) if pid == (id - 1) => prev_id = Some(id),
Some(pid) => return Ok(pid + 1), Some(pid) => return Ok(pid + 1),

View file

@ -18,7 +18,7 @@ pub fn run() -> Result<String> {
fn part1(input: &str) -> Result<usize> { fn part1(input: &str) -> Result<usize> {
let bag_rules = input let bag_rules = input
.lines() .lines()
.map(|line| line.parse()) .map(str::parse)
.collect::<Result<Vec<BagRule>>>() .collect::<Result<Vec<BagRule>>>()
.unwrap(); .unwrap();
@ -42,7 +42,7 @@ fn part1(input: &str) -> Result<usize> {
fn part2(input: &str) -> Result<usize> { fn part2(input: &str) -> Result<usize> {
let bag_rules = input let bag_rules = input
.lines() .lines()
.map(|line| line.parse()) .map(str::parse)
.collect::<Result<Vec<BagRule>>>() .collect::<Result<Vec<BagRule>>>()
.unwrap(); .unwrap();
@ -168,7 +168,7 @@ mod tests {
fn part1_provided_parse() { fn part1_provided_parse() {
let bag_rules = PROVIDED1 let bag_rules = PROVIDED1
.lines() .lines()
.map(|line| line.parse()) .map(str::parse)
.collect::<Result<Vec<BagRule>>>() .collect::<Result<Vec<BagRule>>>()
.unwrap(); .unwrap();

View file

@ -17,7 +17,7 @@ pub fn run() -> Result<String> {
fn part1(input: &str) -> Result<i64> { fn part1(input: &str) -> Result<i64> {
let instructions = input let instructions = input
.lines() .lines()
.map(|line| line.parse()) .map(str::parse)
.collect::<Result<Vec<Instruction>>>()?; .collect::<Result<Vec<Instruction>>>()?;
let mut interpreter = Interpreter::new(instructions); let mut interpreter = Interpreter::new(instructions);
@ -31,7 +31,7 @@ fn part1(input: &str) -> Result<i64> {
fn part2(input: &str) -> Result<i64> { fn part2(input: &str) -> Result<i64> {
let instructions = input let instructions = input
.lines() .lines()
.map(|line| line.parse()) .map(str::parse)
.collect::<Result<Vec<Instruction>>>()?; .collect::<Result<Vec<Instruction>>>()?;
for idx in 0..instructions.len() { for idx in 0..instructions.len() {

View file

@ -14,10 +14,7 @@ pub fn run() -> Result<String> {
} }
fn part1(input: &str) -> Result<i64> { fn part1(input: &str) -> Result<i64> {
let actions: Vec<Action> = input let actions: Vec<Action> = input.lines().map(str::parse).collect::<Result<_>>()?;
.lines()
.map(|line| line.parse())
.collect::<Result<_>>()?;
let mut ship = Ship::new(); let mut ship = Ship::new();
@ -29,10 +26,7 @@ fn part1(input: &str) -> Result<i64> {
} }
fn part2(input: &str) -> Result<i64> { fn part2(input: &str) -> Result<i64> {
let actions: Vec<Action> = input let actions: Vec<Action> = input.lines().map(str::parse).collect::<Result<_>>()?;
.lines()
.map(|line| line.parse())
.collect::<Result<_>>()?;
let mut ship = Ship::new(); let mut ship = Ship::new();
@ -212,7 +206,7 @@ impl Ship {
} }
ActionKind::Forward => { ActionKind::Forward => {
for mv in self.waypoint.as_moves(action.arg).iter() { for mv in &self.waypoint.as_moves(action.arg) {
self.process(mv); self.process(mv);
} }
} }

View file

@ -294,7 +294,7 @@ impl std::str::FromStr for Program {
type Err = anyhow::Error; type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> { fn from_str(s: &str) -> Result<Self> {
let instructions = s.lines().map(|line| line.parse()).collect::<Result<_>>()?; let instructions = s.lines().map(str::parse).collect::<Result<_>>()?;
Ok(Program { Ok(Program {
instructions, instructions,

View file

@ -120,13 +120,13 @@ fn parse_input(input: &str) -> Result<(HashMap<&str, Field>, Ticket, Vec<Ticket>
let my_ticket = my_ticket_part let my_ticket = my_ticket_part
.lines() .lines()
.skip(1) .skip(1)
.map(|line| line.parse()) .map(str::parse)
.next() .next()
.context("no second line for ticket")??; .context("no second line for ticket")??;
let tickets = tickets_part let tickets = tickets_part
.lines() .lines()
.skip(1) .skip(1)
.map(|line| line.parse()) .map(str::parse)
.collect::<Result<_>>() .collect::<Result<_>>()
.context("couldn't parse tickets")?; .context("couldn't parse tickets")?;
@ -184,16 +184,19 @@ impl std::str::FromStr for Field {
fn from_str(s: &str) -> Result<Self> { fn from_str(s: &str) -> Result<Self> {
let mut ranges = s.split(" or "); let mut ranges = s.split(" or ");
let mut range1 = ranges.next().context("no first range found")?.split('-'); let mut first_range = ranges.next().context("no first range found")?.split('-');
let range1_start = range1.next().context("no bound for range")?.parse()?; let first_range_start = first_range.next().context("no bound for range")?.parse()?;
let range1_end = range1.next().context("no bound for range")?.parse()?; let first_range_end = first_range.next().context("no bound for range")?.parse()?;
let mut range2 = ranges.next().context("no second range found")?.split('-'); let mut second_range = ranges.next().context("no second range found")?.split('-');
let range2_start = range2.next().context("no bound for range")?.parse()?; let second_range_start = second_range.next().context("no bound for range")?.parse()?;
let range2_end = range2.next().context("no bound for range")?.parse()?; let second_range_end = second_range.next().context("no bound for range")?.parse()?;
Ok(Field { Ok(Field {
ranges: (range1_start..=range1_end, range2_start..=range2_end), ranges: (
first_range_start..=first_range_end,
second_range_start..=second_range_end,
),
}) })
} }
} }