From 47d455620e518aa9cf74b123dd6e93ec7a7aa911 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fabian=20L=C3=B6schner?= Date: Wed, 5 Feb 2025 17:12:00 +0100 Subject: [PATCH] Apply clippy --fix --- splashsurf/src/allocator.rs | 2 +- splashsurf/src/convert.rs | 12 ++- splashsurf/src/io.rs | 26 +++--- splashsurf/src/logging.rs | 12 +-- splashsurf/src/main.rs | 2 +- splashsurf/src/reconstruction.rs | 33 +++---- .../benches/benches/bench_neighborhood.rs | 12 +-- .../benches/benches/bench_subdomain_grid.rs | 6 +- splashsurf_lib/examples/minimal_levelset.rs | 2 +- splashsurf_lib/src/aabb.rs | 6 +- splashsurf_lib/src/dense_subdomains.rs | 87 +++++++++---------- splashsurf_lib/src/density_map.rs | 8 +- splashsurf_lib/src/generic_tree.rs | 8 +- splashsurf_lib/src/halfedge_mesh.rs | 26 +++--- splashsurf_lib/src/io.rs | 12 +-- splashsurf_lib/src/io/bgeo_format.rs | 22 +++-- splashsurf_lib/src/io/obj_format.rs | 15 ++-- splashsurf_lib/src/io/ply_format.rs | 38 ++++---- splashsurf_lib/src/io/vtk_format.rs | 23 +++-- splashsurf_lib/src/io/xyz_format.rs | 4 +- splashsurf_lib/src/kernel.rs | 4 +- splashsurf_lib/src/lib.rs | 4 +- splashsurf_lib/src/marching_cubes.rs | 14 ++- .../src/marching_cubes/marching_cubes_lut.rs | 7 +- .../marching_cubes/narrow_band_extraction.rs | 10 +-- .../src/marching_cubes/triangulation.rs | 2 +- splashsurf_lib/src/mesh.rs | 35 ++++---- splashsurf_lib/src/neighborhood_search.rs | 18 ++-- splashsurf_lib/src/postprocessing.rs | 57 +++++------- splashsurf_lib/src/profiling.rs | 7 +- splashsurf_lib/src/reconstruction.rs | 22 ++--- splashsurf_lib/src/sph_interpolation.rs | 7 +- splashsurf_lib/src/uniform_grid.rs | 43 +++++---- splashsurf_lib/src/utils.rs | 8 +- 34 files changed, 273 insertions(+), 321 deletions(-) diff --git a/splashsurf/src/allocator.rs b/splashsurf/src/allocator.rs index 5028f22..37cfe04 100644 --- a/splashsurf/src/allocator.rs +++ b/splashsurf/src/allocator.rs @@ -21,7 +21,7 @@ unsafe impl GlobalAlloc for CountingAllocator { self.peak_allocation .fetch_max(current_allocation, Ordering::AcqRel); } - return ret; + ret } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { diff --git a/splashsurf/src/convert.rs b/splashsurf/src/convert.rs index a654e9d..a07aa36 100644 --- a/splashsurf/src/convert.rs +++ b/splashsurf/src/convert.rs @@ -136,13 +136,11 @@ fn convert_mesh(cmd_args: &ConvertSubcommandArgs) -> Result<(), anyhow::Error> { /// Returns an error if the file already exists but overwrite is disabled fn overwrite_check(cmd_args: &ConvertSubcommandArgs) -> Result<(), anyhow::Error> { - if !cmd_args.overwrite { - if cmd_args.output_file.exists() { - return Err(anyhow!( - "Aborting: Output file \"{}\" already exists. Use overwrite flag to ignore this.", - cmd_args.output_file.display() - )); - } + if !cmd_args.overwrite && cmd_args.output_file.exists() { + return Err(anyhow!( + "Aborting: Output file \"{}\" already exists. Use overwrite flag to ignore this.", + cmd_args.output_file.display() + )); } Ok(()) diff --git a/splashsurf/src/io.rs b/splashsurf/src/io.rs index 701db45..57d5e51 100644 --- a/splashsurf/src/io.rs +++ b/splashsurf/src/io.rs @@ -22,15 +22,9 @@ pub struct FormatParameters { } /// File format parameters for input files -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] pub struct InputFormatParameters {} -impl Default for InputFormatParameters { - fn default() -> Self { - Self {} - } -} - /// File format parameters for output files #[derive(Clone, Debug)] pub struct OutputFormatParameters { @@ -107,7 +101,7 @@ pub fn read_particle_positions_with_attributes>( let vtk_pieces = VtkFile::load_file(input_file) .map(|f| f.into_pieces()) - .with_context(|| format!("Failed to load particle positions from file"))?; + .with_context(|| "Failed to load particle positions from file".to_string())?; if vtk_pieces.len() > 1 { warn!("VTK file contains more than one \"piece\". Only the first one will be loaded."); @@ -176,13 +170,13 @@ pub fn write_particle_positions>( .ok_or(anyhow!("Invalid extension of output file"))?; match extension.to_lowercase().as_str() { - "vtk" => vtk_format::particles_to_vtk(particles, &output_file), + "vtk" => vtk_format::particles_to_vtk(particles, output_file), "bgeo" => bgeo_format::particles_to_bgeo( particles, - &output_file, + output_file, format_params.enable_compression, ), - "json" => json_format::particles_to_json(particles, &output_file), + "json" => json_format::particles_to_json(particles, output_file), _ => Err(anyhow!( "Unsupported file format extension \"{}\" for writing particles", extension @@ -214,8 +208,8 @@ pub fn read_surface_mesh>( .ok_or(anyhow!("Invalid extension of input file"))?; match extension.to_lowercase().as_str() { - "vtk" => vtk_format::surface_mesh_from_vtk(&input_file), - "ply" => ply_format::surface_mesh_from_ply(&input_file), + "vtk" => vtk_format::surface_mesh_from_vtk(input_file), + "ply" => ply_format::surface_mesh_from_ply(input_file), _ => Err(anyhow!( "Unsupported file format extension \"{}\" for reading surface meshes", extension @@ -261,9 +255,9 @@ where .ok_or(anyhow!("Invalid extension of output file"))?; match extension.to_lowercase().as_str() { - "vtk" => vtk_format::write_vtk(mesh, &output_file, "mesh"), - "ply" => ply_format::mesh_to_ply(mesh, &output_file), - "obj" => obj_format::mesh_to_obj(mesh, &output_file), + "vtk" => vtk_format::write_vtk(mesh, output_file, "mesh"), + "ply" => ply_format::mesh_to_ply(mesh, output_file), + "obj" => obj_format::mesh_to_obj(mesh, output_file), _ => Err(anyhow!( "Unsupported file format extension \"{}\"", extension, diff --git a/splashsurf/src/logging.rs b/splashsurf/src/logging.rs index 030cec5..47aeabc 100644 --- a/splashsurf/src/logging.rs +++ b/splashsurf/src/logging.rs @@ -22,15 +22,15 @@ impl ProgressHandler { fn handle R, R>(&mut self, inner_function: F) -> R { let handle = get_progress_bar(); - return match handle { - Some(pb) => pb.suspend(|| return inner_function(self)), + match handle { + Some(pb) => pb.suspend(|| inner_function(self)), None => inner_function(self), - }; + } } /// Create a new instance of "Self" pub fn new(pipe: T) -> Self { - return Self(pipe); + Self(pipe) } } @@ -44,12 +44,12 @@ impl ProgressHandler { impl Write for ProgressHandler { #[inline] fn write(&mut self, buf: &[u8]) -> std::io::Result { - return self.handle(|this| this.0.write(buf)); + self.handle(|this| this.0.write(buf)) } #[inline] fn flush(&mut self) -> std::io::Result<()> { - return self.handle(|this| this.0.flush()); + self.handle(|this| this.0.flush()) } } diff --git a/splashsurf/src/main.rs b/splashsurf/src/main.rs index 73541fc..4e8e1c2 100644 --- a/splashsurf/src/main.rs +++ b/splashsurf/src/main.rs @@ -97,7 +97,7 @@ fn run_splashsurf() -> Result<(), anyhow::Error> { splashsurf_lib::profiling::write_to_string() .unwrap() .split("\n") - .filter(|l| l.len() > 0) + .filter(|l| !l.is_empty()) .for_each(|l| info!("{}", l)); // Print memory stats if available diff --git a/splashsurf/src/reconstruction.rs b/splashsurf/src/reconstruction.rs index cc7129b..6a5bd8a 100644 --- a/splashsurf/src/reconstruction.rs +++ b/splashsurf/src/reconstruction.rs @@ -375,27 +375,30 @@ pub fn reconstruct_subcommand(cmd_args: &ReconstructSubcommandArgs) -> Result<() path.input_file.display() ) }) - .map_err(|err| { + .inspect_err(|err| { // Already log the error in case there are multiple errors - logging::log_error(&err); - err + logging::log_error(err); }) - .and_then(|_| { - logging::get_progress_bar().map(|pb| pb.inc(1)); - Ok(()) + .map(|_| { + if let Some(pb) = logging::get_progress_bar() { + pb.inc(1) + } }) }) } else { paths.iter().try_for_each(|path| { - reconstruction_pipeline(path, &args).and_then(|_| { - logging::get_progress_bar().map(|pb| pb.inc(1)); - Ok(()) + reconstruction_pipeline(path, &args).map(|_| { + if let Some(pb) = logging::get_progress_bar() { + pb.inc(1) + } }) }) }; if paths.len() > 1 { - logging::get_progress_bar().map(|pb| pb.finish()); + if let Some(pb) = logging::get_progress_bar() { + pb.finish() + } logging::set_progress_bar(None); } @@ -922,7 +925,7 @@ pub(crate) fn reconstruction_pipeline_generic( .parent() // Add a trailing separator if the parent is non-empty .map(|p| p.join("")) - .unwrap_or_else(PathBuf::new); + .unwrap_or_default(); let output_filename = format!( "raw_{}", paths.output_file.file_name().unwrap().to_string_lossy() @@ -1028,7 +1031,7 @@ pub(crate) fn reconstruction_pipeline_generic( // Global neighborhood search let nl = reconstruction .particle_neighbors() - .map(|nl| Cow::Borrowed(nl)) + .map(Cow::Borrowed) .unwrap_or_else(|| { let search_radius = params.compact_support_radius; @@ -1059,8 +1062,8 @@ pub(crate) fn reconstruction_pipeline_generic( .map(|j| { let dist = (particle_positions[i] - particle_positions[j]).norm_squared(); - let weight = R::one() - (dist / squared_r).clamp(R::zero(), R::one()); - return weight; + + R::one() - (dist / squared_r).clamp(R::zero(), R::one()) }) .fold(R::zero(), R::add) }) @@ -1073,7 +1076,7 @@ pub(crate) fn reconstruction_pipeline_generic( .expect("interpolator is required") .interpolate_scalar_quantity( weighted_ncounts.as_slice(), - &mesh_with_data.vertices(), + mesh_with_data.vertices(), true, ) }; diff --git a/splashsurf_lib/benches/benches/bench_neighborhood.rs b/splashsurf_lib/benches/benches/bench_neighborhood.rs index b937bda..25a74bd 100644 --- a/splashsurf_lib/benches/benches/bench_neighborhood.rs +++ b/splashsurf_lib/benches/benches/bench_neighborhood.rs @@ -10,13 +10,13 @@ static COMPACT_SUPPORT_RADIUS: f64 = 4.0 * PARTICLE_RADIUS; //static NUM_PARTICLES: Option = Some(800); static NUM_PARTICLES: Option = None; -static PARTICLE_FILE: &'static str = "../data/bunny_frame_14_7705_particles.vtk"; +static PARTICLE_FILE: &str = "../data/bunny_frame_14_7705_particles.vtk"; fn particle_subset(particle_positions: &[Vector3]) -> &[Vector3] { - if let Some(n_particles) = NUM_PARTICLES.clone() { + if let Some(n_particles) = NUM_PARTICLES { &particle_positions[0..n_particles] } else { - &particle_positions[..] + particle_positions } } @@ -35,7 +35,7 @@ pub fn neighborhood_search_naive(c: &mut Criterion) { b.iter(|| { neighborhood_lists.clear(); neighborhood_search::neighborhood_search_naive( - &particle_positions, + particle_positions, COMPACT_SUPPORT_RADIUS as f32, &mut neighborhood_lists, ); @@ -64,7 +64,7 @@ pub fn neighborhood_search_spatial_hashing(c: &mut Criterion) { neighborhood_lists.clear(); neighborhood_search::neighborhood_search_spatial_hashing::( &domain, - &particle_positions, + particle_positions, COMPACT_SUPPORT_RADIUS as f32, &mut neighborhood_lists, ); @@ -93,7 +93,7 @@ pub fn neighborhood_search_spatial_hashing_parallel(c: &mut Criterion) { neighborhood_lists.clear(); neighborhood_search::neighborhood_search_spatial_hashing_parallel::( &domain, - &particle_positions, + particle_positions, COMPACT_SUPPORT_RADIUS as f32, &mut neighborhood_lists, ); diff --git a/splashsurf_lib/benches/benches/bench_subdomain_grid.rs b/splashsurf_lib/benches/benches/bench_subdomain_grid.rs index 7b0180e..2e3db9d 100644 --- a/splashsurf_lib/benches/benches/bench_subdomain_grid.rs +++ b/splashsurf_lib/benches/benches/bench_subdomain_grid.rs @@ -12,7 +12,7 @@ fn parameters_canyon() -> Parameters { let compact_support_radius = 4.0 * particle_radius; let cube_size = 1.5 * particle_radius; - let parameters = Parameters { + Parameters { particle_radius, rest_density: 1000.0, compact_support_radius, @@ -27,9 +27,7 @@ fn parameters_canyon() -> Parameters { }, )), global_neighborhood_list: false, - }; - - parameters + } } pub fn grid_canyon(c: &mut Criterion) { diff --git a/splashsurf_lib/examples/minimal_levelset.rs b/splashsurf_lib/examples/minimal_levelset.rs index d605bf0..7e4f4b1 100644 --- a/splashsurf_lib/examples/minimal_levelset.rs +++ b/splashsurf_lib/examples/minimal_levelset.rs @@ -88,7 +88,7 @@ pub fn marching_cubes>( let vertex_index = *edge_to_vertex.entry(edge).or_insert_with(|| { let vertex_index = vertices.len(); - let origin_coords = grid.point_coordinates(&edge.origin()); + let origin_coords = grid.point_coordinates(edge.origin()); let target_coords = grid.point_coordinates(&edge.target()); let origin_value = level_set.evaluate(&origin_coords); diff --git a/splashsurf_lib/src/aabb.rs b/splashsurf_lib/src/aabb.rs index 18db882..b5ec7e5 100644 --- a/splashsurf_lib/src/aabb.rs +++ b/splashsurf_lib/src/aabb.rs @@ -30,9 +30,9 @@ where if points.is_empty() { Self::zeros() } else if points.len() == 1 { - Self::from_point(points[0].clone()) + Self::from_point(points[0]) } else { - let initial_aabb = Self::from_point(points[0].clone()); + let initial_aabb = Self::from_point(points[0]); points[1..] .par_iter() .fold( @@ -73,7 +73,7 @@ where #[inline(always)] pub fn from_point(point: SVector) -> Self { Self { - min: point.clone(), + min: point, max: point, } } diff --git a/splashsurf_lib/src/dense_subdomains.rs b/splashsurf_lib/src/dense_subdomains.rs index b82c40c..e459a34 100644 --- a/splashsurf_lib/src/dense_subdomains.rs +++ b/splashsurf_lib/src/dense_subdomains.rs @@ -101,10 +101,10 @@ pub(crate) struct Subdomains { per_subdomain_particles: Vec>, } -pub(crate) fn initialize_parameters<'a, I: Index, R: Real>( +pub(crate) fn initialize_parameters( parameters: &Parameters, _particles: &[Vector3], - output_surface: &'a SurfaceReconstruction, + output_surface: &SurfaceReconstruction, ) -> Result, anyhow::Error> { let chunk_size = 500; @@ -199,7 +199,7 @@ pub(crate) fn initialize_parameters<'a, I: Index, R: Real>( .context("compute global number of marching cubes cells per dimension")?; let global_mc_grid = UniformCartesianCubeGrid3d::::new( - &global_mc_grid.aabb().min(), + global_mc_grid.aabb().min(), &num_global_mc_cells, cube_size, ) @@ -225,7 +225,7 @@ pub(crate) fn initialize_parameters<'a, I: Index, R: Real>( let subdomain_size = cube_size * subdomain_cubes.to_real_unchecked(); // Background grid of the subdomains let subdomain_grid = UniformCartesianCubeGrid3d::::new( - &global_mc_grid.aabb().min(), + global_mc_grid.aabb().min(), &num_subdomains, subdomain_size, )?; @@ -275,7 +275,7 @@ pub(crate) fn extract_narrow_band( // AABB of the particles let aabb = { - let mut aabb = Aabb3d::::par_from_points(&particles); + let mut aabb = Aabb3d::::par_from_points(particles); // Add some safety margin, this should be large enough such that all mesh vertices are guaranteed to be inside of it aabb.grow_uniformly(ghost_particle_margin); info!("Enlarged AABB: {:?}", aabb); @@ -287,7 +287,7 @@ pub(crate) fn extract_narrow_band( let mut neighbors = Vec::new(); neighborhood_search_spatial_hashing_parallel::( &aabb, - &particles, + particles, compact_support_radius, &mut neighbors, ); @@ -312,8 +312,7 @@ pub(crate) fn extract_narrow_band( let mut first_ring = surface_particles .iter() .copied() - .map(|i| neighbor_lists[i].iter().copied()) - .flatten() + .flat_map(|i| neighbor_lists[i].iter().copied()) .collect::>(); info!("First ring before dedup: {}", first_ring.len()); { @@ -326,8 +325,7 @@ pub(crate) fn extract_narrow_band( let mut second_ring = first_ring .iter() .copied() - .map(|i| neighbor_lists[i].iter().copied()) - .flatten() + .flat_map(|i| neighbor_lists[i].iter().copied()) .collect::>(); info!("Second ring before dedup: {}", second_ring.len()); { @@ -357,11 +355,11 @@ pub(crate) fn extract_narrow_band( { profile!("Collect narrow band positions"); - let narrow_band_positions = narrow_band + + narrow_band .into_iter() - .map(|i| particles[i].clone()) - .collect::>(); - narrow_band_positions + .map(|i| particles[i]) + .collect::>() } } @@ -596,14 +594,14 @@ pub(crate) fn compute_global_densities_and_neighbors( neighborhood_search_spatial_hashing_flat_filtered::( &margin_aabb, - &subdomain_particles, + subdomain_particles, parameters.compact_support_radius, neighborhood_lists, |i| is_inside[i], ); sequential_compute_particle_densities_filtered::( - &subdomain_particles, + subdomain_particles, neighborhood_lists, parameters.compact_support_radius, parameters.particle_rest_mass, @@ -762,15 +760,15 @@ pub(crate) fn reconstruction( if !is_max[0] && !is_max[1] { // Edge is already in the correct subdomain - (subdomain_index, local_edge.clone()) + (subdomain_index, *local_edge) } else { // We have to translate to the neighboring subdomain (+1 in all directions where is_max == true) let subdomain_cell = subdomain_grid .try_unflatten_cell_index(subdomain_index) .expect("invalid subdomain index"); - let mut target_subdomain_ijk = subdomain_cell.index().clone(); - let mut target_local_origin_ijk = local_edge.origin().index().clone(); + let mut target_subdomain_ijk = *subdomain_cell.index(); + let mut target_local_origin_ijk = *local_edge.origin().index(); // Obtain index of new subdomain and new origin point for (&orth_axis, &is_max) in local_edge @@ -932,8 +930,8 @@ pub(crate) fn reconstruction( // Use global coordinate calculation for consistency with neighboring domains let global_point_ijk = local_to_global_point_ijk( point_ijk, - subdomain_ijk.clone(), - mc_cells_per_subdomain.clone(), + *subdomain_ijk, + *mc_cells_per_subdomain, ); let global_point = parameters .global_marching_cubes_grid @@ -1004,11 +1002,11 @@ pub(crate) fn reconstruction( let vertex_index = *edge_to_vertex.entry(edge).or_insert_with(|| { // TODO: Nonlinear interpolation - let origin_coords = mc_grid.point_coordinates(&edge.origin()); + let origin_coords = mc_grid.point_coordinates(edge.origin()); let target_coords = mc_grid.point_coordinates(&edge.target()); let flat_origin_idx = mc_grid - .flatten_point_index(&edge.origin()) + .flatten_point_index(edge.origin()) .to_usize() .unwrap(); let flat_target_idx = mc_grid @@ -1185,8 +1183,8 @@ pub(crate) fn reconstruction( // Use global coordinate calculation for consistency with neighboring domains let global_point_ijk = local_to_global_point_ijk( point_ijk, - subdomain_ijk.clone(), - mc_cells_per_subdomain.clone(), + *subdomain_ijk, + *mc_cells_per_subdomain, ); let global_point = parameters .global_marching_cubes_grid @@ -1271,11 +1269,11 @@ pub(crate) fn reconstruction( let vertex_index = *edge_to_vertex.entry(edge).or_insert_with(|| { // TODO: Nonlinear interpolation - let origin_coords = mc_grid.point_coordinates(&edge.origin()); + let origin_coords = mc_grid.point_coordinates(edge.origin()); let target_coords = mc_grid.point_coordinates(&edge.target()); let flat_origin_idx = mc_grid - .flatten_point_index(&edge.origin()) + .flatten_point_index(edge.origin()) .to_usize() .unwrap(); let flat_target_idx = mc_grid @@ -1460,22 +1458,18 @@ pub(crate) fn stitching( }) // For each exterior vertex there is a corresponding globalized edge index .zip(patch.exterior_vertex_edge_indices.iter()) - .enumerate() - .for_each( - |(_exterior_local_idx, ((old_local_idx, vert), edge_index))| { - let global_index = *exterior_vertex_mapping - .entry(edge_index.clone()) - .or_insert_with(|| { - // Exterior vertices will come after all interior vertices in the mesh - let global_index = total_interior_vert_count - + exterior_vertices.len(); - exterior_vertices.push(*vert); - global_index - }); - local_to_global_vertex_mapping[old_local_idx] = - global_index; - }, - ); + .for_each(|((old_local_idx, vert), edge_index)| { + let global_index = *exterior_vertex_mapping + .entry(*edge_index) + .or_insert_with(|| { + // Exterior vertices will come after all interior vertices in the mesh + let global_index = + total_interior_vert_count + exterior_vertices.len(); + exterior_vertices.push(*vert); + global_index + }); + local_to_global_vertex_mapping[old_local_idx] = global_index; + }); } // Insert exterior triangles @@ -1795,7 +1789,7 @@ pub(crate) mod debug { let subdomain_ijk = subdomain_grid .try_unflatten_cell_index(flat_subdomain_idx as I) .unwrap(); - let [i, j, k] = subdomain_ijk.index().clone(); + let [i, j, k] = *subdomain_ijk.index(); let vertex_offset = hexmesh.vertices.len(); @@ -1821,7 +1815,7 @@ pub(crate) mod debug { } hexmesh.cells.push([ - vertex_offset + 0, + vertex_offset, vertex_offset + 1, vertex_offset + 2, vertex_offset + 3, @@ -1881,8 +1875,7 @@ pub(crate) mod debug { } }); - let no_owned_particles_counter = no_owned_particles_counter.into_inner(); - no_owned_particles_counter + no_owned_particles_counter.into_inner() } } diff --git a/splashsurf_lib/src/density_map.rs b/splashsurf_lib/src/density_map.rs index 763c3b6..44742df 100644 --- a/splashsurf_lib/src/density_map.rs +++ b/splashsurf_lib/src/density_map.rs @@ -645,7 +645,7 @@ impl SparseDensityMapGenerator { let particle_volume = self.particle_rest_mass / particle_density; // TODO: Check performance with just using multiplication - let min_supported_point = grid.point_coordinates_array(&min_supported_point_ijk); + let min_supported_point = grid.point_coordinates_array(min_supported_point_ijk); // dx, dy, dz are the deltas of the supported points as seen from the current particle position let mut dx = min_supported_point[0] - particle[0] @@ -685,11 +685,11 @@ impl SparseDensityMapGenerator { .entry(flat_point_index) .or_insert(R::zero()) += density_contribution; } - k = k + I::one(); + k += I::one(); } - j = j + I::one(); + j += I::one(); } - i = i + I::one(); + i += I::one(); } } } diff --git a/splashsurf_lib/src/generic_tree.rs b/splashsurf_lib/src/generic_tree.rs index d383ead..d9ae0ab 100644 --- a/splashsurf_lib/src/generic_tree.rs +++ b/splashsurf_lib/src/generic_tree.rs @@ -39,12 +39,12 @@ pub trait TreeNodeMut: TreeNode { /// Trait for non-mutable sequential tree iteration algorithms. Automatically implemented for types that implement [`TreeNode`]. pub trait VisitableTree: TreeNode { /// An iterator over all nodes and its children in depth-first order. - fn dfs_iter<'a>(&'a self) -> DfsIter<'a, Self> { + fn dfs_iter(&self) -> DfsIter<'_, Self> { DfsIter::new(self) } /// An iterator over all nodes and its children in breadth-first order. - fn bfs_iter<'a>(&'a self) -> BfsIter<'a, Self> { + fn bfs_iter(&self) -> BfsIter<'_, Self> { BfsIter::new(self) } } @@ -110,7 +110,7 @@ impl<'a, T: TreeNode + ?Sized> Iterator for DfsIter<'a, T> { } } -impl<'a, T: TreeNode + ?Sized> FusedIterator for DfsIter<'a, T> {} +impl FusedIterator for DfsIter<'_, T> {} /// Breadth-first search iterator returned by the [`VisitableTree::bfs_iter`] function pub struct BfsIter<'a, T: ?Sized> { @@ -139,7 +139,7 @@ impl<'a, T: TreeNode + ?Sized> Iterator for BfsIter<'a, T> { } } -impl<'a, T: TreeNode + ?Sized> FusedIterator for BfsIter<'a, T> {} +impl FusedIterator for BfsIter<'_, T> {} /// Trait for non-mutable parallel tree visitation algorithms. Automatically implemented for types that implement [`TreeNode`] and [`ThreadSafe`](crate::ThreadSafe). pub trait ParVisitableTree: TreeNode { diff --git a/splashsurf_lib/src/halfedge_mesh.rs b/splashsurf_lib/src/halfedge_mesh.rs index 74bcde4..09dcb9a 100644 --- a/splashsurf_lib/src/halfedge_mesh.rs +++ b/splashsurf_lib/src/halfedge_mesh.rs @@ -108,7 +108,7 @@ impl HalfEdgeTriMesh { } /// Iterator over the one-ring vertex neighbors of the given vertex - pub fn vertex_one_ring<'a>(&'a self, vertex: usize) -> impl Iterator + 'a { + pub fn vertex_one_ring(&self, vertex: usize) -> impl Iterator + '_ { self.vertex_half_edge_map[vertex] .iter() .copied() @@ -116,15 +116,15 @@ impl HalfEdgeTriMesh { } /// Iterator over the outgoing half-edges of the given vertex - pub fn outgoing_half_edges<'a>(&'a self, vertex: usize) -> impl Iterator + 'a { + pub fn outgoing_half_edges(&self, vertex: usize) -> impl Iterator + '_ { self.vertex_half_edge_map[vertex] .iter() .copied() - .map(|he_i| self.half_edges[he_i].clone()) + .map(|he_i| self.half_edges[he_i]) } /// Iterator over all incident faces of the given vertex - pub fn incident_faces<'a>(&'a self, vertex: usize) -> impl Iterator + 'a { + pub fn incident_faces(&self, vertex: usize) -> impl Iterator + '_ { self.outgoing_half_edges(vertex).filter_map(|he| he.face) } @@ -137,7 +137,7 @@ impl HalfEdgeTriMesh { for &he_idx in from_edges { let he = &self.half_edges[he_idx]; if he.to == to { - return Some(he.clone()); + return Some(*he); } } @@ -146,7 +146,7 @@ impl HalfEdgeTriMesh { /// Returns whether the given half-edge or its opposite half-edge is a boundary edge pub fn is_boundary_edge(&self, half_edge: HalfEdge) -> bool { - return half_edge.is_boundary() || self.opposite(half_edge).is_boundary(); + half_edge.is_boundary() || self.opposite(half_edge).is_boundary() } /// Returns whether the given vertex is a boundary vertex @@ -241,10 +241,12 @@ impl HalfEdgeTriMesh { for &he in &self.vertex_half_edge_map[v0] { let he = &self.half_edges[he]; let vv = he.to; - if vv != v1 && Some(vv) != v_pos && Some(vv) != v_neg { - if let Some(_) = self.half_edge(vv, v1) { - return Err(IllegalHalfEdgeCollapse::IntersectionOfOneRing); - } + if vv != v1 + && Some(vv) != v_pos + && Some(vv) != v_neg + && self.half_edge(vv, v1).is_some() + { + return Err(IllegalHalfEdgeCollapse::IntersectionOfOneRing); } } @@ -320,13 +322,13 @@ impl HalfEdgeTriMesh { // Update the faces referencing the removed vertex for &he_idx in &conn_from { - self.half_edges[he_idx].face.map(|f| { + if let Some(f) = self.half_edges[he_idx].face { self.triangles[f].iter_mut().for_each(|i| { if *i == v_from { *i = v_to; } }) - }); + } } // Update the half-edges around the collapsed triangles (they become opposites) diff --git a/splashsurf_lib/src/io.rs b/splashsurf_lib/src/io.rs index 5d466f1..6cfd4c5 100644 --- a/splashsurf_lib/src/io.rs +++ b/splashsurf_lib/src/io.rs @@ -23,12 +23,12 @@ pub fn particles_from_file>( .ok_or(anyhow!("Invalid extension of input file"))?; match extension.to_lowercase().as_str() { - "vtk" => vtk_format::particles_from_vtk(&input_file), - "vtu" => vtk_format::particles_from_vtk(&input_file), - "xyz" => xyz_format::particles_from_xyz(&input_file), - "ply" => ply_format::particles_from_ply(&input_file), - "bgeo" => bgeo_format::particles_from_bgeo(&input_file), - "json" => json_format::particles_from_json(&input_file), + "vtk" => vtk_format::particles_from_vtk(input_file), + "vtu" => vtk_format::particles_from_vtk(input_file), + "xyz" => xyz_format::particles_from_xyz(input_file), + "ply" => ply_format::particles_from_ply(input_file), + "bgeo" => bgeo_format::particles_from_bgeo(input_file), + "json" => json_format::particles_from_json(input_file), _ => Err(anyhow!( "Unsupported file format extension \"{}\" for reading particles", extension diff --git a/splashsurf_lib/src/io/bgeo_format.rs b/splashsurf_lib/src/io/bgeo_format.rs index e27b8ff..bdbb206 100644 --- a/splashsurf_lib/src/io/bgeo_format.rs +++ b/splashsurf_lib/src/io/bgeo_format.rs @@ -109,7 +109,7 @@ pub fn particles_to_bgeo>( } fn particles_to_bgeo_impl(particles: &[Vector3]) -> Result { - let particles_f32 = particles.iter().map(|x| x.as_slice()).flatten().copied().map(|x| Some(x.to_f32())?) + let particles_f32 = particles.iter().flat_map(|x| x.as_slice()).copied().map(|x| Some(x.to_f32())?) .map(|vec| { vec.ok_or_else(|| { anyhow!("Failed to convert coordinate from input float type to f32, value out of range?") @@ -165,7 +165,7 @@ pub fn write_bgeo_file( // Write attribute definitions for attrib in &bgeo.attribute_definitions { - writer.write_all(&(attrib.name.as_bytes().len() as u16).to_be_bytes())?; + writer.write_all(&(attrib.name.len() as u16).to_be_bytes())?; writer.write_all(attrib.name.as_bytes())?; writer.write_all(&(attrib.size as u16).to_be_bytes())?; writer.write_all(&(attrib.attr_type.to_i32()).to_be_bytes())?; @@ -203,8 +203,8 @@ pub fn write_bgeo_file( } // End bytes - writer.write_all(&(0x00 as u8).to_be_bytes())?; - writer.write_all(&(0xff as u8).to_be_bytes())?; + writer.write_all(&0x00_u8.to_be_bytes())?; + writer.write_all(&0xff_u8.to_be_bytes())?; Ok(()) } @@ -505,12 +505,10 @@ mod parser { Ok((input, attr)) } - _ => { - return Err(make_bgeo_error( - input, - BgeoParserErrorKind::UnsupportedAttributeType(attr_type), - )); - } + _ => Err(make_bgeo_error( + input, + BgeoParserErrorKind::UnsupportedAttributeType(attr_type), + )), } } @@ -780,7 +778,7 @@ mod error { for (_, kind) in self.backtrace.iter().skip(1) { err = err.context(format!("{:?}", kind)); } - return err; + err } else { anyhow!("Unknown") } @@ -899,7 +897,7 @@ fn test_bgeo_roundtrip_uncompressed() { // Read if not compressed if !is_compressed { - File::open(&input_file) + File::open(input_file) .unwrap() .read_to_end(&mut orig) .unwrap(); diff --git a/splashsurf_lib/src/io/obj_format.rs b/splashsurf_lib/src/io/obj_format.rs index 98420f6..29a9c65 100644 --- a/splashsurf_lib/src/io/obj_format.rs +++ b/splashsurf_lib/src/io/obj_format.rs @@ -30,7 +30,7 @@ pub fn mesh_to_obj, P: AsRef>( let mesh_vertices = &mesh.mesh; for v in mesh_vertices.vertices() { - write!(&mut writer, "v {} {} {}\n", v.x, v.y, v.z)?; + writeln!(&mut writer, "v {} {} {}", v.x, v.y, v.z)?; } let normals = mesh @@ -39,13 +39,10 @@ pub fn mesh_to_obj, P: AsRef>( .find(|attrib| attrib.name == "normals"); if let Some(normals) = normals { - match &normals.data { - AttributeData::Vector3Real(normals) => { - for n in normals { - write!(&mut writer, "vn {} {} {}\n", n.x, n.y, n.z)?; - } + if let AttributeData::Vector3Real(normals) = &normals.data { + for n in normals { + writeln!(&mut writer, "vn {} {} {}", n.x, n.y, n.z)?; } - _ => {} } } @@ -56,7 +53,7 @@ pub fn mesh_to_obj, P: AsRef>( .iter() .copied() .try_for_each(|v| write!(writer, " {}//{}", v + 1, v + 1))?; - write!(writer, "\n")?; + writeln!(writer)?; } } else { for f in mesh_vertices.cells() { @@ -65,7 +62,7 @@ pub fn mesh_to_obj, P: AsRef>( .iter() .copied() .try_for_each(|v| write!(writer, " {}", v + 1))?; - write!(writer, "\n")?; + writeln!(writer)?; } } diff --git a/splashsurf_lib/src/io/ply_format.rs b/splashsurf_lib/src/io/ply_format.rs index fffe4ae..ea016a2 100644 --- a/splashsurf_lib/src/io/ply_format.rs +++ b/splashsurf_lib/src/io/ply_format.rs @@ -44,7 +44,7 @@ fn parse_particles_from_ply( .ok_or(anyhow!("PLY file is missing a 'vertex' element"))?; let particles = elements - .into_iter() + .iter() .map(|e| { let vertex = ( e.get("x").unwrap(), @@ -130,7 +130,7 @@ fn parse_mesh_from_ply( .ok_or(anyhow!("PLY file is missing a 'face' element"))?; let triangles = faces - .into_iter() + .iter() .map(|e| { let indices = e .get("vertex_indices") @@ -204,32 +204,32 @@ pub fn mesh_to_ply, P: AsRef>( .context("Failed to open file handle for writing PLY file")?; let mut writer = BufWriter::with_capacity(1000000, file); - write!(&mut writer, "ply\n")?; - write!(&mut writer, "format binary_little_endian 1.0\n")?; - write!(&mut writer, "element vertex {}\n", mesh.vertices().len())?; - write!(&mut writer, "property float x\n")?; - write!(&mut writer, "property float y\n")?; - write!(&mut writer, "property float z\n")?; + writeln!(&mut writer, "ply")?; + writeln!(&mut writer, "format binary_little_endian 1.0")?; + writeln!(&mut writer, "element vertex {}", mesh.vertices().len())?; + writeln!(&mut writer, "property float x")?; + writeln!(&mut writer, "property float y")?; + writeln!(&mut writer, "property float z")?; for p_attr in &mesh.point_attributes { if p_attr.name == "normals" { - write!(&mut writer, "property float nx\n")?; - write!(&mut writer, "property float ny\n")?; - write!(&mut writer, "property float nz\n")?; + writeln!(&mut writer, "property float nx")?; + writeln!(&mut writer, "property float ny")?; + writeln!(&mut writer, "property float nz")?; } else { match p_attr.data { - AttributeData::ScalarU64(_) => write!(&mut writer, "property uint {}\n", p_attr.name)?, - AttributeData::ScalarReal(_) => write!(&mut writer, "property float {}\n", p_attr.name)?, + AttributeData::ScalarU64(_) => writeln!(&mut writer, "property uint {}", p_attr.name)?, + AttributeData::ScalarReal(_) => writeln!(&mut writer, "property float {}", p_attr.name)?, AttributeData::Vector3Real(_) => { - write!(&mut writer, "property float {}_x\n", p_attr.name)?; - write!(&mut writer, "property float {}_y\n", p_attr.name)?; - write!(&mut writer, "property float {}_z\n", p_attr.name)?; + writeln!(&mut writer, "property float {}_x", p_attr.name)?; + writeln!(&mut writer, "property float {}_y", p_attr.name)?; + writeln!(&mut writer, "property float {}_z", p_attr.name)?; }, } } } - write!(&mut writer, "element face {}\n", mesh.cells().len())?; - write!(&mut writer, "property list uchar uint vertex_indices\n")?; - write!(&mut writer, "end_header\n")?; + writeln!(&mut writer, "element face {}", mesh.cells().len())?; + writeln!(&mut writer, "property list uchar uint vertex_indices")?; + writeln!(&mut writer, "end_header")?; for (i, v) in mesh.vertices().iter().enumerate() { writer.write_all(&v.x.to_f32().expect("failed to convert coordinate to f32").to_le_bytes())?; diff --git a/splashsurf_lib/src/io/vtk_format.rs b/splashsurf_lib/src/io/vtk_format.rs index d3acfa8..8922f96 100644 --- a/splashsurf_lib/src/io/vtk_format.rs +++ b/splashsurf_lib/src/io/vtk_format.rs @@ -7,7 +7,7 @@ use anyhow::{anyhow, Context}; use nalgebra::Vector3; use std::borrow::Cow; use std::fs::create_dir_all; -use std::path::{Path, PathBuf}; +use std::path::Path; use vtkio::model::{ Attribute, Attributes, CellType, Cells, PolyDataPiece, UnstructuredGridPiece, VertexNumbers, }; @@ -71,8 +71,8 @@ impl DataPiece { }; match points { - IOBuffer::F64(coords) => particles_from_coords(&coords), - IOBuffer::F32(coords) => particles_from_coords(&coords), + IOBuffer::F64(coords) => particles_from_coords(coords), + IOBuffer::F32(coords) => particles_from_coords(coords), _ => Err(anyhow!( "Point coordinate IOBuffer does not contain f32 or f64 values" )), @@ -214,18 +214,18 @@ pub fn read_vtk>(filename: P) -> Result { /// Loads all supported pieces of the given VTK file fn load_pieces(vtk_file: Vtk) -> Result, anyhow::Error> { - let file_path = vtk_file.file_path.as_ref().map(PathBuf::as_path); + let file_path = vtk_file.file_path.as_deref(); let loaded_pieces = match vtk_file.data { DataSet::UnstructuredGrid { pieces, .. } => pieces .into_iter() .map(|p| p.into_loaded_piece_data(file_path)) - .map(|p| p.map(|p| DataPiece::UnstructuredGrid(p))) + .map(|p| p.map(DataPiece::UnstructuredGrid)) .collect::, _>>()?, DataSet::PolyData { pieces, .. } => pieces .into_iter() .map(|p| p.into_loaded_piece_data(file_path)) - .map(|p| p.map(|p| DataPiece::PolyData(p))) + .map(|p| p.map(DataPiece::PolyData)) .collect::, _>>()?, _ => Err(anyhow!( "VTK file does not contain supported data set pieces" @@ -287,7 +287,7 @@ fn surface_mesh_from_unstructured_grid( return Err(anyhow!("Length of cell vertex array is invalid. Expected 4 values per cell (3 for each triangle vertex index + 1 for vertex count). There are {} values for {} cells.", cell_verts.len(), num_cells)); } - let cells = cell_verts + cell_verts .chunks_exact(4) .enumerate() .map(|(cell_idx, cell)| { @@ -296,8 +296,7 @@ fn surface_mesh_from_unstructured_grid( .then(|| [cell[1] as usize, cell[2] as usize, cell[3] as usize]) .ok_or_else(|| anyhow!("Expected only triangle cells. Invalid number of vertex indices ({}) of cell {}", cell[0], cell_idx)) }) - .try_collect_with_capacity(num_cells as usize)?; - cells + .try_collect_with_capacity(num_cells as usize)? }; Ok(MeshWithData::new(TriMesh3d { @@ -313,19 +312,19 @@ fn try_convert_io_buffer_to_attribute( ) -> Result, anyhow::Error> { match num_comp { 1 => match &io_buffer { - IOBuffer::U32(vec) => try_map_scalars_to_real(&vec, |val| { + IOBuffer::U32(vec) => try_map_scalars_to_real(vec, |val| { R::from_u32(val).ok_or_else(|| { anyhow!("Cannot convert an attribute value from u32 to Real type") }) }) .map(|v| AttributeData::ScalarReal(v)), - IOBuffer::F32(vec) => try_map_scalars_to_real(&vec, |val| { + IOBuffer::F32(vec) => try_map_scalars_to_real(vec, |val| { R::from_f32(val).ok_or_else(|| { anyhow!("Cannot convert an attribute value from f32 to Real type") }) }) .map(|v| AttributeData::ScalarReal(v)), - IOBuffer::F64(vec) => try_map_scalars_to_real(&vec, |val| { + IOBuffer::F64(vec) => try_map_scalars_to_real(vec, |val| { R::from_f64(val).ok_or_else(|| { anyhow!("Cannot convert an attribute value from f64 to Real type") }) diff --git a/splashsurf_lib/src/io/xyz_format.rs b/splashsurf_lib/src/io/xyz_format.rs index c9b1713..5d20ad2 100644 --- a/splashsurf_lib/src/io/xyz_format.rs +++ b/splashsurf_lib/src/io/xyz_format.rs @@ -17,7 +17,7 @@ pub fn particles_from_xyz>( let get_four_bytes = |buffer: &[u8], offset: usize| -> [u8; 4] { [ - buffer[offset + 0], + buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], @@ -26,7 +26,7 @@ pub fn particles_from_xyz>( let mut particles = Vec::new(); - while let Ok(_) = reader.read_exact(&mut buffer) { + while reader.read_exact(&mut buffer).is_ok() { let x = f32::from_ne_bytes(get_four_bytes(&buffer, 0)); let y = f32::from_ne_bytes(get_four_bytes(&buffer, 4)); let z = f32::from_ne_bytes(get_four_bytes(&buffer, 8)); diff --git a/splashsurf_lib/src/kernel.rs b/splashsurf_lib/src/kernel.rs index 42c8965..8c43799 100644 --- a/splashsurf_lib/src/kernel.rs +++ b/splashsurf_lib/src/kernel.rs @@ -41,7 +41,7 @@ impl CubicSplineKernel { #[replace_float_literals(R::from_f64(literal).expect("Literal must fit in R"))] fn cubic_function(q: R) -> R { if q < R::one() { - return (3.0 / (2.0 * R::pi())) * ((2.0 / 3.0) - q * q + 0.5 * q * q * q); + (3.0 / (2.0 * R::pi())) * ((2.0 / 3.0) - q * q + 0.5 * q * q * q) } else if q < 2.0 { let x = 2.0 - q; return (R::one() / (4.0 * R::pi())) * x * x * x; @@ -54,7 +54,7 @@ impl CubicSplineKernel { #[replace_float_literals(R::from_f64(literal).expect("Literal must fit in R"))] fn cubic_function_dq(q: R) -> R { if q < 1.0 { - return (3.0 / (4.0 * R::pi())) * (-4.0 * q + 3.0 * q * q); + (3.0 / (4.0 * R::pi())) * (-4.0 * q + 3.0 * q * q) } else if q < 2.0 { let x = 2.0 - q; return -(3.0 / (4.0 * R::pi())) * x * x; diff --git a/splashsurf_lib/src/lib.rs b/splashsurf_lib/src/lib.rs index f803fd3..1d497f8 100644 --- a/splashsurf_lib/src/lib.rs +++ b/splashsurf_lib/src/lib.rs @@ -309,10 +309,10 @@ pub fn reconstruct_surface( } /// Performs a marching cubes surface construction of the fluid represented by the given particle positions, inplace -pub fn reconstruct_surface_inplace<'a, I: Index, R: Real>( +pub fn reconstruct_surface_inplace( particle_positions: &[Vector3], parameters: &Parameters, - output_surface: &'a mut SurfaceReconstruction, + output_surface: &mut SurfaceReconstruction, ) -> Result<(), ReconstructionError> { // Clear the existing mesh output_surface.mesh.clear(); diff --git a/splashsurf_lib/src/marching_cubes.rs b/splashsurf_lib/src/marching_cubes.rs index 8af6794..9aa3bb4 100644 --- a/splashsurf_lib/src/marching_cubes.rs +++ b/splashsurf_lib/src/marching_cubes.rs @@ -118,12 +118,8 @@ pub fn triangulate_density_map_append( ) -> Result<(), MarchingCubesError> { profile!("triangulate_density_map_append"); - let marching_cubes_data = construct_mc_input( - grid, - &density_map, - iso_surface_threshold, - &mut mesh.vertices, - ); + let marching_cubes_data = + construct_mc_input(grid, density_map, iso_surface_threshold, &mut mesh.vertices); triangulate(marching_cubes_data, mesh)?; Ok(()) @@ -191,7 +187,7 @@ pub fn check_mesh_consistency( add_edge_errors(&mut error_string, e); } } - error_string += &format!("\n"); + error_string += "\n"; } if check_manifold && !non_manifold_edges.is_empty() { @@ -201,7 +197,7 @@ pub fn check_mesh_consistency( add_edge_errors(&mut error_string, e); } } - error_string += &format!("\n"); + error_string += "\n"; } if check_manifold && !non_manifold_vertices.is_empty() { @@ -209,7 +205,7 @@ pub fn check_mesh_consistency( if debug { error_string += &format!("\n\t{:?}", non_manifold_vertices); } - error_string += &format!("\n"); + error_string += "\n"; } Err(error_string) diff --git a/splashsurf_lib/src/marching_cubes/marching_cubes_lut.rs b/splashsurf_lib/src/marching_cubes/marching_cubes_lut.rs index 0127f10..3f3c3b5 100644 --- a/splashsurf_lib/src/marching_cubes/marching_cubes_lut.rs +++ b/splashsurf_lib/src/marching_cubes/marching_cubes_lut.rs @@ -315,10 +315,7 @@ pub fn marching_cubes_triangulation_iter( vertices_inside: &[bool; 8], ) -> impl Iterator { let triangulation = get_marching_cubes_triangulation_raw(vertices_inside); - (0..5) - .into_iter() - .map(move |i| triangulation_to_triangle(triangulation, i)) - .flatten() + (0..5).filter_map(move |i| triangulation_to_triangle(triangulation, i)) } /// Converts an array of bool representing bits to the corresponding usize, the order of the bits is least to most significant @@ -341,7 +338,7 @@ fn triangulation_to_triangle(triangulation: &[i32; 16], triangle_index: usize) - Some([ triangulation[3 * i + 2], triangulation[3 * i + 1], - triangulation[3 * i + 0], + triangulation[3 * i], ]) } } diff --git a/splashsurf_lib/src/marching_cubes/narrow_band_extraction.rs b/splashsurf_lib/src/marching_cubes/narrow_band_extraction.rs index 9057aad..db5d5d7 100644 --- a/splashsurf_lib/src/marching_cubes/narrow_band_extraction.rs +++ b/splashsurf_lib/src/marching_cubes/narrow_band_extraction.rs @@ -12,7 +12,7 @@ pub(crate) fn construct_mc_input( vertices: &mut Vec>, ) -> MarchingCubesInput { let mut marching_cubes_data = MarchingCubesInput::default(); - let _ = interpolate_points_to_cell_data_generic::( + interpolate_points_to_cell_data_generic::( grid, density_map, iso_surface_threshold, @@ -81,7 +81,7 @@ fn interpolate_points_to_cell_data_generic( for neighbor_edge in neighborhood.neighbor_edge_iter() { let neighbor = neighbor_edge.neighbor_index(); // Get flat index of neighbor on global grid - let flat_neighbor_index = grid.flatten_point_index(&neighbor); + let flat_neighbor_index = grid.flatten_point_index(neighbor); // Try to read out the function value at the neighboring point let neighbor_value = if let Some(v) = density_map.get(flat_neighbor_index) { @@ -112,11 +112,9 @@ fn interpolate_points_to_cell_data_generic( // each cell adjacent to the edge crossing the iso-surface. // This includes the above/below iso-surface flags and the interpolated vertex index. for cell in grid.cells_adjacent_to_edge(&neighbor_edge).iter().flatten() { - let flat_cell_index = grid.flatten_cell_index(&cell); + let flat_cell_index = grid.flatten_cell_index(cell); - let cell_data_entry = cell_data - .entry(flat_cell_index) - .or_insert_with(CellData::default); + let cell_data_entry = cell_data.entry(flat_cell_index).or_default(); // Store the index of the interpolated vertex on the corresponding local edge of the cell let local_edge_index = cell.local_edge_index_of(&neighbor_edge).unwrap(); diff --git a/splashsurf_lib/src/marching_cubes/triangulation.rs b/splashsurf_lib/src/marching_cubes/triangulation.rs index 9e39597..e42d4d1 100644 --- a/splashsurf_lib/src/marching_cubes/triangulation.rs +++ b/splashsurf_lib/src/marching_cubes/triangulation.rs @@ -42,7 +42,7 @@ pub(crate) fn triangulate( { // TODO: Allow user to set option to skip invalid triangles? let global_triangle = get_triangle(cell_data, triangle) - .map_err(|e| TriangulationError::TriangleConnectivityError(e))?; + .map_err(TriangulationError::TriangleConnectivityError)?; mesh.triangles.push(global_triangle); } } diff --git a/splashsurf_lib/src/mesh.rs b/splashsurf_lib/src/mesh.rs index ab7ae0a..b88a962 100644 --- a/splashsurf_lib/src/mesh.rs +++ b/splashsurf_lib/src/mesh.rs @@ -367,7 +367,8 @@ fn vertex_keep_table>(mesh: &MeshT, cell_indices: &[us let cells = mesh.cells(); // Each entry is true if this vertex should be kept, false otherwise - let vertex_keep_table = { + + { let mut table = vec![false; vertices.len()]; for cell in cell_indices.iter().copied().map(|c_i| &cells[c_i]) { for &vertex_index in cell.vertices() { @@ -375,9 +376,7 @@ fn vertex_keep_table>(mesh: &MeshT, cell_indices: &[us } } table - }; - - vertex_keep_table + } } /// Returns a new mesh keeping only the given cells and vertices in the mesh @@ -428,7 +427,7 @@ fn keep_cells_impl>( .copied() .enumerate() .filter_map(|(i, should_keep)| if should_keep { Some(i) } else { None }) - .map(|index| vertices[index].clone()) + .map(|index| vertices[index]) .collect(); MeshT::from_vertices_and_connectivity(relabeled_vertices, relabeled_cells) @@ -496,7 +495,7 @@ impl CellConnectivity for TriangleOrQuadCell { } fn num_vertices(&self) -> usize { - return self.num_vertices(); + self.num_vertices() } fn vertices(&self) -> &[usize] { @@ -617,7 +616,7 @@ impl Mesh3d for PointCloud3d { } } -impl<'a, R: Real, MeshT: Mesh3d + Clone> Mesh3d for std::borrow::Cow<'a, MeshT> { +impl + Clone> Mesh3d for std::borrow::Cow<'_, MeshT> { type Cell = MeshT::Cell; fn vertices(&self) -> &[Vector3] { @@ -639,7 +638,7 @@ impl<'a, R: Real, MeshT: Mesh3d + Clone> Mesh3d for std::borrow::Cow<'a, M impl TriangleCell { /// Returns an iterator over all edges of this triangle - pub fn edges<'a>(&'a self) -> impl Iterator + 'a { + pub fn edges(&self) -> impl Iterator + '_ { (0..3).map(|i| (self.0[i], self.0[(i + 1) % 3])) } } @@ -666,7 +665,7 @@ pub struct EdgeInformation { impl MeshEdgeInformation { /// Iterator over all edge information stored in this struct - pub fn iter<'a>(&'a self) -> impl Iterator + 'a { + pub fn iter(&self) -> impl Iterator + '_ { self.edge_counts.iter().map(|(e, (edge_idx, count))| { let info = &self.edge_info[*edge_idx]; EdgeInformation { @@ -696,7 +695,7 @@ impl MeshEdgeInformation { } /// Iterator over all boundary edges - pub fn boundary_edges<'a>(&'a self) -> impl Iterator + 'a { + pub fn boundary_edges(&self) -> impl Iterator + '_ { self.edge_counts .values() .filter(|(_, count)| *count == 1) @@ -704,7 +703,7 @@ impl MeshEdgeInformation { } /// Iterator over all non-manifold edges - pub fn non_manifold_edges<'a>(&'a self) -> impl Iterator + 'a { + pub fn non_manifold_edges(&self) -> impl Iterator + '_ { self.edge_counts .values() .filter(|(_, count)| *count > 2) @@ -857,7 +856,7 @@ impl TriMesh3d { } /// Same as [`Self::vertex_normals_inplace`] but assumes that the output is already zeroed - fn vertex_normals_inplace_assume_zeroed<'a>(&self, normals: &'a mut [Unit>]) { + fn vertex_normals_inplace_assume_zeroed(&self, normals: &mut [Unit>]) { assert_eq!(normals.len(), self.vertices.len()); // First, compute the directions of the normals... @@ -876,7 +875,7 @@ impl TriMesh3d { } /// Same as [`Self::par_vertex_normals_inplace`] but assumes that the output is already zeroed - fn par_vertex_normals_inplace_assume_zeroed<'a>(&self, normals: &'a mut [Unit>]) { + fn par_vertex_normals_inplace_assume_zeroed(&self, normals: &mut [Unit>]) { assert_eq!(normals.len(), self.vertices.len()); // First, compute the directions of the normals... @@ -1281,7 +1280,7 @@ impl> Mesh3d for MeshWithData { let cell_attributes = self .cell_attributes .iter() - .map(|attr| attr.keep_indices(&cell_indices)) + .map(|attr| attr.keep_indices(cell_indices)) .collect(); new_mesh.cell_attributes = cell_attributes; @@ -1391,13 +1390,13 @@ impl MeshAttribute { fn keep_indices(&self, indices: &[usize]) -> Self { let data = match &self.data { AttributeData::ScalarU64(d) => { - AttributeData::ScalarU64(indices.iter().copied().map(|i| d[i].clone()).collect()) + AttributeData::ScalarU64(indices.iter().copied().map(|i| d[i]).collect()) } AttributeData::ScalarReal(d) => { - AttributeData::ScalarReal(indices.iter().copied().map(|i| d[i].clone()).collect()) + AttributeData::ScalarReal(indices.iter().copied().map(|i| d[i]).collect()) } AttributeData::Vector3Real(d) => { - AttributeData::Vector3Real(indices.iter().copied().map(|i| d[i].clone()).collect()) + AttributeData::Vector3Real(indices.iter().copied().map(|i| d[i]).collect()) } }; @@ -1607,7 +1606,7 @@ pub mod vtk_helper { { let points = { let mut points: Vec = Vec::with_capacity(mesh.vertices().len() * 3); - points.extend(mesh.vertices().iter().map(|p| p.as_slice()).flatten()); + points.extend(mesh.vertices().iter().flat_map(|p| p.as_slice())); points }; diff --git a/splashsurf_lib/src/neighborhood_search.rs b/splashsurf_lib/src/neighborhood_search.rs index c064b56..139bdb9 100644 --- a/splashsurf_lib/src/neighborhood_search.rs +++ b/splashsurf_lib/src/neighborhood_search.rs @@ -171,7 +171,7 @@ pub fn neighborhood_search_spatial_hashing_filtered( let search_radius_squared = search_radius * search_radius; // Create a new grid for neighborhood search - let grid = UniformGrid::from_aabb(&domain, search_radius) + let grid = UniformGrid::from_aabb(domain, search_radius) .expect("Failed to construct grid for neighborhood search!"); // Map for spatially hashed storage of all particles (map from cell -> enclosed particles) let particles_per_cell = @@ -252,10 +252,8 @@ impl FlatNeighborhoodList { self.neighbor_ptr.len() - 1 } - pub fn iter<'a>(&'a self) -> impl Iterator + 'a { - (0..self.neighbor_ptr.len()) - .into_iter() - .flat_map(|i| self.get_neighbors(i)) + pub fn iter(&self) -> impl Iterator + '_ { + (0..self.neighbor_ptr.len()).flat_map(|i| self.get_neighbors(i)) } /// Returns a slice containing the neighborhood list of the given particle @@ -369,7 +367,7 @@ pub fn neighborhood_search_spatial_hashing_flat_filtered( let search_radius_squared = search_radius * search_radius; // Create a new grid for neighborhood search - let grid = UniformGrid::from_aabb(&domain, search_radius) + let grid = UniformGrid::from_aabb(domain, search_radius) .expect("Failed to construct grid for neighborhood search!"); // Map for spatially hashed storage of all particles (map from cell -> enclosed particles) let particles_per_cell = @@ -414,7 +412,7 @@ pub fn neighborhood_search_spatial_hashing_flat_filtered( }) .flatten() .copied() - .for_each(|particle_j| neighbor_test(particle_j)); + .for_each(&mut neighbor_test); // Loop over current cell std::iter::once(current_cell) @@ -463,7 +461,7 @@ pub fn neighborhood_search_spatial_hashing_parallel( let search_radius_squared = search_radius * search_radius; // Create a new grid for neighborhood search - let grid = UniformGrid::from_aabb(&domain, search_radius) + let grid = UniformGrid::from_aabb(domain, search_radius) .expect("Failed to construct grid for neighborhood search!"); // Map for spatially hashed storage of all particles (map from cell -> enclosed particles) @@ -523,7 +521,7 @@ pub fn neighborhood_search_spatial_hashing_parallel( let neighborhood_test = |pos_i: Vector3, particle_j: usize, local_buffer: &mut Vec| { - let pos_j = unsafe { particle_positions.get_unchecked(particle_j).clone() }; + let pos_j = unsafe { *particle_positions.get_unchecked(particle_j) }; // TODO: We might not be able to guarantee that this is symmetric. // Therefore, it might be possible that only one side of some neighborhood relationships gets detected. @@ -536,7 +534,7 @@ pub fn neighborhood_search_spatial_hashing_parallel( // Iterate over all particles of the current cell for (i, particle_i) in cell_k_particles.iter().copied().enumerate() { - let pos_i = unsafe { particle_positions.get_unchecked(particle_i).clone() }; + let pos_i = unsafe { *particle_positions.get_unchecked(particle_i) }; // Check for neighborhood with particles of all adjacent cells // Transitive neighborhood relationship is not handled explicitly. diff --git a/splashsurf_lib/src/postprocessing.rs b/splashsurf_lib/src/postprocessing.rs index 74c18f9..034a151 100644 --- a/splashsurf_lib/src/postprocessing.rs +++ b/splashsurf_lib/src/postprocessing.rs @@ -39,9 +39,9 @@ pub fn par_laplacian_smoothing_inplace( // Compute mean position of neighboring vertices let mut vertex_sum = Vector3::zeros(); for j in vertex_connectivity[i].iter() { - vertex_sum += vertex_buffer[j.clone()]; + vertex_sum += vertex_buffer[*j]; } - if vertex_connectivity[i].len() > 0 { + if !vertex_connectivity[i].is_empty() { let n = R::from_usize(vertex_connectivity[i].len()).unwrap(); vertex_sum /= n; } @@ -164,7 +164,7 @@ pub fn marching_cubes_cleanup( for &v1 in vertex_buffer.iter() { if mesh.is_valid_vertex(v1) { if let Some(he) = mesh.half_edge(v1, v0) { - if let Ok(_) = mesh.try_half_edge_collapse(he) { + if mesh.try_half_edge_collapse(he).is_ok() { collapse_count += 1; // Move to averaged position @@ -211,7 +211,7 @@ pub fn decimation(mesh: &mut TriMesh3d, keep_vertices: bool) -> Vec< profile!("convert mesh back"); let (new_mesh, vertex_map) = half_edge_mesh.into_parts(keep_vertices); *mesh = new_mesh; - return vertex_map; + vertex_map } } @@ -297,12 +297,9 @@ fn process_triangle_collapse_queue( if let Some(he) = mesh.half_edge(from, to) { last_res = Some(mesh.try_half_edge_collapse(he)); - match last_res { - Some(Ok(_)) => { - processed += 1; - return None; - } - _ => {} + if let Some(Ok(_)) = last_res { + processed += 1; + return None; } } else { warn!( @@ -319,7 +316,7 @@ fn process_triangle_collapse_queue( warn!("Invalid collapse: {:?} (from {} to {})", e, from, to); None } - _ => return None, + _ => None, } }) .collect(); @@ -422,7 +419,7 @@ pub fn merge_single_barnacle_configurations_he(mesh: &mut HalfEdgeTriMe && mesh .vertex_one_ring(i) .map(|j| mesh.vertex_one_ring_len(j)) - .all(|len| len >= 4 && len <= 6) + .all(|len| (4..=6).contains(&len)) && mesh .vertex_one_ring(i) .map(|j| mesh.vertex_one_ring_len(j)) @@ -592,7 +589,7 @@ pub fn merge_double_barnacle_configurations_he(mesh: &mut HalfEdgeTriMe if let Some(other_pair) = candidate_to_pair_map.get(&l) { return *other_pair < pair; } - return false; + false }) }; @@ -621,14 +618,12 @@ pub fn merge_double_barnacle_configurations_he(mesh: &mut HalfEdgeTriMe if k != j { if mesh.vertex_one_ring(k).all(|l| l != j) { half_edge_collapses.insert(k, i); + } else if (mesh.vertices[k] - mesh.vertices[i]).norm() + <= (mesh.vertices[k] - mesh.vertices[j]).norm() + { + half_edge_collapses.insert(k, i); } else { - if (mesh.vertices[k] - mesh.vertices[i]).norm() - <= (mesh.vertices[k] - mesh.vertices[j]).norm() - { - half_edge_collapses.insert(k, i); - } else { - half_edge_collapses.insert(k, j); - } + half_edge_collapses.insert(k, j); } } }; @@ -690,14 +685,12 @@ pub fn convert_tris_to_quads( quad[2] = tri_i[2]; quad[3] = missing_vertex; } + } else if tri_j.contains(&tri_i[1]) { + quad[1] = tri_i[1]; + quad[2] = missing_vertex; + quad[3] = tri_i[2]; } else { - if tri_j.contains(&tri_i[1]) { - quad[1] = tri_i[1]; - quad[2] = missing_vertex; - quad[3] = tri_i[2]; - } else { - panic!("this should not happen"); - } + panic!("this should not happen"); } quad @@ -815,7 +808,7 @@ pub fn convert_tris_to_quads( } } - return None; + None }) .collect::>(); @@ -867,12 +860,8 @@ pub fn convert_tris_to_quads( ); let mut cells = Vec::with_capacity(filtered_triangles.len() + quads.len()); - cells.extend( - filtered_triangles - .into_iter() - .map(|tri| TriangleOrQuadCell::Tri(tri)), - ); - cells.extend(quads.into_iter().map(|quad| TriangleOrQuadCell::Quad(quad))); + cells.extend(filtered_triangles.into_iter().map(TriangleOrQuadCell::Tri)); + cells.extend(quads.into_iter().map(TriangleOrQuadCell::Quad)); MixedTriQuadMesh3d { vertices: mesh.vertices.clone(), diff --git a/splashsurf_lib/src/profiling.rs b/splashsurf_lib/src/profiling.rs index ddf0c42..713292c 100644 --- a/splashsurf_lib/src/profiling.rs +++ b/splashsurf_lib/src/profiling.rs @@ -5,7 +5,7 @@ use parking_lot::RwLock; use std::collections::hash_map::RandomState; use std::collections::{HashMap, HashSet}; use std::error::Error; -use std::hash::{BuildHasher, Hash, Hasher}; +use std::hash::{BuildHasher, Hash}; use std::io; use std::time::{Duration, Instant}; use thread_local::ThreadLocal; @@ -110,10 +110,7 @@ pub struct ScopeId { impl ScopeId { fn get_hash(id: Option<&ScopeId>) -> u64 { - let mut hasher = RANDOM_STATE.build_hasher(); - id.hash(&mut hasher); - let hash = hasher.finish(); - hash + RANDOM_STATE.hash_one(id) } } diff --git a/splashsurf_lib/src/reconstruction.rs b/splashsurf_lib/src/reconstruction.rs index ff91006..e311203 100644 --- a/splashsurf_lib/src/reconstruction.rs +++ b/splashsurf_lib/src/reconstruction.rs @@ -14,15 +14,15 @@ use log::{info, trace}; use nalgebra::Vector3; /// Performs a surface reconstruction with a regular grid for domain decomposition -pub(crate) fn reconstruct_surface_subdomain_grid<'a, I: Index, R: Real>( +pub(crate) fn reconstruct_surface_subdomain_grid( particle_positions: &[Vector3], parameters: &Parameters, - output_surface: &'a mut SurfaceReconstruction, + output_surface: &mut SurfaceReconstruction, ) -> Result<(), anyhow::Error> { profile!("surface reconstruction subdomain-grid"); let internal_parameters = - initialize_parameters(parameters, &particle_positions, output_surface)?; + initialize_parameters(parameters, particle_positions, output_surface)?; output_surface.grid = internal_parameters .global_marching_cubes_grid() .context("failed to convert global marching cubes grid")?; @@ -34,7 +34,7 @@ pub(crate) fn reconstruct_surface_subdomain_grid<'a, I: Index, R: Real>( */ let subdomains = - decomposition::>(&internal_parameters, &particle_positions)?; + decomposition::>(&internal_parameters, particle_positions)?; /* { @@ -49,13 +49,13 @@ pub(crate) fn reconstruct_surface_subdomain_grid<'a, I: Index, R: Real>( let (particle_densities, particle_neighbors) = compute_global_densities_and_neighbors( &internal_parameters, - &particle_positions, + particle_positions, &subdomains, ); let surface_patches = reconstruction( &internal_parameters, - &particle_positions, + particle_positions, &particle_densities, &subdomains, ); @@ -76,10 +76,10 @@ pub(crate) fn reconstruct_surface_subdomain_grid<'a, I: Index, R: Real>( } /// Performs a global surface reconstruction without domain decomposition -pub(crate) fn reconstruct_surface_global<'a, I: Index, R: Real>( +pub(crate) fn reconstruct_surface_global( particle_positions: &[Vector3], parameters: &Parameters, - output_surface: &'a mut SurfaceReconstruction, + output_surface: &mut SurfaceReconstruction, ) -> Result<(), ReconstructionError> { profile!("reconstruct_surface_global"); @@ -134,7 +134,7 @@ pub(crate) fn compute_particle_densities_and_neighbors( trace!("Starting neighborhood search..."); neighborhood_search::search_inplace::( - &grid.aabb(), + grid.aabb(), particle_positions, parameters.compact_support_radius, parameters.enable_multi_threading, @@ -153,12 +153,12 @@ pub(crate) fn compute_particle_densities_and_neighbors( } /// Reconstruct a surface, appends triangulation to the given mesh -pub(crate) fn reconstruct_single_surface_append<'a, I: Index, R: Real>( +pub(crate) fn reconstruct_single_surface_append( workspace: &mut LocalReconstructionWorkspace, grid: &UniformGrid, particle_positions: &[Vector3], parameters: &Parameters, - output_mesh: &'a mut TriMesh3d, + output_mesh: &mut TriMesh3d, ) -> Result<(), ReconstructionError> { let particle_rest_density = parameters.rest_density; let particle_rest_volume = R::from_f64((4.0 / 3.0) * std::f64::consts::PI).unwrap() diff --git a/splashsurf_lib/src/sph_interpolation.rs b/splashsurf_lib/src/sph_interpolation.rs index 75a8a2c..5df76b5 100644 --- a/splashsurf_lib/src/sph_interpolation.rs +++ b/splashsurf_lib/src/sph_interpolation.rs @@ -277,10 +277,9 @@ fn build_rtree( .collect(); // Build the R-tree to accelerate SPH neighbor queries near the interpolation points - let tree = { + + { profile!("build R-tree"); RTree::bulk_load(particles) - }; - - tree + } } diff --git a/splashsurf_lib/src/uniform_grid.rs b/splashsurf_lib/src/uniform_grid.rs index 7ee2c80..ca49a9e 100644 --- a/splashsurf_lib/src/uniform_grid.rs +++ b/splashsurf_lib/src/uniform_grid.rs @@ -189,7 +189,7 @@ impl UniformCartesianCubeGrid3d { .unscale(cell_size) .map(|x| x.floor()) .scale(cell_size); - let aabb = Aabb3d::new(aligned_min, aabb.max().clone()); + let aabb = Aabb3d::new(aligned_min, *aabb.max()); let n_cells_real = aabb.extents() / cell_size; let n_cells_per_dim = Self::checked_n_cells_per_dim(&n_cells_real) @@ -204,7 +204,7 @@ impl UniformCartesianCubeGrid3d { n_cells_per_dim: &[I; 3], cell_size: R, ) -> Result> { - let n_cells_per_dim = n_cells_per_dim.clone(); + let n_cells_per_dim = *n_cells_per_dim; let n_points_per_dim = Self::checked_n_points_per_dim(&n_cells_per_dim) .ok_or(GridConstructionError::IndexTypeTooSmallPointsPerDim)?; @@ -284,7 +284,7 @@ impl UniformCartesianCubeGrid3d { } pub fn get_edge(&self, origin_ijk: [I; 3], axis: Axis) -> Option> { - let mut target_ijk = origin_ijk.clone(); + let mut target_ijk = origin_ijk; target_ijk[axis.dim()] += I::one(); if self.point_exists(&origin_ijk) && self.point_exists(&target_ijk) { Some(EdgeIndex { @@ -479,7 +479,7 @@ impl UniformCartesianCubeGrid3d { return None; } - let mut neighbor_ijk = point_ijk.clone(); + let mut neighbor_ijk = *point_ijk; neighbor_ijk[dim] = direction.apply_step(neighbor_ijk[dim], I::one()); Some(PointIndex::from_ijk(neighbor_ijk)) } @@ -493,7 +493,7 @@ impl UniformCartesianCubeGrid3d { let DirectedAxis { axis, direction } = direction; let dim = axis.dim(); - let mut neighbor_ijk = point_ijk.clone(); + let mut neighbor_ijk = *point_ijk; neighbor_ijk[dim] = direction.apply_step(neighbor_ijk[dim], I::one()); neighbor_ijk } @@ -509,9 +509,9 @@ impl UniformCartesianCubeGrid3d { } /// Returns an array of all cells that may be adjacent to the specified edge - pub fn cells_adjacent_to_edge<'a, 'b>( + pub fn cells_adjacent_to_edge( &self, - edge: &NeighborEdge<'a, 'b, I>, + edge: &NeighborEdge<'_, '_, I>, ) -> [Option>; 4] { // Each cell has the same index as the point in its lower corner, its 'origin point'. // To get all cells adjacent to the given edge, all corresponding origin points have to be found @@ -533,7 +533,7 @@ impl UniformCartesianCubeGrid3d { // Try to obtain all points that might be the origin or lower corner of a cell // Some of them (p1, p3 or both) might not exist if the edge is at the boundary of the grid - let p0 = Some(edge_start_point.clone()); + let p0 = Some(*edge_start_point); let p1 = self.get_point_neighbor(edge_start_point, step_dir1); let p3 = self.get_point_neighbor(edge_start_point, step_dir3); // Get the last origin point by combining both steps @@ -559,9 +559,9 @@ impl UniformCartesianCubeGrid3d { } /// Returns an array of all cells that contain the point which is the origin point of the given neighborhood - pub fn cells_adjacent_to_point<'a>( + pub fn cells_adjacent_to_point( &self, - neighborhood: &Neighborhood<'a, I>, + neighborhood: &Neighborhood<'_, I>, ) -> [Option>; 8] { let cells_above = neighborhood .get_neighbor_edge(Axis::Z.with_direction(Direction::Positive)) @@ -665,7 +665,7 @@ impl UniformCartesianCubeGrid3d { cell_size * n_cells_per_dim[2].to_real()?, ); - Some(Aabb3d::new(min.clone(), max)) + Some(Aabb3d::new(*min, max)) } fn checked_num_points(n_points_per_dim: &[I; 3]) -> Option { @@ -741,7 +741,7 @@ impl CellIndex { } #[inline(always)] - pub fn local_edge_index_of<'a, 'b>(&self, edge: &NeighborEdge<'a, 'b, I>) -> Option { + pub fn local_edge_index_of(&self, edge: &NeighborEdge<'_, '_, I>) -> Option { let (start_point, _) = edge.ascending_point_order(); let start_point_local = self.local_point_index_of(start_point.index())?; let edge_dim = edge.connectivity.axis.dim(); @@ -1007,7 +1007,7 @@ const CELL_LOCAL_EDGE_TO_FACE_FLAGS: [FaceFlags; 12] = [ FaceFlags::from_bits_truncate(FaceFlags::X_NEG.bits() | FaceFlags::Y_POS.bits()), ]; -impl<'a, I: Index> Neighborhood<'a, I> { +impl Neighborhood<'_, I> { /// Returns if the origin point has a valid neighbor following the specified directed axis #[inline(always)] pub fn has_neighbor(&self, direction: DirectedAxis) -> bool { @@ -1022,10 +1022,7 @@ impl<'a, I: Index> Neighborhood<'a, I> { /// Get the edge to a specific neighbor in the given direction from the origin point of the neighborhood #[inline(always)] - pub fn get_neighbor_edge<'b>( - &'b self, - direction: DirectedAxis, - ) -> Option> { + pub fn get_neighbor_edge(&self, direction: DirectedAxis) -> Option> { self.neighbors .get(&direction) .as_ref() @@ -1033,7 +1030,7 @@ impl<'a, I: Index> Neighborhood<'a, I> { } /// Iterate over all valid neighbor points and the corresponding directed axis from the origin to the neighbor - pub fn neighbor_edge_iter<'b>(&'b self) -> impl Iterator> { + pub fn neighbor_edge_iter(&self) -> impl Iterator> { self.neighbors .iter() .filter_map(move |(&connectivity, optional_neighbor)| { @@ -1056,17 +1053,17 @@ impl<'a, I: Index> Neighborhood<'a, I> { } } -impl<'a, 'b, I: Index> NeighborEdge<'a, 'b, I> { +impl NeighborEdge<'_, '_, I> { /// Returns the origin of this neighbor edge #[inline(always)] pub fn origin_index(&self) -> &PointIndex { - &self.neighborhood.origin + self.neighborhood.origin } /// Returns the neighbor of the origin node connected by this neighbor edge #[inline(always)] pub fn neighbor_index(&self) -> &PointIndex { - &self.neighbor + self.neighbor } /// Returns the connectivity between the origin point and its neighbor in terms of a directed axis @@ -1080,9 +1077,9 @@ impl<'a, 'b, I: Index> NeighborEdge<'a, 'b, I> { #[inline(always)] pub fn ascending_point_order(&self) -> (&PointIndex, &PointIndex) { if self.connectivity.direction.is_positive() { - (self.origin_index(), &self.neighbor_index()) + (self.origin_index(), self.neighbor_index()) } else { - (&self.neighbor_index(), self.origin_index()) + (self.neighbor_index(), self.origin_index()) } } } diff --git a/splashsurf_lib/src/utils.rs b/splashsurf_lib/src/utils.rs index 4acc66e..be3d6d3 100644 --- a/splashsurf_lib/src/utils.rs +++ b/splashsurf_lib/src/utils.rs @@ -57,8 +57,8 @@ pub(crate) struct UnsafeSlice<'a, T> { slice: &'a [UnsafeCell], } -unsafe impl<'a, T: Send + Sync> Send for UnsafeSlice<'a, T> {} -unsafe impl<'a, T: Send + Sync> Sync for UnsafeSlice<'a, T> {} +unsafe impl Send for UnsafeSlice<'_, T> {} +unsafe impl Sync for UnsafeSlice<'_, T> {} impl<'a, T> UnsafeSlice<'a, T> { /// Wraps a slice to be able to share mutable access between threads @@ -167,8 +167,8 @@ impl ChunkSize { } else { // Ensure that there are the desired amount of tasks/chunks per thread let num_tasks = parallel_policy.tasks_per_thread * num_threads; - let task_size = (num_items / num_tasks).max(parallel_policy.min_task_size); - task_size + + (num_items / num_tasks).max(parallel_policy.min_task_size) } // Ensure that we don't have less than a minimum number of items per thread .max(16);