Skip to content

Commit

Permalink
Clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
kornelski committed Oct 4, 2023
1 parent 0b58ead commit 81d44aa
Show file tree
Hide file tree
Showing 12 changed files with 58 additions and 26 deletions.
13 changes: 9 additions & 4 deletions imagequant-sys/src/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
//! This crate is not supposed to be used in Rust directly. For Rust, see the parent [imagequant](https://lib.rs/imagequant) crate.
#![allow(non_camel_case_types)]
#![allow(clippy::missing_safety_doc)]
#![allow(clippy::wildcard_imports)]
#![allow(clippy::items_after_statements)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_possible_wrap)]

use imagequant::capi::*;
use imagequant::Error::LIQ_OK;
Expand Down Expand Up @@ -79,7 +83,7 @@ pub(crate) static LIQ_FREED_MAGIC: MagicTag = MagicTag(b"liq_freed_magic\0".as_p

#[no_mangle]
#[inline(never)]
unsafe fn liq_received_invalid_pointer(ptr: *const u8) -> bool {
unsafe extern "C" fn liq_received_invalid_pointer(ptr: *const u8) -> bool {
if ptr.is_null() {
return true;
}
Expand All @@ -91,6 +95,7 @@ macro_rules! bad_object {
($obj:expr, $tag:expr) => {{
let obj = &*$obj;
#[allow(unused_unsafe)]
#[allow(clippy::ptr_as_ptr)]
let bork = if cfg!(miri) { false } else { unsafe { liq_received_invalid_pointer((obj as *const _ as *const u8)) } };
(bork || (($obj).magic_header != $tag))
}};
Expand Down Expand Up @@ -200,7 +205,7 @@ pub unsafe extern "C" fn liq_set_log_callback(attr: &mut liq_attr, callback: liq
if bad_object!(attr, LIQ_ATTR_MAGIC) { return; }
attr.inner.set_log_callback(move |attr, msg| {
if let Ok(tmp) = CString::new(msg) {
callback(attr_to_liq_attr_ptr(attr), tmp.as_ptr(), user_info)
callback(attr_to_liq_attr_ptr(attr), tmp.as_ptr(), user_info);
}
});
}
Expand Down Expand Up @@ -507,7 +512,7 @@ pub extern "C" fn liq_get_remapping_quality(result: &liq_result) -> c_int {

#[no_mangle]
#[inline(never)]
pub fn liq_image_quantize(img: &mut liq_image, attr: &mut liq_attr, write_only_output: &mut MaybeUninit<Option<Box<liq_result>>>) -> liq_error {
pub extern "C" fn liq_image_quantize(img: &mut liq_image, attr: &mut liq_attr, write_only_output: &mut MaybeUninit<Option<Box<liq_result>>>) -> liq_error {
if bad_object!(attr, LIQ_ATTR_MAGIC) ||
bad_object!(img, LIQ_IMAGE_MAGIC) { return Error::InvalidPointer; }
let attr = &mut attr.inner;
Expand Down Expand Up @@ -734,7 +739,7 @@ fn c_callback_test_c() {
let user_data = user_data.0.cast::<i32>();
*user_data += 1;
}
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();
let mut img = liq_image_create_custom(&a, get_row, AnySyncSendPtr(std::ptr::addr_of_mut!(called).cast::<c_void>()), 123, 5, 0.).unwrap();
liq_quantize_image(&mut a, &mut img).unwrap()
};
assert!(called > 5 && called < 50);
Expand Down
4 changes: 4 additions & 0 deletions src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ impl Attributes {

// true == abort
#[inline]
#[must_use]
pub(crate) fn progress(self: &Attributes, percent: f32) -> bool {
if let Some(f) = &self.progress_callback {
f(percent) == ControlFlow::Break
Expand All @@ -274,6 +275,7 @@ impl Attributes {
}
}

#[must_use]
pub(crate) fn feedback_loop_trials(&self, hist_items: usize) -> u16 {
let mut feedback_loop_trials = self.feedback_loop_trials;
if hist_items > 5000 {
Expand Down Expand Up @@ -303,6 +305,7 @@ impl Attributes {
}

/// returns iterations, `iteration_limit`
#[must_use]
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;
Expand All @@ -326,6 +329,7 @@ impl Attributes {
}

#[inline]
#[must_use]
pub(crate) fn posterize_bits(&self) -> u8 {
self.min_posterization_output.max(self.min_posterization_input)
}
Expand Down
6 changes: 5 additions & 1 deletion src/capi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,22 @@ use std::mem::MaybeUninit;

pub const LIQ_VERSION: u32 = 40000;

#[must_use]
pub fn liq_get_palette_impl(r: &mut QuantizationResult) -> &Palette {
r.int_palette()
}

#[must_use]
pub unsafe fn liq_image_create_rgba_rows_impl<'rows>(attr: &Attributes, rows: &'rows [*const RGBA], width: u32, height: u32, gamma: f64) -> Option<crate::image::Image<'rows>> {
let rows = SeaCow::borrowed(std::mem::transmute::<&'rows [*const RGBA], &'rows [Pointer<RGBA>]>(rows));
let rows = SeaCow::borrowed(&*(rows as *const [*const rgb::RGBA<u8>] as *const [Pointer<rgb::RGBA<u8>>]));
let rows_slice = rows.as_slice();
if rows_slice.iter().any(|r| r.0.is_null()) {
return None;
}
crate::image::Image::new_internal(attr, crate::rows::PixelsSource::Pixels { rows, pixels: None }, width, height, gamma).ok()
}

#[must_use]
pub unsafe fn liq_image_create_rgba_bitmap_impl<'rows>(attr: &Attributes, rows: Box<[*const RGBA]>, width: u32, height: u32, gamma: f64) -> Option<crate::image::Image<'rows>> {
let rows = SeaCow::boxed(std::mem::transmute::<Box<[*const RGBA]>, Box<[Pointer<RGBA>]>>(rows));
let rows_slice = rows.as_slice();
Expand All @@ -38,6 +41,7 @@ pub unsafe fn liq_image_create_rgba_bitmap_impl<'rows>(attr: &Attributes, rows:
crate::image::Image::new_internal(attr, crate::rows::PixelsSource::Pixels { rows, pixels: None }, width, height, gamma).ok()
}

#[must_use]
pub unsafe fn liq_image_create_custom_impl<'rows>(attr: &Attributes, row_callback: Box<RowCallback<'rows>>, width: u32, height: u32, gamma: f64) -> Option<Image<'rows>> {
Image::new_internal(attr, crate::rows::PixelsSource::Callback(row_callback), width, height, gamma).ok()
}
Expand Down
2 changes: 1 addition & 1 deletion src/hist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ impl Histogram {
}));
}

pub(crate) fn add_pixel_rows(&mut self, image: &mut DynamicRows<'_, '_>, importance_map: Option<&[u8]>, posterize_bits: u8) -> Result<(), Error> {
pub(crate) fn add_pixel_rows(&mut self, image: &DynamicRows<'_, '_>, importance_map: Option<&[u8]>, posterize_bits: u8) -> Result<(), Error> {
let width = image.width as usize;
let height = image.height as usize;

Expand Down
23 changes: 9 additions & 14 deletions src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,19 +245,14 @@ impl<'pixels> Image<'pixels> {
return Ok(()); // shrug
}

let noise = match self.importance_map.as_deref_mut() {
Some(n) => n,
None => {
let vec = try_zero_vec(width * height)?;
self.importance_map.get_or_insert_with(move || vec.into_boxed_slice())
},
let noise = if let Some(n) = self.importance_map.as_deref_mut() { n } else {
let vec = try_zero_vec(width * height)?;
self.importance_map.get_or_insert_with(move || vec.into_boxed_slice())
};
let edges = match self.edges.as_mut() {
Some(e) => e,
None => {
let vec = try_zero_vec(width * height)?;
self.edges.get_or_insert_with(move || vec.into_boxed_slice())
},

let edges = if let Some(e) = self.edges.as_mut() { e } else {
let vec = try_zero_vec(width * height)?;
self.edges.get_or_insert_with(move || vec.into_boxed_slice())
};

let mut rows_iter = self.px.all_rows_f()?.chunks_exact(width);
Expand All @@ -278,10 +273,10 @@ impl<'pixels> Image<'pixels> {
curr = next;
next = curr_row[(i + 1).min(width - 1)].0;
// contrast is difference between pixels neighbouring horizontally and vertically
let horiz = (prev + next - curr * 2.).map(|c| c.abs()); // noise is amplified
let horiz = (prev + next - curr * 2.).map(f32::abs); // noise is amplified
let prevl = prev_row[i].0;
let nextl = next_row[i].0;
let vert = (prevl + nextl - curr * 2.).map(|c| c.abs());
let vert = (prevl + nextl - curr * 2.).map(f32::abs);
let horiz = horiz.a.max(horiz.r).max(horiz.g.max(horiz.b));
let vert = vert.a.max(vert.r).max(vert.g.max(vert.b));
let edge = horiz.max(vert);
Expand Down
9 changes: 7 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,14 @@
//! See `examples/` directory for example code.
#![doc(html_logo_url = "https://pngquant.org/pngquant-logo.png")]
#![deny(missing_docs)]
#![allow(clippy::bool_to_int_with_if)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::doc_markdown)]
#![allow(clippy::if_not_else)]
#![allow(clippy::inline_always)]
#![allow(clippy::items_after_statements)]
#![allow(clippy::map_unwrap_or)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::redundant_closure_for_method_calls)]
#![allow(clippy::unreadable_literal)]
Expand Down Expand Up @@ -95,11 +100,11 @@ fn histogram() {
let attr = Attributes::new();
let mut hist = Histogram::new(&attr);

let bitmap1 = vec![RGBA {r:0, g:0, b:0, a:0}; 1];
let bitmap1 = [RGBA {r:0, g:0, b:0, a:0}; 1];
let mut image1 = attr.new_image(&bitmap1[..], 1, 1, 0.0).unwrap();
hist.add_image(&attr, &mut image1).unwrap();

let bitmap2 = vec![RGBA {r:255, g:255, b:255, a:255}; 1];
let bitmap2 = [RGBA {r:255, g:255, b:255, a:255}; 1];
let mut image2 = attr.new_image(&bitmap2[..], 1, 1, 0.0).unwrap();
hist.add_image(&attr, &mut image2).unwrap();

Expand Down
2 changes: 1 addition & 1 deletion src/mediancut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ impl<'hist> MBox<'hist> {
fn box_stats(hist: &[HistItem], avg_color: &f_pixel) -> (ARGBF, f32) {
let mut variance = ARGBF::default();
let mut max_error = 0.;
for a in hist.iter() {
for a in hist {
variance += (avg_color.0 - a.color.0).map(|c| c * c) * a.adjusted_weight;
let diff = avg_color.diff(&a.color);
if diff > max_error {
Expand Down
2 changes: 1 addition & 1 deletion src/nearest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ fn vp_create_node(indexes: &mut [MapIndex], items: &PalF) -> Node {
return Node {
vantage_point: palette[usize::from(indexes[0].idx)],
idx: indexes[0].idx,
inner: NodeInner::Leaf { len: 0, idxs: [Default::default(); LEAF_MAX_SIZE], colors: Box::new([Default::default(); LEAF_MAX_SIZE]) },
inner: NodeInner::Leaf { len: 0, idxs: [0; LEAF_MAX_SIZE], colors: Box::new([f_pixel::default(); LEAF_MAX_SIZE]) },
};
}

Expand Down
2 changes: 2 additions & 0 deletions src/pal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ impl PalPop {
self.0 < 0.
}

#[must_use]
pub fn to_fixed(self) -> Self {
if self.0 < 0. {
return self;
Expand All @@ -195,6 +196,7 @@ impl PalPop {
}

#[inline(always)]
#[must_use]
pub fn popularity(self) -> f32 {
self.0.abs()
}
Expand Down
3 changes: 3 additions & 0 deletions src/quant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ impl QuantizationResult {
}

/// Approximate mean square error of the palette used for the most recent remapping
#[must_use]
pub fn remapping_error(&self) -> Option<f64> {
self.remapped.as_ref()
.and_then(|re| re.palette_error)
Expand All @@ -182,6 +183,7 @@ impl QuantizationResult {
}

/// Palette remapping error mapped back to 0-100 scale, same as the scale in [`Attributes::set_quality()`]
#[must_use]
pub fn remapping_quality(&self) -> Option<u8> {
self.remapped.as_ref()
.and_then(|re| re.palette_error)
Expand All @@ -193,6 +195,7 @@ impl QuantizationResult {
///
/// It's slighly better if you get palette from the [`remapped()`][Self::remapped] call instead
#[inline]
#[must_use]
pub fn palette(&mut self) -> &[RGBA] {
self.int_palette().as_slice()
}
Expand Down
8 changes: 7 additions & 1 deletion src/rows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub(crate) struct DynamicRowsIter<'parent, 'pixels, 'rows> {
}

impl<'a, 'pixels, 'rows> DynamicRowsIter<'a, 'pixels, 'rows> {
#[must_use]
pub fn row_f<'px>(&'px mut self, temp_row: &mut [MaybeUninit<RGBA>], row: usize) -> &'px [f_pixel] {
debug_assert_eq!(temp_row.len(), self.px.width as usize);
match self.px.f_pixels.as_ref() {
Expand All @@ -50,6 +51,7 @@ impl<'a, 'pixels, 'rows> DynamicRowsIter<'a, 'pixels, 'rows> {
}
}

#[must_use]
pub fn row_f_shared<'px>(&'px self, temp_row: &mut [MaybeUninit<RGBA>], temp_row_f: &'px mut [MaybeUninit<f_pixel>], row: usize) -> &'px [f_pixel] {
match self.px.f_pixels.as_ref() {
Some(pixels) => &pixels[self.px.width as usize * row..],
Expand All @@ -62,6 +64,7 @@ impl<'a, 'pixels, 'rows> DynamicRowsIter<'a, 'pixels, 'rows> {
}
}

#[must_use]
pub fn row_rgba<'px>(&'px self, temp_row: &'px mut [MaybeUninit<RGBA>], row: usize) -> &'px [RGBA] {
self.px.row_rgba(temp_row, row)
}
Expand Down Expand Up @@ -96,6 +99,7 @@ impl<'pixels,'rows> DynamicRows<'pixels,'rows> {
unsafe { slice_assume_init_mut(row_f_pixels) }
}

#[must_use]
fn should_use_low_memory(&self) -> bool {
self.width() * self.height() > LIQ_HIGH_MEMORY_LIMIT / std::mem::size_of::<f_pixel>()
}
Expand Down Expand Up @@ -197,11 +201,13 @@ impl<'pixels,'rows> DynamicRows<'pixels,'rows> {
}

#[inline(always)]
#[must_use]
pub fn width(&self) -> usize {
self.width as usize
}

#[inline(always)]
#[must_use]
pub fn height(&self) -> usize {
self.height as usize
}
Expand Down Expand Up @@ -231,5 +237,5 @@ unsafe fn box_assume_init<T>(s: Box<[MaybeUninit<T>]>) -> Box<[T]> {

#[inline(always)]
unsafe fn slice_assume_init_mut<T>(s: &mut [MaybeUninit<T>]) -> &mut [T] {
std::mem::transmute(s)
&mut *(s as *mut [MaybeUninit<T>] as *mut [T])
}
10 changes: 9 additions & 1 deletion src/seacow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,15 @@ unsafe impl<T: Send + Sync> Sync for PointerMut<T> {}

impl<'a, T> SeaCow<'a, T> {
#[inline]
#[must_use]
pub fn borrowed(data: &'a [T]) -> Self {
Self {
inner: SeaCowInner::Borrowed(data),
}
}

#[inline]
#[must_use]
pub fn boxed(data: Box<[T]>) -> Self {
Self {
inner: SeaCowInner::Boxed(data),
Expand All @@ -42,6 +44,7 @@ impl<'a, T> SeaCow<'a, T> {
/// The pointer must be `malloc`-allocated
#[inline]
#[cfg(feature = "_internal_c_ffi")]
#[must_use]
pub unsafe fn c_owned(ptr: *mut T, len: usize, free_fn: unsafe extern fn(*mut c_void)) -> Self {
debug_assert!(!ptr.is_null());
debug_assert!(len > 0);
Expand Down Expand Up @@ -79,6 +82,7 @@ impl<'a, T> Drop for SeaCowInner<'a, T> {
}

impl<'a, T> SeaCow<'a, T> {
#[must_use]
pub fn as_slice(&self) -> &[T] {
match &self.inner {
#[cfg(feature = "_internal_c_ffi")]
Expand Down Expand Up @@ -127,6 +131,7 @@ enum MutCow<'a, T: ?Sized> {
}

impl<'a, T: ?Sized> MutCow<'a, T> {
#[must_use]
pub fn borrow_mut(&mut self) -> &mut T {
match self {
Self::Owned(a) => a,
Expand All @@ -137,6 +142,7 @@ impl<'a, T: ?Sized> MutCow<'a, T> {

impl<'a, T: Sync + Send + Copy + 'static> RowBitmapMut<'a, T> {
#[inline]
#[must_use]
pub fn new_contiguous(data: &mut [T], width: usize) -> Self {
Self {
rows: MutCow::Owned(data.chunks_exact_mut(width).map(|r| PointerMut(r.as_mut_ptr())).collect()),
Expand All @@ -147,9 +153,10 @@ impl<'a, T: Sync + Send + Copy + 'static> RowBitmapMut<'a, T> {
/// Inner pointers must be valid for `'a` too, and at least `width` large each
#[inline]
#[cfg(feature = "_internal_c_ffi")]
#[must_use]
pub unsafe fn new(rows: &'a mut [*mut T], width: usize) -> Self {
Self {
rows: MutCow::Borrowed(std::mem::transmute::<&'a mut [*mut T], &'a mut [PointerMut<T>]>(rows)),
rows: MutCow::Borrowed(&mut *(rows as *mut [*mut T] as *mut [PointerMut<T>])),
width,
}
}
Expand All @@ -168,6 +175,7 @@ impl<'a, T: Sync + Send + Copy + 'static> RowBitmapMut<'a, T> {
})
}

#[must_use]
pub(crate) fn len(&mut self) -> usize {
self.rows.borrow_mut().len()
}
Expand Down

0 comments on commit 81d44aa

Please sign in to comment.