From 9f15d1c53938a441a6bbfb2de866492797f69e22 Mon Sep 17 00:00:00 2001 From: Kornel Date: Sun, 22 Jan 2023 17:52:20 +0000 Subject: [PATCH] Clippy --- benches/bench.rs | 12 ++++++------ imagequant-sys/src/ffi.rs | 24 ++++++++++++------------ src/attr.rs | 16 ++++++++-------- src/blur.rs | 16 ++++++++-------- src/capi.rs | 14 +++++++------- src/hist.rs | 26 ++++++++++---------------- src/image.rs | 11 +++++------ src/kmeans.rs | 16 ++++++++-------- src/lib.rs | 10 +++++----- src/mediancut.rs | 24 ++++++++++++------------ src/nearest.rs | 7 +++---- src/pal.rs | 15 ++++++++------- src/quant.rs | 22 +++++++++++----------- src/rayoff.rs | 2 +- src/remap.rs | 16 ++++++++-------- src/rows.rs | 9 ++++++--- 16 files changed, 118 insertions(+), 122 deletions(-) diff --git a/benches/bench.rs b/benches/bench.rs index 0e226b8..ba5453b 100644 --- a/benches/bench.rs +++ b/benches/bench.rs @@ -13,7 +13,7 @@ fn histogram(b: &mut Bencher) { let mut img = liq.new_image(&*img.buffer, img.width, img.height, 0.).unwrap(); let mut hist = Histogram::new(&liq); hist.add_image(&liq, &mut img).unwrap(); - }) + }); } #[bench] @@ -28,12 +28,12 @@ fn remap_ord(b: &mut Bencher) { b.iter(move || { res.remap_into(&mut img, &mut buf).unwrap(); res.remap_into(&mut img, &mut buf).unwrap(); - }) + }); } #[bench] fn kmeans(b: &mut Bencher) { - b.iter(_unstable_internal_kmeans_bench()) + b.iter(_unstable_internal_kmeans_bench()); } #[bench] @@ -48,7 +48,7 @@ fn remap_floyd(b: &mut Bencher) { b.iter(move || { res.remap_into(&mut img, &mut buf).unwrap(); res.remap_into(&mut img, &mut buf).unwrap(); - }) + }); } #[bench] @@ -59,7 +59,7 @@ fn quantize_s8(b: &mut Bencher) { b.iter(move || { let mut img = liq.new_image(&*img.buffer, img.width, img.height, 0.).unwrap(); liq.quantize(&mut img).unwrap(); - }) + }); } #[bench] @@ -70,5 +70,5 @@ fn quantize_s1(b: &mut Bencher) { b.iter(move || { let mut img = liq.new_image(&*img.buffer, img.width, img.height, 0.).unwrap(); liq.quantize(&mut img).unwrap(); - }) + }); } diff --git a/imagequant-sys/src/ffi.rs b/imagequant-sys/src/ffi.rs index c9ceb32..443f5ff 100644 --- a/imagequant-sys/src/ffi.rs +++ b/imagequant-sys/src/ffi.rs @@ -4,9 +4,9 @@ #![allow(non_camel_case_types)] #![allow(clippy::missing_safety_doc)] -use imagequant::*; use imagequant::capi::*; use imagequant::Error::LIQ_OK; +use imagequant::*; use std::ffi::CString; use std::mem::ManuallyDrop; use std::mem::MaybeUninit; @@ -378,7 +378,7 @@ pub unsafe extern "C" fn liq_image_set_importance_map(img: &mut liq_image, impor img.set_importance_map(importance_map_slice).err().unwrap_or(LIQ_OK) } else if ownership == liq_ownership::LIQ_OWN_PIXELS { let copy: Box<[u8]> = importance_map_slice.into(); - free_fn(importance_map as *mut _); + free_fn(importance_map.cast()); img.set_importance_map(copy).err().unwrap_or(LIQ_OK); LIQ_OK } else { @@ -425,7 +425,7 @@ pub extern "C" fn liq_attr_create_with_allocator(_unused: *mut c_void, free: uns inner: Attributes::new(), c_api_free: free, }); - debug_assert_eq!((&*attr) as *const liq_attr, unsafe { attr_to_liq_attr_ptr(&attr.inner) } as *const liq_attr); + debug_assert_eq!(std::ptr::addr_of!(*attr), unsafe { attr_to_liq_attr_ptr(&attr.inner) } as *const liq_attr); Some(attr) } @@ -494,14 +494,14 @@ pub extern "C" fn liq_get_remapping_error(result: &liq_result) -> f64 { #[inline(never)] pub extern "C" fn liq_get_quantization_quality(result: &liq_result) -> c_int { if bad_object!(result, LIQ_RESULT_MAGIC) { return -1; } - result.inner.quantization_quality().map(c_int::from).unwrap_or(-1) + result.inner.quantization_quality().map_or(-1, c_int::from) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_get_remapping_quality(result: &liq_result) -> c_int { if bad_object!(result, LIQ_RESULT_MAGIC) { return -1; } - result.inner.remapping_quality().map(c_int::from).unwrap_or(-1) + result.inner.remapping_quality().map_or(-1, c_int::from) } #[no_mangle] @@ -644,14 +644,14 @@ fn links_and_runs() { unsafe { assert!(liq_version() >= 40000); let attr = liq_attr_create().unwrap(); - let mut hist = liq_histogram_create(&*attr).unwrap(); - assert_eq!(LIQ_OK, liq_histogram_add_fixed_color(&mut *hist, liq_color {r: 0, g: 0, b: 0, a: 0}, 0.)); - liq_histogram_add_colors(&mut *hist, &*attr, ptr::null(), 0, 0.); + let mut hist = liq_histogram_create(&attr).unwrap(); + assert_eq!(LIQ_OK, liq_histogram_add_fixed_color(&mut hist, liq_color {r: 0, g: 0, b: 0, a: 0}, 0.)); + liq_histogram_add_colors(&mut hist, &attr, ptr::null(), 0, 0.); let mut res = MaybeUninit::uninit(); // this is fine, because there is 1 fixed color to generate - assert_eq!(LIQ_OK, liq_histogram_quantize(&mut *hist, &*attr, &mut res)); + assert_eq!(LIQ_OK, liq_histogram_quantize(&mut hist, &attr, &mut res)); let res = res.assume_init().unwrap(); liq_result_destroy(Some(res)); @@ -728,12 +728,12 @@ fn c_callback_test_c() { assert_eq!(123, width); for i in 0..width as isize { let n = i as u8; - (*output_row.offset(i as isize)).write(RGBA::new(n, n, n, n)); + (*output_row.offset(i)).write(RGBA::new(n, n, n, n)); } - let user_data = user_data.0 as *mut i32; + let user_data = user_data.0.cast::(); *user_data += 1; } - let mut img = liq_image_create_custom(&a, get_row, AnySyncSendPtr((&mut called) as *mut _ as *mut c_void), 123, 5, 0.).unwrap(); + let mut img = liq_image_create_custom(&a, get_row, AnySyncSendPtr(std::ptr::addr_of_mut!(called) as *mut c_void), 123, 5, 0.).unwrap(); liq_quantize_image(&mut a, &mut img).unwrap() }; assert!(called > 5 && called < 50); diff --git a/src/attr.rs b/src/attr.rs index 635c3fd..8b9101b 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -1,8 +1,8 @@ use crate::error::Error; use crate::hist::Histogram; use crate::image::Image; -use crate::pal::MAX_COLORS; use crate::pal::PalLen; +use crate::pal::MAX_COLORS; use crate::pal::RGBA; use crate::quant::{mse_to_quality, quality_to_mse, QuantizationResult}; use crate::remap::DitherMapMode; @@ -129,7 +129,7 @@ impl Attributes { let mut iterations = (8 - value).max(0) as u16; iterations += iterations * iterations / 2; self.kmeans_iterations = iterations; - self.kmeans_iteration_limit = 1. / ((1 << (23 - value)) as f64); + self.kmeans_iteration_limit = 1. / f64::from(1 << (23 - value)); self.feedback_loop_trials = (56 - 9 * value).max(0) as _; self.max_histogram_entries = ((1 << 17) + (1 << 18) * (10 - value)) as _; self.min_posterization_input = if value >= 8 { 1 } else { 0 }; @@ -186,7 +186,7 @@ impl Attributes { #[must_use] pub fn quality(&self) -> (u8, u8) { ( - self.max_mse.map(mse_to_quality).unwrap_or(0), + self.max_mse.map_or(0, mse_to_quality), mse_to_quality(self.target_mse), ) } @@ -285,24 +285,24 @@ impl Attributes { if hist_items > 50000 { feedback_loop_trials = (feedback_loop_trials * 3 + 3) / 4; } - if hist_items > 100000 { + if hist_items > 100_000 { feedback_loop_trials = (feedback_loop_trials * 3 + 3) / 4; } feedback_loop_trials } - /// max_mse, target_mse, user asked for perfect quality + /// `max_mse`, `target_mse`, user asked for perfect quality pub(crate) fn target_mse(&self, hist_items_len: usize) -> (Option, f64, bool) { let max_mse = self.max_mse.map(|mse| mse * if hist_items_len <= MAX_COLORS { 0.33 } else { 1. }); let aim_for_perfect_quality = self.target_mse == 0.; - let mut target_mse = self.target_mse.max(((1 << self.min_posterization_output) as f64 / 1024.).powi(2)); + let mut target_mse = self.target_mse.max((f64::from(1 << self.min_posterization_output) / 1024.).powi(2)); if let Some(max_mse) = max_mse { target_mse = target_mse.min(max_mse); } (max_mse, target_mse, aim_for_perfect_quality) } - /// returns iterations, iteration_limit + /// returns iterations, `iteration_limit` pub(crate) fn kmeans_iterations(&self, hist_items_len: usize, palette_error_is_known: bool) -> (u16, f64) { let mut iteration_limit = self.kmeans_iteration_limit; let mut iterations = self.kmeans_iterations; @@ -315,7 +315,7 @@ impl Attributes { if hist_items_len > 50000 { iterations = (iterations * 3 + 3) / 4; } - if hist_items_len > 100000 { + if hist_items_len > 100_000 { iterations = (iterations * 3 + 3) / 4; iteration_limit *= 2.; } diff --git a/src/blur.rs b/src/blur.rs index 4941166..c6be1ff 100644 --- a/src/blur.rs +++ b/src/blur.rs @@ -6,23 +6,23 @@ fn transposing_1d_blur(src: &[u8], dst: &mut [u8], width: usize, height: usize, } for (j, row) in src.chunks_exact(width).enumerate() { - let mut sum = row[0] as u16 * size; + let mut sum = u16::from(row[0]) * size; for &v in &row[0..size as usize] { - sum += v as u16; + sum += u16::from(v); } for i in 0..size as usize { - sum -= row[0] as u16; - sum += row[i + size as usize] as u16; + sum -= u16::from(row[0]); + sum += u16::from(row[i + size as usize]); dst[i * height + j] = (sum / (size * 2)) as u8; } for i in size as usize..width - size as usize { - sum -= row[i - size as usize] as u16; - sum += row[i + size as usize] as u16; + sum -= u16::from(row[i - size as usize]); + sum += u16::from(row[i + size as usize]); dst[i * height + j] = (sum / (size * 2)) as u8; } for i in width - size as usize..width { - sum -= row[i - size as usize] as u16; - sum += row[width - 1] as u16; + sum -= u16::from(row[i - size as usize]); + sum += u16::from(row[width - 1]); dst[i * height + j] = (sum / (size * 2)) as u8; } } diff --git a/src/capi.rs b/src/capi.rs index 4e22341..3a7b3d6 100644 --- a/src/capi.rs +++ b/src/capi.rs @@ -2,16 +2,16 @@ //! For public stable a C FFI interface, see imagequant-sys crate instead. #![allow(missing_docs)] -use crate::Error; -use crate::RGBA; -use crate::Attributes; -use crate::Palette; -use crate::QuantizationResult; -use crate::Image; use crate::rows::RowCallback; +use crate::seacow::Pointer; use crate::seacow::RowBitmapMut; use crate::seacow::SeaCow; -use crate::seacow::Pointer; +use crate::Attributes; +use crate::Error; +use crate::Image; +use crate::Palette; +use crate::QuantizationResult; +use crate::RGBA; use std::mem::MaybeUninit; pub const LIQ_VERSION: u32 = 40000; diff --git a/src/hist.rs b/src/hist.rs index f69ef5c..4a0cb8f 100644 --- a/src/hist.rs +++ b/src/hist.rs @@ -122,7 +122,7 @@ impl Histogram { self.fixed_colors.insert(HashColor(c, idx as _)); } - if attr.progress(attr.progress_stage1 as f32 * 0.40) { + if attr.progress(f32::from(attr.progress_stage1) * 0.40) { return Err(Aborted); // bow can free the RGBA source if copy has been made in f_pixels } @@ -190,7 +190,7 @@ impl Histogram { } if attr.progress(0.) { return Err(Aborted); } - if attr.progress(attr.progress_stage1 as f32 * 0.89) { + if attr.progress(f32::from(attr.progress_stage1) * 0.89) { return Err(Aborted); } @@ -210,8 +210,8 @@ impl Histogram { } else { 0 }; self.hashmap.entry(px_int) - .and_modify(move |e| e.0 += boost as u32) - .or_insert((boost as u32, rgba)); + .and_modify(move |e| e.0 += u32::from(boost)) + .or_insert((u32::from(boost), rgba)); } fn reserve(&mut self, entries: usize) { @@ -253,7 +253,7 @@ impl Histogram { let pixels_row = &image_iter.row_rgba(&mut temp_row, row)[..width]; let importance_map = importance_map.next().map(move |m| &m[..width]).unwrap_or(&[]); for (col, px) in pixels_row.iter().copied().enumerate() { - self.add_color(px, importance_map.get(col).copied().unwrap_or(255) as u16); + self.add_color(px, u16::from(importance_map.get(col).copied().unwrap_or(255))); } } self.init_posterize_bits(posterize_bits); @@ -301,10 +301,8 @@ impl Histogram { counts[cluster_index as usize] += 1; - temp.push(TempHistItem { - color, cluster_index, weight, - }); - weight as f64 + temp.push(TempHistItem { color, weight, cluster_index }); + f64::from(weight) }).sum::(); let mut clusters = [Cluster { begin: 0, end: 0 }; LIQ_MAXCLUSTER]; @@ -336,11 +334,7 @@ impl Histogram { items[next_index].adjusted_weight = temp_item.weight; } - Ok(HistogramInternal { - items, - clusters, - total_perceptual_weight, - }) + Ok(HistogramInternal { items, total_perceptual_weight, clusters }) } } @@ -404,12 +398,12 @@ impl std::hash::Hasher for RgbaHasher { fn write_isize(&mut self, _i: isize) { unimplemented!() } } -/// libstd's HashSet is afraid of NaN. +/// libstd's `HashSet` is afraid of NaN. /// contains color + original index (since hashmap forgets order) #[derive(PartialEq, Debug)] pub(crate) struct HashColor(pub f_pixel, pub u32); -#[allow(clippy::derive_hash_xor_eq)] +#[allow(clippy::derived_hash_with_manual_eq)] impl Hash for HashColor { #[inline] fn hash(&self, state: &mut H) { diff --git a/src/image.rs b/src/image.rs index cc9fa01..0c5981b 100644 --- a/src/image.rs +++ b/src/image.rs @@ -1,14 +1,14 @@ use crate::attr::Attributes; use crate::blur::{liq_blur, liq_max3, liq_min3}; use crate::error::*; -use crate::LIQ_HIGH_MEMORY_LIMIT; -use crate::pal::{PalIndex, MAX_COLORS, MIN_OPAQUE_A, PalF, RGBA, f_pixel, gamma_lut}; -use crate::PushInCapacity; +use crate::pal::{f_pixel, gamma_lut, PalF, PalIndex, MAX_COLORS, MIN_OPAQUE_A, RGBA}; use crate::remap::DitherMapMode; use crate::rows::{DynamicRows, PixelsSource}; use crate::seacow::Pointer; use crate::seacow::RowBitmap; use crate::seacow::SeaCow; +use crate::PushInCapacity; +use crate::LIQ_HIGH_MEMORY_LIMIT; use rgb::ComponentMap; use std::mem::MaybeUninit; @@ -27,7 +27,6 @@ pub struct Image<'pixels> { } impl<'pixels> Image<'pixels> { - /// Makes an image from RGBA pixels. /// /// See the [`rgb`] and [`bytemuck`](//lib.rs/bytemuck) crates for making `[RGBA]` slices from `[u8]` slices. @@ -160,7 +159,7 @@ impl<'pixels> Image<'pixels> { i += 1; } while lastcol <= col { - edges[lastcol] = ((edges[lastcol] as u16 + 128) as f32 + edges[lastcol] = ((u16::from(edges[lastcol]) + 128) as f32 * (255. / (255 + 128) as f32) * (1. - 20. / (20 + neighbor_count) as f32)) as u8; @@ -234,7 +233,7 @@ impl<'pixels> Image<'pixels> { } /// Builds two maps: - /// importance_map - approximation of areas with high-frequency noise, except straight edges. 1=flat, 0=noisy. + /// `importance_map` - approximation of areas with high-frequency noise, except straight edges. 1=flat, 0=noisy. /// edges - noise map including all edges pub(crate) fn contrast_maps(&mut self) -> Result<(), Error> { let width = self.width(); diff --git a/src/kmeans.rs b/src/kmeans.rs index 6d57717..eb832a7 100644 --- a/src/kmeans.rs +++ b/src/kmeans.rs @@ -1,8 +1,8 @@ -use crate::Error; use crate::hist::{HistItem, HistogramInternal}; use crate::nearest::Nearest; use crate::pal::{f_pixel, PalF, PalIndex, PalPop}; use crate::rayoff::*; +use crate::Error; use rgb::alt::ARGB; use rgb::ComponentMap; use std::cell::RefCell; @@ -34,8 +34,8 @@ impl Kmeans { #[inline] pub fn update_color(&mut self, px: f_pixel, value: f32, matched: PalIndex) { let c = &mut self.averages[matched as usize]; - c.sum += (px.0 * value).map(|c| c as f64); - c.total += value as f64; + c.sum += (px.0 * value).map(|c| f64::from(c)); + c.total += f64::from(value); } pub fn finalize(self, palette: &mut PalF) -> f64 { @@ -75,9 +75,9 @@ impl Kmeans { .map(RefCell::into_inner) .reduce(Kmeans::try_merge) .transpose()? - .map(|kmeans| { + .map_or(0., |kmeans| { kmeans.finalize(palette) / total - }).unwrap_or(0.); + }); replace_unused_colors(palette, hist)?; Ok(diff) @@ -94,9 +94,9 @@ impl Kmeans { diff = new_diff; item.adjusted_weight = (item.perceptual_weight + 2. * item.adjusted_weight) * (0.5 + diff); } - debug_assert!((diff as f64) < 1e20); + debug_assert!(f64::from(diff) < 1e20); self.update_color(px, item.adjusted_weight, matched); - (diff * item.perceptual_weight) as f64 + f64::from(diff * item.perceptual_weight) }).sum::(); } @@ -125,7 +125,7 @@ fn replace_unused_colors(palette: &mut PalF, hist: &HistogramInternal) -> Result for pal_idx in 0..palette.len() { let pop = palette.pop_as_slice()[pal_idx]; if pop.popularity() == 0. && !pop.is_fixed() { - let n = Nearest::new(&palette)?; + let n = Nearest::new(palette)?; let mut worst = None; let mut worst_diff = 0.; let colors = palette.as_slice(); diff --git a/src/lib.rs b/src/lib.rs index 0b7712a..9bad639 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -25,10 +25,10 @@ mod rayoff; #[cfg(feature = "threads")] mod rayoff { - pub(crate) use rayon::prelude::{ParallelSliceMut, ParallelIterator, ParallelBridge}; - pub(crate) use thread_local::ThreadLocal; - pub(crate) use rayon::scope; pub(crate) use num_cpus::get as num_cpus; + pub(crate) use rayon::prelude::{ParallelBridge, ParallelIterator, ParallelSliceMut}; + pub(crate) use rayon::scope; + pub(crate) use thread_local::ThreadLocal; } /// Use imagequant-sys crate instead @@ -149,7 +149,7 @@ fn poke_it() { // The magic happens in quantize() let mut res = match liq.quantize(img) { Ok(res) => res, - Err(err) => panic!("Quantization failed, because: {:?}", err), + Err(err) => panic!("Quantization failed, because: {err:?}"), }; // Enable dithering for subsequent remappings @@ -176,7 +176,7 @@ fn set_importance_map() { img.set_importance_map(&map[..]).unwrap(); let mut res = liq.quantize(&mut img).unwrap(); let pal = res.palette(); - assert_eq!(1, pal.len(), "{:?}", pal); + assert_eq!(1, pal.len(), "{pal:?}"); assert_eq!(bitmap[0], pal[0]); } diff --git a/src/mediancut.rs b/src/mediancut.rs index f582490..24bd8d1 100644 --- a/src/mediancut.rs +++ b/src/mediancut.rs @@ -1,9 +1,9 @@ -use crate::PushInCapacity; use crate::hist::{HistItem, HistogramInternal}; use crate::pal::{f_pixel, PalF, PalPop}; use crate::pal::{PalLen, ARGBF}; use crate::quant::quality_to_mse; -use crate::{OrdFloat, Error}; +use crate::PushInCapacity; +use crate::{Error, OrdFloat}; use rgb::ComponentMap; use rgb::ComponentSlice; use std::cmp::Reverse; @@ -32,7 +32,7 @@ impl<'hist> MBox<'hist> { let weight_sum = hist.iter().map(|a| { debug_assert!(a.adjusted_weight.is_finite()); debug_assert!(a.adjusted_weight > 0.); - a.adjusted_weight as f64 + f64::from(a.adjusted_weight) }).sum(); Self::new_c(hist, weight_sum, weighed_average_color(hist)) } @@ -86,7 +86,7 @@ impl<'hist> MBox<'hist> { pub fn compute_total_error(&mut self) -> f64 { let avg = self.avg_color; - let e = self.colors.iter().map(move |a| avg.diff(&a.color) as f64 * a.perceptual_weight as f64).sum::(); + let e = self.colors.iter().map(move |a| f64::from(avg.diff(&a.color)) * f64::from(a.perceptual_weight)).sum::(); self.total_error = Some(e); e } @@ -128,7 +128,7 @@ impl<'hist> MBox<'hist> { let w = median.diff(&a.color).sqrt() * ((1. + a.adjusted_weight).sqrt() - 1.); debug_assert!(w.is_finite()); a.mc_color_weight = w; - w as f64 + f64::from(w) }) .sum() } @@ -141,7 +141,7 @@ impl<'hist> MBox<'hist> { let break_at = hist_item_sort_half(self.colors, half_weight).max(1); let (left, right) = self.colors.split_at_mut(break_at); - let left_sum = left.iter().map(|a| a.adjusted_weight as f64).sum(); + let left_sum = left.iter().map(|a| f64::from(a.adjusted_weight)).sum(); let right_sum = self.adjusted_weight_sum - left_sum; [MBox::new_s(left, left_sum, other_boxes), @@ -192,7 +192,7 @@ fn hist_item_sort_half(mut base: &mut [HistItem], mut weight_half_sum: f64) -> u loop { let partition = qsort_partition(base); let (left, right) = base.split_at_mut(partition + 1); // +1, because pivot stays on the left side - let left_sum = left.iter().map(|c| c.mc_color_weight as f64).sum::(); + let left_sum = left.iter().map(|c| f64::from(c.mc_color_weight)).sum::(); if left_sum >= weight_half_sum { match left.get_mut(..partition) { // trim pivot point, avoid panick branch in [] Some(left) if !left.is_empty() => { base = left; continue; }, @@ -266,7 +266,7 @@ impl<'hist> MedianCutter<'hist> { b.colors.iter_mut().for_each(move |a| a.tmp.likely_palette_index = i as _); // store total color popularity (perceptual_weight is approximation of it) - let pop = b.colors.iter().map(|a| a.perceptual_weight as f64).sum::(); + let pop = b.colors.iter().map(|a| f64::from(a.perceptual_weight)).sum::(); palette.push(b.avg_color, PalPop::new(pop as f32)); } palette @@ -278,7 +278,7 @@ impl<'hist> MedianCutter<'hist> { while self.boxes.len() < self.target_colors as usize { // first splits boxes that exceed quality limit (to have colors for things like odd green pixel), // later raises the limit to allow large smooth areas/gradients get colors. - let fraction_done = self.boxes.len() as f64 / (self.target_colors as f64); + let fraction_done = self.boxes.len() as f64 / f64::from(self.target_colors); let current_max_mse = max_mse + fraction_done * 16. * max_mse; let bi = match self.take_best_splittable_box(current_max_mse) { Some(bi) => bi, @@ -300,9 +300,9 @@ impl<'hist> MedianCutter<'hist> { .filter(|(_, b)| b.colors.len() > 1) .map(move |(i, b)| { let cv = b.variance.r.max(b.variance.g).max(b.variance.b); - let mut thissum = b.adjusted_weight_sum * cv.max(b.variance.a) as f64; - if b.max_error as f64 > max_mse { - thissum = thissum * b.max_error as f64 / max_mse; + let mut thissum = b.adjusted_weight_sum * f64::from(cv.max(b.variance.a)); + if f64::from(b.max_error) > max_mse { + thissum = thissum * f64::from(b.max_error) / max_mse; } (i, thissum) }) diff --git a/src/nearest.rs b/src/nearest.rs index 713ec1e..3a919f8 100644 --- a/src/nearest.rs +++ b/src/nearest.rs @@ -1,7 +1,7 @@ -use crate::pal::MAX_COLORS; use crate::pal::PalIndex; +use crate::pal::MAX_COLORS; use crate::pal::{f_pixel, PalF}; -use crate::{OrdFloat, Error}; +use crate::{Error, OrdFloat}; impl<'pal> Nearest<'pal> { #[inline(never)] @@ -73,7 +73,7 @@ pub struct Visitor { impl Visitor { #[inline] fn visit(&mut self, distance: f32, distance_squared: f32, idx: PalIndex) { - if distance_squared < self.distance_squared && self.exclude != idx as i16 { + if distance_squared < self.distance_squared && self.exclude != i16::from(idx) { self.distance = distance; self.distance_squared = distance_squared; self.idx = idx; @@ -81,7 +81,6 @@ impl Visitor { } } - pub(crate) struct Node { vantage_point: f_pixel, inner: NodeInner, diff --git a/src/pal.rs b/src/pal.rs index ff30a41..eaee418 100644 --- a/src/pal.rs +++ b/src/pal.rs @@ -1,5 +1,5 @@ -use arrayvec::ArrayVec; use crate::hist::{FixedColorsSet, HashColor}; +use arrayvec::ArrayVec; use rgb::ComponentMap; use std::ops::{Deref, DerefMut}; @@ -53,8 +53,8 @@ impl f_pixel { unsafe { use std::arch::aarch64::*; - let px = vld1q_f32(self as *const f_pixel as *const f32); - let py = vld1q_f32(other as *const f_pixel as *const f32); + let px = vld1q_f32((self as *const f_pixel).cast::()); + let py = vld1q_f32((other as *const f_pixel).cast::()); // y.a - x.a let mut alphas = vsubq_f32(py, px); @@ -134,7 +134,7 @@ impl f_pixel { } pub fn from_rgba(gamma_lut: &[f32; 256], px: RGBA) -> Self { - let a = px.a as f32 / 255.; + let a = f32::from(px.a) / 255.; Self(ARGBF { a: a * LIQ_WEIGHT_A, r: gamma_lut[px.r as usize] * LIQ_WEIGHT_R * a, @@ -358,6 +358,7 @@ impl std::ops::DerefMut for Palette { impl Palette { /// Palette colors #[inline(always)] + #[must_use] pub fn as_slice(&self) -> &[RGBA] { &self.entries[..self.count as usize] } @@ -397,7 +398,7 @@ fn pal_test() { let mut p = PalF::new(); let gamma = gamma_lut(0.45455); for i in 0..=255u8 { - let rgba = RGBA::new(i,i,i,100+i/2); + let rgba = RGBA::new(i, i, i, 100 + i / 2); p.push(f_pixel::from_rgba(&gamma, rgba), PalPop::new(1.)); assert_eq!(i as usize + 1, p.len()); assert_eq!(i as usize + 1, p.pop_as_slice().len()); @@ -410,7 +411,7 @@ fn pal_test() { for i in 0..=255u8 { let rgba = p.as_slice()[i as usize].to_rgb(0.45455); - assert_eq!(rgba, RGBA::new(i,i,i,100+i/2)); - assert_eq!(int_pal[i as usize], RGBA::new(i,i,i,100+i/2)); + assert_eq!(rgba, RGBA::new(i, i, i, 100 + i / 2)); + assert_eq!(int_pal[i as usize], RGBA::new(i, i, i, 100 + i / 2)); } } diff --git a/src/quant.rs b/src/quant.rs index 2294222..d44e045 100644 --- a/src/quant.rs +++ b/src/quant.rs @@ -1,15 +1,15 @@ -use arrayvec::ArrayVec; use crate::attr::{Attributes, ControlFlow}; use crate::error::*; use crate::hist::{FixedColorsSet, HistogramInternal}; use crate::image::Image; use crate::kmeans::Kmeans; use crate::mediancut::mediancut; -use crate::OrdFloat; use crate::pal::{PalIndex, PalF, PalLen, PalPop, Palette, LIQ_WEIGHT_MSE, MAX_COLORS, MAX_TRANSP_A, RGBA}; use crate::remap::{mse_to_standard_mse, DitherMapMode, Remapped}; use crate::remap::{remap_to_palette, remap_to_palette_floyd}; use crate::seacow::RowBitmapMut; +use crate::OrdFloat; +use arrayvec::ArrayVec; use std::cmp::Reverse; use std::fmt; use std::mem::MaybeUninit; @@ -30,13 +30,13 @@ pub struct QuantizationResult { impl QuantizationResult { pub(crate) fn new(attr: &Attributes, hist: HistogramInternal, freeze_result_colors: bool, fixed_colors: &FixedColorsSet, gamma: f64) -> Result { - if attr.progress(attr.progress_stage1 as f32) { return Err(Aborted); } + if attr.progress(f32::from(attr.progress_stage1)) { return Err(Aborted); } let (max_mse, target_mse, target_mse_is_zero) = attr.target_mse(hist.items.len()); let (mut palette, palette_error) = find_best_palette(attr, target_mse, target_mse_is_zero, max_mse, hist, fixed_colors)?; if freeze_result_colors { palette.iter_mut().for_each(|(_, p)| *p = p.to_fixed()); } - if attr.progress(attr.progress_stage1 as f32 + attr.progress_stage2 as f32 + attr.progress_stage3 as f32 * 0.95) { + if attr.progress(f32::from(attr.progress_stage1) + f32::from(attr.progress_stage2) + f32::from(attr.progress_stage3) * 0.95) { return Err(Aborted); } if let (Some(palette_error), Some(max_mse)) = (palette_error, max_mse) { @@ -324,7 +324,7 @@ impl fmt::Debug for QuantizationResult { /// Repeats mediancut with different histogram weights to find palette with minimum error. /// -/// feedback_loop_trials controls how long the search will take. < 0 skips the iteration. +/// `feedback_loop_trials` controls how long the search will take. < 0 skips the iteration. #[allow(clippy::or_fun_call)] pub(crate) fn find_best_palette(attr: &Attributes, target_mse: f64, target_mse_is_zero: bool, max_mse: Option, mut hist: HistogramInternal, fixed_colors: &FixedColorsSet) -> Result<(PalF, Option), Error> { let few_input_colors = hist.items.len() + fixed_colors.len() <= attr.max_colors as usize; @@ -345,8 +345,8 @@ pub(crate) fn find_best_palette(attr: &Attributes, target_mse: f64, target_mse_i let mut new_palette = mediancut(&mut hist, max_colors - fixed_colors.len() as PalLen, target_mse * target_mse_overshoot, max_mse_per_color)? .with_fixed_colors(max_colors, fixed_colors); - let stage_done = 1. - (trials_left.max(0) as f32 / (total_trials + 1) as f32).powi(2); - let overall_done = attr.progress_stage1 as f32 + stage_done * attr.progress_stage2 as f32; + let stage_done = 1. - (f32::from(trials_left.max(0)) / f32::from(total_trials + 1)).powi(2); + let overall_done = f32::from(attr.progress_stage1) + stage_done * f32::from(attr.progress_stage2); attr.verbose_print(format!(" selecting colors...{}%", (100. * stage_done) as u8)); if trials_left <= 0 { break Some(new_palette); } @@ -384,8 +384,8 @@ fn refine_palette(palette: &mut PalF, attr: &Attributes, hist: &mut HistogramInt attr.verbose_print(" moving colormap towards local minimum"); let mut i = 0; while i < iterations { - let stage_done = i as f32 / iterations as f32; - let overall_done = attr.progress_stage1 as f32 + attr.progress_stage2 as f32 + stage_done * attr.progress_stage3 as f32 * 0.89; + let stage_done = f32::from(i) / f32::from(iterations); + let overall_done = f32::from(attr.progress_stage1) + f32::from(attr.progress_stage2) + stage_done * f32::from(attr.progress_stage3) * 0.89; if attr.progress(overall_done) { break; } @@ -421,8 +421,8 @@ pub(crate) fn quality_to_mse(quality: u8) -> f64 { return 1e20; // + epsilon for floating point errors } if quality >= 100 { return 0.; } - let extra_low_quality_fudge = (0.016 / (0.001 + quality as f64) - 0.001).max(0.); - LIQ_WEIGHT_MSE * (extra_low_quality_fudge + 2.5 / (210. + quality as f64).powf(1.2) * (100.1 - quality as f64) / 100.) + let extra_low_quality_fudge = (0.016 / (0.001 + f64::from(quality)) - 0.001).max(0.); + LIQ_WEIGHT_MSE * (extra_low_quality_fudge + 2.5 / (210. + f64::from(quality)).powf(1.2) * (100.1 - f64::from(quality)) / 100.) } pub(crate) fn mse_to_quality(mse: f64) -> u8 { diff --git a/src/rayoff.rs b/src/rayoff.rs index c5493a5..78d1418 100644 --- a/src/rayoff.rs +++ b/src/rayoff.rs @@ -1,5 +1,5 @@ -use std::slice::ChunksMut; use once_cell::unsync::OnceCell; +use std::slice::ChunksMut; pub(crate) struct ThreadLocal(OnceCell); diff --git a/src/remap.rs b/src/remap.rs index f3224b9..6ce1f5a 100644 --- a/src/remap.rs +++ b/src/remap.rs @@ -1,8 +1,8 @@ -use crate::error::*; +use crate::error::Error; use crate::image::Image; use crate::kmeans::Kmeans; use crate::nearest::Nearest; -use crate::pal::{ARGBF, LIQ_WEIGHT_MSE, MIN_OPAQUE_A, PalF, PalIndex, Palette, f_pixel}; +use crate::pal::{f_pixel, PalF, PalIndex, Palette, ARGBF, LIQ_WEIGHT_MSE, MIN_OPAQUE_A}; use crate::quant::QuantizationResult; use crate::rayoff::*; use crate::rows::{temp_buf, DynamicRows}; @@ -74,12 +74,12 @@ pub(crate) fn remap_to_palette<'x, 'b: 'x>(px: &mut DynamicRows, background: Opt if let Some(bg) = bg_pixels.get(col) { let bg_diff = bg.diff(inp); if bg_diff <= diff { - remapping_error += bg_diff as f64; + remapping_error += f64::from(bg_diff); out.write(transparent_index); continue; } } - remapping_error += diff as f64; + remapping_error += f64::from(diff); out.write(matched); kmeans.update_color(*inp, 1., matched); } @@ -95,7 +95,7 @@ pub(crate) fn remap_to_palette<'x, 'b: 'x>(px: &mut DynamicRows, background: Opt .map(|t| RefCell::into_inner(t).0) .reduce(Kmeans::merge) { kmeans.finalize(palette); } - let remapping_error = remapping_error / (px.width * px.height) as f64; + let remapping_error = remapping_error / f64::from(px.width * px.height); Ok((remapping_error, unsafe { output_pixels.assume_init() })) } @@ -140,7 +140,7 @@ fn get_dithered_pixel(dither_level: f32, max_dither_error: f32, thiserr: f_pixel /// Uses edge/noise map to apply dithering only to flat areas. Dithering on edges creates jagged lines, and noisy areas are "naturally" dithered. /// -/// If output_image_is_remapped is true, only pixels noticeably changed by error diffusion will be written to output image. +/// If `output_image_is_remapped` is true, only pixels noticeably changed by error diffusion will be written to output image. #[inline(never)] pub(crate) fn remap_to_palette_floyd(input_image: &mut Image, mut output_pixels: RowBitmapMut<'_, MaybeUninit>, palette: &PalF, quant: &QuantizationResult, max_dither_error: f32, output_image_is_remapped: bool) -> Result<(), Error> { let progress_stage1 = if quant.use_dither_map != DitherMapMode::None { 20 } else { 0 }; @@ -256,7 +256,7 @@ fn dither_row(row_pixels: &[f_pixel], output_pixels_row: &mut [MaybeUninit = dyn Fn(&mut [MaybeUninit], usize) + Send + Sync + 'a; pub(crate) enum PixelsSource<'pixels, 'rows> { /// The `pixels` field is never read, but it is used to store the rows. #[allow(dead_code)] - Pixels { rows: SeaCow<'rows, Pointer>, pixels: Option> }, + Pixels { + rows: SeaCow<'rows, Pointer>, + pixels: Option>, + }, Callback(Box>), }