From 73b9d2ff3b4d9f84ecd9a60f35f07f6159b66bbd Mon Sep 17 00:00:00 2001 From: Colin Walters Date: Fri, 30 Apr 2021 09:18:14 -0400 Subject: [PATCH] treefile: Minor cleanup of handle_repo_packages_overrides() This isn't important at all, but I am just trying to up my "Rust iterator and mapping" skills. Here: - In this case we always want to go from `Option` to `Option`, so instead of destructuring `Some()` back to another `Some()` we can use `as_mut()` to manipulate the inner vector directly. - Now instead of destroying the inner `Vec<>` we need to use `drain()` instead - And then we can just `extend()` with a reversed iterator from our explicit temporary --- rust/src/treefile.rs | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/rust/src/treefile.rs b/rust/src/treefile.rs index 95e37d9d..e872430f 100644 --- a/rust/src/treefile.rs +++ b/rust/src/treefile.rs @@ -1306,24 +1306,23 @@ impl TreeComposeConfig { // we need to ensure that appended repo packages override earlier ones fn handle_repo_packages_overrides(&mut self) { - if let Some(repo_packages) = self.repo_packages.take() { + self.repo_packages.as_mut().map(|repo_packages| { let mut seen_pkgs: HashSet = HashSet::new(); - self.repo_packages = Some({ - let mut v: Vec = repo_packages - .into_iter() - .rev() - .map(|mut rp| { - rp.packages.retain(|p| seen_pkgs.insert(p.into())); - rp - }) - .filter(|rp| !rp.packages.is_empty()) - .collect(); - // can't inline this in the iterator chain above: - // https://doc.rust-lang.org/std/iter/struct.Map.html#notes-about-side-effects - v.reverse(); - v - }); - } + // Create a temporary new filtered vec; see + // https://doc.rust-lang.org/std/iter/struct.Map.html#notes-about-side-effects for why + // the reverse and re-reverse due to the side effect during `map()`. + let v: Vec<_> = repo_packages + .drain(..) + .rev() + .map(|mut rp| { + rp.packages.retain(|p| seen_pkgs.insert(p.into())); + rp + }) + .filter(|rp| !rp.packages.is_empty()) + .collect(); + // Now replace the original, re-reversing. + repo_packages.extend(v.into_iter().rev()); + }); } }