diff --git a/benches/copy_from.rs b/benches/copy_from.rs index 37a4af8b9d..39a7d49383 100644 --- a/benches/copy_from.rs +++ b/benches/copy_from.rs @@ -6,7 +6,7 @@ pub fn bench_copy_from(c: &mut Criterion) { let mut dst = ImageBuffer::from_pixel(2048, 2048, Rgba([0u8, 0, 0, 255])); c.bench_function("copy_from", |b| { - b.iter(|| dst.copy_from(black_box(&src), 0, 0)) + b.iter(|| dst.copy_from(black_box(&src), 0, 0)); }); } diff --git a/benches/decode.rs b/benches/decode.rs index 87ebfda1bd..3a288b22f6 100644 --- a/benches/decode.rs +++ b/benches/decode.rs @@ -96,7 +96,7 @@ fn bench_load(c: &mut Criterion, def: &BenchDef) { group.bench_function(file_name.to_owned(), |b| { b.iter(|| { image::load_from_memory_with_format(&buf, def.format).unwrap(); - }) + }); }); } } diff --git a/benches/encode.rs b/benches/encode.rs index 8c1fd955db..c6339b5cb1 100644 --- a/benches/encode.rs +++ b/benches/encode.rs @@ -38,7 +38,7 @@ fn encode_all(c: &mut Criterion) { ]; for definition in BENCH_DEFS { - encode_definition(c, definition) + encode_definition(c, definition); } } @@ -55,7 +55,7 @@ fn encode_zeroed(group: &mut BenchGroup, with: &dyn Encoder, size: u32, color: E let im = vec![0; (color.bits_per_pixel() as usize * size as usize + 7) / 8 * size as usize]; group.bench_with_input( - BenchmarkId::new(format!("zero-{:?}-rawvec", color), size), + BenchmarkId::new(format!("zero-{color:?}-rawvec"), size), &im, |b, image| { let mut v = vec![]; @@ -64,7 +64,7 @@ fn encode_zeroed(group: &mut BenchGroup, with: &dyn Encoder, size: u32, color: E }, ); group.bench_with_input( - BenchmarkId::new(format!("zero-{:?}-bufvec", color), size), + BenchmarkId::new(format!("zero-{color:?}-bufvec"), size), &im, |b, image| { let mut v = vec![]; @@ -73,7 +73,7 @@ fn encode_zeroed(group: &mut BenchGroup, with: &dyn Encoder, size: u32, color: E }, ); group.bench_with_input( - BenchmarkId::new(format!("zero-{:?}-file", color), size), + BenchmarkId::new(format!("zero-{color:?}-file"), size), &im, |b, image| { let file = File::create("temp.bmp").unwrap(); diff --git a/examples/concat/main.rs b/examples/concat/main.rs index 63dcb09167..b36e88f681 100644 --- a/examples/concat/main.rs +++ b/examples/concat/main.rs @@ -2,7 +2,7 @@ use image::{GenericImage, GenericImageView, ImageBuffer, Pixel, Primitive}; /// Example showcasing a generic implementation of image concatenation. /// -/// The example images are coming from https://placeholder.com/ +/// The example images are coming from / /// /// Run from the root of the repository with: /// cargo run --release --example concat diff --git a/examples/opening.rs b/examples/opening.rs index 85d7615197..8e7c071eb9 100644 --- a/examples/opening.rs +++ b/examples/opening.rs @@ -24,7 +24,7 @@ fn main() { // The color method returns the image's ColorType println!("{:?}", im.color()); - let fout = &mut File::create(Path::new(&format!("{}.png", file))).unwrap(); + let fout = &mut File::create(Path::new(&format!("{file}.png"))).unwrap(); // Write the contents of this image to the Writer in PNG format. im.write_to(fout, ImageFormat::Png).unwrap(); diff --git a/examples/scaledown/main.rs b/examples/scaledown/main.rs index f0d3475af4..bd9e0fe48f 100644 --- a/examples/scaledown/main.rs +++ b/examples/scaledown/main.rs @@ -15,30 +15,28 @@ impl Elapsed { impl fmt::Display for Elapsed { fn fmt(&self, out: &mut fmt::Formatter) -> Result<(), fmt::Error> { match (self.0.as_secs(), self.0.subsec_nanos()) { - (0, n) if n < 1000 => write!(out, "{} ns", n), + (0, n) if n < 1000 => write!(out, "{n} ns"), (0, n) if n < 1_000_000 => write!(out, "{} µs", n / 1000), (0, n) => write!(out, "{} ms", n / 1_000_000), (s, n) if s < 10 => write!(out, "{}.{:02} s", s, n / 10_000_000), - (s, _) => write!(out, "{} s", s), + (s, _) => write!(out, "{s} s"), } } } fn main() { let img = image::open("examples/scaledown/test.jpg").unwrap(); - for &(name, filter) in [ + for &(name, filter) in &[ ("near", FilterType::Nearest), ("tri", FilterType::Triangle), ("cmr", FilterType::CatmullRom), ("gauss", FilterType::Gaussian), ("lcz2", FilterType::Lanczos3), - ] - .iter() - { + ] { let timer = Instant::now(); let scaled = img.resize(400, 400, filter); println!("Scaled by {} in {}", name, Elapsed::from(&timer)); - let mut output = File::create(&format!("test-{}.png", name)).unwrap(); + let mut output = File::create(&format!("test-{name}.png")).unwrap(); scaled.write_to(&mut output, ImageFormat::Png).unwrap(); } @@ -46,7 +44,7 @@ fn main() { let timer = Instant::now(); let scaled = img.thumbnail(*size, *size); println!("Thumbnailed to {} in {}", size, Elapsed::from(&timer)); - let mut output = File::create(format!("test-thumb{}.png", size)).unwrap(); + let mut output = File::create(format!("test-thumb{size}.png")).unwrap(); scaled.write_to(&mut output, ImageFormat::Png).unwrap(); } } diff --git a/examples/scaleup/main.rs b/examples/scaleup/main.rs index 14866a5125..e7e07f045c 100644 --- a/examples/scaleup/main.rs +++ b/examples/scaleup/main.rs @@ -15,36 +15,34 @@ impl Elapsed { impl fmt::Display for Elapsed { fn fmt(&self, out: &mut fmt::Formatter) -> Result<(), fmt::Error> { match (self.0.as_secs(), self.0.subsec_nanos()) { - (0, n) if n < 1000 => write!(out, "{} ns", n), + (0, n) if n < 1000 => write!(out, "{n} ns"), (0, n) if n < 1_000_000 => write!(out, "{} µs", n / 1000), (0, n) => write!(out, "{} ms", n / 1_000_000), (s, n) if s < 10 => write!(out, "{}.{:02} s", s, n / 10_000_000), - (s, _) => write!(out, "{} s", s), + (s, _) => write!(out, "{s} s"), } } } fn main() { let tiny = image::open("examples/scaleup/tinycross.png").unwrap(); - for &(name, filter) in [ + for &(name, filter) in &[ ("near", FilterType::Nearest), ("tri", FilterType::Triangle), ("xcmr", FilterType::CatmullRom), ("ygauss", FilterType::Gaussian), ("zlcz2", FilterType::Lanczos3), - ] - .iter() - { + ] { let timer = Instant::now(); let scaled = tiny.resize(32, 32, filter); println!("Scaled by {} in {}", name, Elapsed::from(&timer)); - let mut output = File::create(&format!("up2-{}.png", name)).unwrap(); + let mut output = File::create(&format!("up2-{name}.png")).unwrap(); scaled.write_to(&mut output, ImageFormat::Png).unwrap(); let timer = Instant::now(); let scaled = tiny.resize(48, 48, filter); println!("Scaled by {} in {}", name, Elapsed::from(&timer)); - let mut output = File::create(&format!("up3-{}.png", name)).unwrap(); + let mut output = File::create(&format!("up3-{name}.png")).unwrap(); scaled.write_to(&mut output, ImageFormat::Png).unwrap(); } } diff --git a/src/animation.rs b/src/animation.rs index c0c124daeb..e9b44c8b2d 100644 --- a/src/animation.rs +++ b/src/animation.rs @@ -11,6 +11,7 @@ pub struct Frames<'a> { impl<'a> Frames<'a> { /// Creates a new `Frames` from an implementation specific iterator. + #[must_use] pub fn new(iterator: Box> + 'a>) -> Self { Frames { iterator } } @@ -69,6 +70,7 @@ pub struct Delay { impl Frame { /// Constructs a new frame without any delay. + #[must_use] pub fn new(buffer: RgbaImage) -> Frame { Frame { delay: Delay::from_ratio(Ratio { numer: 0, denom: 1 }), @@ -79,6 +81,7 @@ impl Frame { } /// Constructs a new frame + #[must_use] pub fn from_parts(buffer: RgbaImage, left: u32, top: u32, delay: Delay) -> Frame { Frame { delay, @@ -89,11 +92,13 @@ impl Frame { } /// Delay of this frame + #[must_use] pub fn delay(&self) -> Delay { self.delay } /// Returns the image buffer + #[must_use] pub fn buffer(&self) -> &RgbaImage { &self.buffer } @@ -104,16 +109,19 @@ impl Frame { } /// Returns the image buffer + #[must_use] pub fn into_buffer(self) -> RgbaImage { self.buffer } /// Returns the x offset + #[must_use] pub fn left(&self) -> u32 { self.left } /// Returns the y offset + #[must_use] pub fn top(&self) -> u32 { self.top } @@ -128,6 +136,7 @@ impl Delay { /// use image::Delay; /// let delay_10ms = Delay::from_numer_denom_ms(10, 1); /// ``` + #[must_use] pub fn from_numer_denom_ms(numerator: u32, denominator: u32) -> Self { Delay { ratio: Ratio::new(numerator, denominator), @@ -148,6 +157,7 @@ impl Delay { /// let duration = Duration::from_millis(20); /// let delay = Delay::from_saturating_duration(duration); /// ``` + #[must_use] pub fn from_saturating_duration(duration: Duration) -> Self { // A few notes: The largest number we can represent as a ratio is u32::MAX but we can // sometimes represent much smaller numbers. @@ -177,6 +187,7 @@ impl Delay { /// /// This is guaranteed to be an exact conversion if the `Delay` was previously created with the /// `from_numer_denom_ms` constructor. + #[must_use] pub fn numer_denom_ms(self) -> (u32, u32) { (self.ratio.numer, self.ratio.denom) } diff --git a/src/buffer.rs b/src/buffer.rs index 404751522c..d1d779007e 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -644,7 +644,7 @@ where /// image::imageops::overlay(&mut img, &on_top, 128, 128); /// ``` /// -/// Convert an RgbaImage to a GrayImage. +/// Convert an `RgbaImage` to a `GrayImage`. /// /// ```no_run /// use image::{open, DynamicImage}; @@ -801,7 +801,7 @@ where /// the bounds will not overflow. fn check_image_fits(width: u32, height: u32, len: usize) -> bool { let checked_len = Self::image_buffer_len(width, height); - checked_len.map(|min_len| min_len <= len).unwrap_or(false) + checked_len.map_or(false, |min_len| min_len <= len) } fn image_buffer_len(width: u32, height: u32) -> Option { @@ -980,7 +980,7 @@ where #[inline] #[track_caller] pub fn put_pixel(&mut self, x: u32, y: u32, pixel: P) { - *self.get_pixel_mut(x, y) = pixel + *self.get_pixel_mut(x, y) = pixel; } } @@ -1198,7 +1198,7 @@ where } fn put_pixel(&mut self, x: u32, y: u32, pixel: P) { - *self.get_pixel_mut(x, y) = pixel + *self.get_pixel_mut(x, y) = pixel; } /// Puts a pixel at location (x, y), ignoring bounds checking. @@ -1206,14 +1206,14 @@ where unsafe fn unsafe_put_pixel(&mut self, x: u32, y: u32, pixel: P) { let indices = self.pixel_indices_unchecked(x, y); let p =

::from_slice_mut(self.data.get_unchecked_mut(indices)); - *p = pixel + *p = pixel; } /// Put a pixel at location (x, y), taking into account alpha channels /// /// DEPRECATED: This method will be removed. Blend the pixel directly instead. fn blend_pixel(&mut self, x: u32, y: u32, p: P) { - self.get_pixel_mut(x, y).blend(&p) + self.get_pixel_mut(x, y).blend(&p); } fn copy_within(&mut self, source: Rect, x: u32, y: u32) -> bool { @@ -1268,6 +1268,7 @@ impl ImageBuffer> { /// # Panics /// /// Panics when the resulting image is larger than the maximum size of a vector. + #[must_use] pub fn new(width: u32, height: u32) -> ImageBuffer> { let size = Self::image_buffer_len(width, height) .expect("Buffer length in `ImageBuffer::new` overflows usize"); @@ -1279,7 +1280,7 @@ impl ImageBuffer> { } } - /// Constructs a new ImageBuffer by copying a pixel + /// Constructs a new `ImageBuffer` by copying a pixel /// /// # Panics /// @@ -1287,12 +1288,12 @@ impl ImageBuffer> { pub fn from_pixel(width: u32, height: u32, pixel: P) -> ImageBuffer> { let mut buf = ImageBuffer::new(width, height); for p in buf.pixels_mut() { - *p = pixel + *p = pixel; } buf } - /// Constructs a new ImageBuffer by repeated application of the supplied function. + /// Constructs a new `ImageBuffer` by repeated application of the supplied function. /// /// The arguments to the function are the pixel's x and y coordinates. /// @@ -1305,13 +1306,14 @@ impl ImageBuffer> { { let mut buf = ImageBuffer::new(width, height); for (x, y, p) in buf.enumerate_pixels_mut() { - *p = f(x, y) + *p = f(x, y); } buf } /// Creates an image buffer out of an existing buffer. /// Returns None if the buffer is not big enough. + #[must_use] pub fn from_vec( width: u32, height: u32, @@ -1322,6 +1324,7 @@ impl ImageBuffer> { /// Consumes the image buffer and returns the underlying data /// as an owned buffer + #[must_use] pub fn into_vec(self) -> Vec { self.into_raw() } @@ -1341,6 +1344,7 @@ impl GrayImage { /// Expands a color palette by re-using the existing buffer. /// Assumes 8 bit per pixel. Uses an optionally transparent index to /// adjust it's alpha value accordingly. + #[must_use] pub fn expand_palette( self, palette: &[(u8, u8, u8)], @@ -1397,7 +1401,7 @@ where let mut buffer: ImageBuffer> = ImageBuffer::new(self.width, self.height); for (to, from) in buffer.pixels_mut().zip(self.pixels()) { - to.from_color(from) + to.from_color(from); } buffer } diff --git a/src/buffer_par.rs b/src/buffer_par.rs index aa90a86664..0cf1fe1b54 100644 --- a/src/buffer_par.rs +++ b/src/buffer_par.rs @@ -377,7 +377,7 @@ where P: Pixel + Send + Sync, P::Subpixel: Send + Sync, { - /// Constructs a new ImageBuffer by repeated application of the supplied function, + /// Constructs a new `ImageBuffer` by repeated application of the supplied function, /// utilizing multi-threading via `rayon`. /// /// The arguments to the function are the pixel's x and y coordinates. diff --git a/src/codecs/avif/encoder.rs b/src/codecs/avif/encoder.rs index 58cbe4c506..5ba8d9af14 100644 --- a/src/codecs/avif/encoder.rs +++ b/src/codecs/avif/encoder.rs @@ -6,6 +6,7 @@ use std::borrow::Cow; use std::cmp::min; use std::io::Write; +use std::mem::size_of; use crate::buffer::ConvertBuffer; use crate::color::{FromColor, Luma, LumaA, Rgb, Rgba}; @@ -187,12 +188,12 @@ impl AvifEncoder { Err(PodCastError::TargetAlignmentGreaterAndInputNotAligned) => { // Sad, but let's allocate. // bytemuck checks alignment _before_ slop but size mismatch before this.. - if buf.len() % std::mem::size_of::() != 0 { + if buf.len() % size_of::() != 0 { Err(ImageError::Parameter(ParameterError::from_kind( ParameterErrorKind::DimensionMismatch, ))) } else { - let len = buf.len() / std::mem::size_of::(); + let len = buf.len() / size_of::(); let mut data = vec![Channel::zero(); len]; let view = try_cast_slice_mut::<_, u8>(data.as_mut_slice()).unwrap(); view.copy_from_slice(buf); @@ -202,7 +203,7 @@ impl AvifEncoder { Err(err) => { // Are you trying to encode a ZST?? Err(ImageError::Parameter(ParameterError::from_kind( - ParameterErrorKind::Generic(format!("{:?}", err)), + ParameterErrorKind::Generic(format!("{err:?}")), ))) } } diff --git a/src/codecs/bmp/decoder.rs b/src/codecs/bmp/decoder.rs index b66d998109..88339d7eef 100644 --- a/src/codecs/bmp/decoder.rs +++ b/src/codecs/bmp/decoder.rs @@ -167,38 +167,35 @@ impl fmt::Display for DecoderError { DecoderError::BitfieldMaskNonContiguous => f.write_str("Non-contiguous bitfield mask"), DecoderError::BitfieldMaskInvalid => f.write_str("Invalid bitfield mask"), DecoderError::BitfieldMaskMissing(bb) => { - f.write_fmt(format_args!("Missing {}-bit bitfield mask", bb)) + f.write_fmt(format_args!("Missing {bb}-bit bitfield mask")) } DecoderError::BitfieldMasksMissing(bb) => { - f.write_fmt(format_args!("Missing {}-bit bitfield masks", bb)) + f.write_fmt(format_args!("Missing {bb}-bit bitfield masks")) } DecoderError::BmpSignatureInvalid => f.write_str("BMP signature not found"), DecoderError::MoreThanOnePlane => f.write_str("More than one plane"), DecoderError::InvalidChannelWidth(tp, n) => { - f.write_fmt(format_args!("Invalid channel bit count for {}: {}", tp, n)) + f.write_fmt(format_args!("Invalid channel bit count for {tp}: {n}")) } - DecoderError::NegativeWidth(w) => f.write_fmt(format_args!("Negative width ({})", w)), + DecoderError::NegativeWidth(w) => f.write_fmt(format_args!("Negative width ({w})")), DecoderError::ImageTooLarge(w, h) => f.write_fmt(format_args!( - "Image too large (one of ({}, {}) > soft limit of {})", - w, h, MAX_WIDTH_HEIGHT + "Image too large (one of ({w}, {h}) > soft limit of {MAX_WIDTH_HEIGHT})" )), DecoderError::InvalidHeight => f.write_str("Invalid height"), DecoderError::ImageTypeInvalidForTopDown(tp) => f.write_fmt(format_args!( - "Invalid image type {} for top-down image.", - tp + "Invalid image type {tp} for top-down image." )), DecoderError::ImageTypeUnknown(tp) => { - f.write_fmt(format_args!("Unknown image compression type {}", tp)) + f.write_fmt(format_args!("Unknown image compression type {tp}")) } DecoderError::HeaderTooSmall(s) => { - f.write_fmt(format_args!("Bitmap header too small ({} bytes)", s)) + f.write_fmt(format_args!("Bitmap header too small ({s} bytes)")) } DecoderError::PaletteSizeExceeded { colors_used, bit_count, } => f.write_fmt(format_args!( - "Palette size {} exceeds maximum size for BMP with bit count of {}", - colors_used, bit_count + "Palette size {colors_used} exceeds maximum size for BMP with bit count of {bit_count}" )), } } @@ -245,8 +242,7 @@ fn check_for_overflow(width: i32, length: i32, channels: usize) -> ImageResult<( ImageError::Unsupported(UnsupportedError::from_format_and_kind( ImageFormat::Bmp.into(), UnsupportedErrorKind::GenericFeature(format!( - "Image dimensions ({}x{} w/{} channels) are too large", - width, length, channels + "Image dimensions ({width}x{length} w/{channels} channels) are too large" )), )) }) @@ -534,7 +530,7 @@ impl BmpDecoder { } /// Create a new decoder that decodes from the stream ```r``` without first - /// reading a BITMAPFILEHEADER. This is useful for decoding the CF_DIB format + /// reading a BITMAPFILEHEADER. This is useful for decoding the `CF_DIB` format /// directly from the Windows clipboard. pub fn new_without_file_header(reader: R) -> ImageResult> { let mut decoder = Self::new_decoder(reader); @@ -582,7 +578,7 @@ impl BmpDecoder { Ok(()) } - /// Read BITMAPCOREHEADER https://msdn.microsoft.com/en-us/library/vs/alm/dd183372(v=vs.85).aspx + /// Read BITMAPCOREHEADER /// /// returns Err if any of the values are invalid. fn read_bitmap_core_header(&mut self) -> ImageResult<()> { @@ -614,7 +610,7 @@ impl BmpDecoder { Ok(()) } - /// Read BITMAPINFOHEADER https://msdn.microsoft.com/en-us/library/vs/alm/dd183376(v=vs.85).aspx + /// Read BITMAPINFOHEADER /// or BITMAPV{2|3|4|5}HEADER. /// /// returns Err if any of the values are invalid. @@ -803,8 +799,7 @@ impl BmpDecoder { UnsupportedError::from_format_and_kind( ImageFormat::Bmp.into(), UnsupportedErrorKind::GenericFeature(format!( - "Unknown bitmap header type (size={})", - bmp_header_size + "Unknown bitmap header type (size={bmp_header_size})" )), ), )) diff --git a/src/codecs/bmp/encoder.rs b/src/codecs/bmp/encoder.rs index 794998c3b3..48977e5690 100644 --- a/src/codecs/bmp/encoder.rs +++ b/src/codecs/bmp/encoder.rs @@ -57,8 +57,7 @@ impl<'a, W: Write + 'a> BmpEncoder<'a, W> { return Err(ImageError::IoError(io::Error::new( io::ErrorKind::InvalidInput, format!( - "Unsupported color type {:?} when using a non-empty palette. Supported types: Gray(8), GrayA(8).", - c + "Unsupported color type {c:?} when using a non-empty palette. Supported types: Gray(8), GrayA(8)." ), ))); } @@ -130,7 +129,7 @@ impl<'a, W: Write + 'a> BmpEncoder<'a, W> { self.writer.write_u32::(0xff << 8)?; // green mask self.writer.write_u32::(0xff)?; // blue mask self.writer.write_u32::(0xff << 24)?; // alpha mask - self.writer.write_u32::(0x73524742)?; // colorspace - sRGB + self.writer.write_u32::(0x7352_4742)?; // colorspace - sRGB // endpoints (3x3) and gamma (3) for _ in 0..12 { @@ -143,10 +142,10 @@ impl<'a, W: Write + 'a> BmpEncoder<'a, W> { ExtendedColorType::Rgb8 => self.encode_rgb(image, width, height, row_pad_size, 3)?, ExtendedColorType::Rgba8 => self.encode_rgba(image, width, height, row_pad_size, 4)?, ExtendedColorType::L8 => { - self.encode_gray(image, width, height, row_pad_size, 1, palette)? + self.encode_gray(image, width, height, row_pad_size, 1, palette)?; } ExtendedColorType::La8 => { - self.encode_gray(image, width, height, row_pad_size, 2, palette)? + self.encode_gray(image, width, height, row_pad_size, 2, palette)?; } _ => { return Err(ImageError::IoError(io::Error::new( @@ -287,10 +286,7 @@ impl<'a, W: Write> ImageEncoder for BmpEncoder<'a, W> { } fn get_unsupported_error_message(c: ExtendedColorType) -> String { - format!( - "Unsupported color type {:?}. Supported types: RGB(8), RGBA(8), Gray(8), GrayA(8).", - c - ) + format!("Unsupported color type {c:?}. Supported types: RGB(8), RGBA(8), Gray(8), GrayA(8).") } /// Returns a tuple representing: (dib header size, written pixel size, palette color count). diff --git a/src/codecs/dds.rs b/src/codecs/dds.rs index 2f07eee77d..e23a23beb2 100644 --- a/src/codecs/dds.rs +++ b/src/codecs/dds.rs @@ -46,25 +46,25 @@ impl fmt::Display for DecoderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { DecoderError::PixelFormatSizeInvalid(s) => { - f.write_fmt(format_args!("Invalid DDS PixelFormat size: {}", s)) + f.write_fmt(format_args!("Invalid DDS PixelFormat size: {s}")) } DecoderError::HeaderSizeInvalid(s) => { - f.write_fmt(format_args!("Invalid DDS header size: {}", s)) + f.write_fmt(format_args!("Invalid DDS header size: {s}")) } DecoderError::HeaderFlagsInvalid(fs) => { - f.write_fmt(format_args!("Invalid DDS header flags: {:#010X}", fs)) + f.write_fmt(format_args!("Invalid DDS header flags: {fs:#010X}")) } DecoderError::DxgiFormatInvalid(df) => { - f.write_fmt(format_args!("Invalid DDS DXGI format: {}", df)) + f.write_fmt(format_args!("Invalid DDS DXGI format: {df}")) } DecoderError::ResourceDimensionInvalid(d) => { - f.write_fmt(format_args!("Invalid DDS resource dimension: {}", d)) + f.write_fmt(format_args!("Invalid DDS resource dimension: {d}")) } DecoderError::Dx10FlagsInvalid(fs) => { - f.write_fmt(format_args!("Invalid DDS DX10 header flags: {:#010X}", fs)) + f.write_fmt(format_args!("Invalid DDS DX10 header flags: {fs:#010X}")) } DecoderError::Dx10ArraySizeInvalid(s) => { - f.write_fmt(format_args!("Invalid DDS DX10 array size: {}", s)) + f.write_fmt(format_args!("Invalid DDS DX10 array size: {s}")) } DecoderError::DdsSignatureInvalid => f.write_str("DDS signature not found"), } @@ -146,7 +146,7 @@ impl Header { } const REQUIRED_FLAGS: u32 = 0x1 | 0x2 | 0x4 | 0x1000; - const VALID_FLAGS: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x1000 | 0x20000 | 0x80000 | 0x800000; + const VALID_FLAGS: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x1000 | 0x20000 | 0x80000 | 0x0080_0000; let flags = r.read_u32::()?; if flags & (REQUIRED_FLAGS | !VALID_FLAGS) != REQUIRED_FLAGS { return Err(DecoderError::HeaderFlagsInvalid(flags).into()); @@ -288,10 +288,7 @@ impl DdsDecoder { return Err(ImageError::Unsupported( UnsupportedError::from_format_and_kind( ImageFormat::Dds.into(), - UnsupportedErrorKind::GenericFeature(format!( - "DDS FourCC {:?}", - fourcc - )), + UnsupportedErrorKind::GenericFeature(format!("DDS FourCC {fourcc:?}")), ), )) } diff --git a/src/codecs/dxt.rs b/src/codecs/dxt.rs index 108f6e1a64..b0d120d125 100644 --- a/src/codecs/dxt.rs +++ b/src/codecs/dxt.rs @@ -285,7 +285,7 @@ fn decode_dxt1_block(source: &[u8], dest: &mut [u8]) { } /// Decode a row of DXT1 data to four rows of RGB data. -/// source.len() should be a multiple of 8, otherwise this panics. +/// `source.len()` should be a multiple of 8, otherwise this panics. fn decode_dxt1_row(source: &[u8], dest: &mut [u8]) { assert!(source.len() % 8 == 0); let block_count = source.len() / 8; @@ -306,7 +306,7 @@ fn decode_dxt1_row(source: &[u8], dest: &mut [u8]) { } /// Decode a row of DXT3 data to four rows of RGBA data. -/// source.len() should be a multiple of 16, otherwise this panics. +/// `source.len()` should be a multiple of 16, otherwise this panics. fn decode_dxt3_row(source: &[u8], dest: &mut [u8]) { assert!(source.len() % 16 == 0); let block_count = source.len() / 16; @@ -327,7 +327,7 @@ fn decode_dxt3_row(source: &[u8], dest: &mut [u8]) { } /// Decode a row of DXT5 data to four rows of RGBA data. -/// source.len() should be a multiple of 16, otherwise this panics. +/// `source.len()` should be a multiple of 16, otherwise this panics. fn decode_dxt5_row(source: &[u8], dest: &mut [u8]) { assert!(source.len() % 16 == 0); let block_count = source.len() / 16; diff --git a/src/codecs/farbfeld.rs b/src/codecs/farbfeld.rs index 96b9ba858e..32fdbc9c1e 100644 --- a/src/codecs/farbfeld.rs +++ b/src/codecs/farbfeld.rs @@ -52,7 +52,7 @@ impl FarbfeldReader { if &magic != b"farbfeld" { return Err(ImageError::Decoding(DecodingError::new( ImageFormat::Farbfeld.into(), - format!("Invalid magic: {:02x?}", magic), + format!("Invalid magic: {magic:02x?}"), ))); } @@ -136,7 +136,7 @@ impl Seek for FarbfeldReader { } let original_offset = self.current_offset; - let end_offset = self.width as u64 * self.height as u64 * 2; + let end_offset = u64::from(self.width) * u64::from(self.height) * 2; let offset_from_current = parse_offset(original_offset, end_offset, pos).ok_or_else(|| { io::Error::new( @@ -263,7 +263,7 @@ impl FarbfeldEncoder { /// Panics if `width * height * 8 != data.len()`. #[track_caller] pub fn encode(self, data: &[u8], width: u32, height: u32) -> ImageResult<()> { - let expected_buffer_len = (width as u64 * height as u64).saturating_mul(8); + let expected_buffer_len = (u64::from(width) * u64::from(height)).saturating_mul(8); assert_eq!( expected_buffer_len, data.len() as u64, diff --git a/src/codecs/gif.rs b/src/codecs/gif.rs index 55e51ff389..ea943f501c 100644 --- a/src/codecs/gif.rs +++ b/src/codecs/gif.rs @@ -126,7 +126,7 @@ impl ImageDecoder for GifDecoder { if frame.left == 0 && frame.width == width - && (frame.top as u64 + frame.height as u64 <= height as u64) + && (u64::from(frame.top) + u64::from(frame.height) <= u64::from(height)) { // If the frame matches the logical screen, or, as a more general case, // fits into it and touches its left and right borders, then @@ -585,7 +585,7 @@ impl GifEncoder { .map_err(ImageError::from_encoding)?; } self.gif_encoder = Some(encoder); - gif_encoder = self.gif_encoder.as_mut().unwrap() + gif_encoder = self.gif_encoder.as_mut().unwrap(); } frame.dispose = DisposalMethod::Background; diff --git a/src/codecs/hdr/decoder.rs b/src/codecs/hdr/decoder.rs index c704f1ab8d..08f8483d5f 100644 --- a/src/codecs/hdr/decoder.rs +++ b/src/codecs/hdr/decoder.rs @@ -49,26 +49,23 @@ impl fmt::Display for DecoderError { DecoderError::TruncatedHeader => f.write_str("EOF in header"), DecoderError::TruncatedDimensions => f.write_str("EOF in dimensions line"), DecoderError::UnparsableF32(line, pe) => { - f.write_fmt(format_args!("Cannot parse {} value as f32: {}", line, pe)) + f.write_fmt(format_args!("Cannot parse {line} value as f32: {pe}")) } DecoderError::UnparsableU32(line, pe) => { - f.write_fmt(format_args!("Cannot parse {} value as u32: {}", line, pe)) + f.write_fmt(format_args!("Cannot parse {line} value as u32: {pe}")) } DecoderError::LineTooShort(line) => { - f.write_fmt(format_args!("Not enough numbers in {}", line)) + f.write_fmt(format_args!("Not enough numbers in {line}")) } DecoderError::ExtraneousColorcorrNumbers => f.write_str("Extra numbers in COLORCORR"), DecoderError::DimensionsLineTooShort(elements, expected) => f.write_fmt(format_args!( - "Dimensions line too short: have {} elements, expected {}", - elements, expected + "Dimensions line too short: have {elements} elements, expected {expected}" )), DecoderError::DimensionsLineTooLong(expected) => f.write_fmt(format_args!( - "Dimensions line too long, expected {} elements", - expected + "Dimensions line too long, expected {expected} elements" )), DecoderError::WrongScanlineLength(len, expected) => f.write_fmt(format_args!( - "Wrong length of decoded scanline: got {}, expected {}", - len, expected + "Wrong length of decoded scanline: got {len}, expected {expected}" )), DecoderError::FirstPixelRlMarker => { f.write_str("First pixel of a scanline shouldn't be run length marker") @@ -163,7 +160,7 @@ impl Rgbe8Pixel { impl HdrDecoder { /// Reads Radiance HDR image header from stream ```r``` - /// if the header is valid, creates HdrDecoder + /// if the header is valid, creates `HdrDecoder` /// strict mode is enabled pub fn new(reader: R) -> ImageResult { HdrDecoder::with_strictness(reader, true) @@ -241,8 +238,7 @@ impl HdrDecoder { UnsupportedError::from_format_and_kind( ImageFormat::Hdr.into(), UnsupportedErrorKind::GenericFeature(format!( - "Image dimensions ({}x{}) are too large", - width, height + "Image dimensions ({width}x{height}) are too large" )), ), )); @@ -518,7 +514,9 @@ impl HdrMetadata { Some((key, val)) => self .custom_attributes .push((key.to_owned(), val.to_owned())), - None => self.custom_attributes.push(("".into(), line.to_owned())), + None => self + .custom_attributes + .push((String::new(), line.to_owned())), } // parse known attributes match maybe_key_value { diff --git a/src/codecs/hdr/encoder.rs b/src/codecs/hdr/encoder.rs index 5686004c8f..ea50c91c81 100644 --- a/src/codecs/hdr/encoder.rs +++ b/src/codecs/hdr/encoder.rs @@ -68,7 +68,7 @@ impl HdrEncoder { w.write_all(b"\n")?; w.write_all(b"# Rust HDR encoder\n")?; w.write_all(b"FORMAT=32-bit_rle_rgbe\n\n")?; - w.write_all(format!("-Y {} +X {}\n", height, width).as_bytes())?; + w.write_all(format!("-Y {height} +X {width}\n").as_bytes())?; if !(8..=32_768).contains(&width) { for pixel in flattened_rgbe_pixels { diff --git a/src/codecs/ico/decoder.rs b/src/codecs/ico/decoder.rs index fb1f9a323e..e1c2c57e5d 100644 --- a/src/codecs/ico/decoder.rs +++ b/src/codecs/ico/decoder.rs @@ -24,7 +24,7 @@ enum DecoderError { /// The entry is in PNG format and specified a length that is shorter than PNG header. PngShorterThanHeader, - /// The enclosed PNG is not in RGBA, which is invalid: https://blogs.msdn.microsoft.com/oldnewthing/20101022-00/?p=12473/. + /// The enclosed PNG is not in RGBA, which is invalid: /. PngNotRgba, /// The entry is in BMP format and specified a data size that is not correct for the image and optional mask data. @@ -63,8 +63,7 @@ impl fmt::Display for DecoderError { entry, image, } => f.write_fmt(format_args!( - "Entry{:?} and {}{:?} dimensions do not match!", - entry, format, image + "Entry{entry:?} and {format}{image:?} dimensions do not match!" )), } } diff --git a/src/codecs/ico/encoder.rs b/src/codecs/ico/encoder.rs index 23892f0469..7c51996d94 100644 --- a/src/codecs/ico/encoder.rs +++ b/src/codecs/ico/encoder.rs @@ -46,8 +46,7 @@ impl<'a> IcoFrame<'a> { if !(1..=256).contains(&width) { return Err(ImageError::Parameter(ParameterError::from_kind( ParameterErrorKind::Generic(format!( - "the image width must be `1..=256`, instead width {} was provided", - width, + "the image width must be `1..=256`, instead width {width} was provided", )), ))); } @@ -55,8 +54,7 @@ impl<'a> IcoFrame<'a> { if !(1..=256).contains(&height) { return Err(ImageError::Parameter(ParameterError::from_kind( ParameterErrorKind::Generic(format!( - "the image height must be `1..=256`, instead height {} was provided", - height, + "the image height must be `1..=256`, instead height {height} was provided", )), ))); } diff --git a/src/codecs/jpeg/decoder.rs b/src/codecs/jpeg/decoder.rs index 3584a6768f..9e985a8097 100644 --- a/src/codecs/jpeg/decoder.rs +++ b/src/codecs/jpeg/decoder.rs @@ -154,7 +154,7 @@ impl ImageError { match err { Unsupported(desc) => ImageError::Unsupported(UnsupportedError::from_format_and_kind( ImageFormat::Jpeg.into(), - UnsupportedErrorKind::GenericFeature(format!("{:?}", desc)), + UnsupportedErrorKind::GenericFeature(format!("{desc:?}")), )), LargeDimensions(_) => ImageError::Limits(LimitError::from_kind( crate::error::LimitErrorKind::DimensionError, diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index 27958c7dee..357fee4a1d 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -219,9 +219,7 @@ impl BitWriter { fn huffman_encode(&mut self, val: u8, table: &[(u8, u16); 256]) -> io::Result<()> { let (size, code) = table[val as usize]; - if size > 16 { - panic!("bad huffman value"); - } + assert!(size <= 16, "bad huffman value"); self.write_bits(code, size) } @@ -316,6 +314,7 @@ impl PixelDensity { /// Creates the most common pixel density type: /// the horizontal and the vertical density are equal, /// and measured in pixels per inch. + #[must_use] pub fn dpi(density: u16) -> Self { PixelDensity { density: (density, density), @@ -401,7 +400,7 @@ impl JpegEncoder { tables.iter_mut().for_each(|t| { t.iter_mut().for_each(|v| { *v = clamp((u32::from(*v) * scale + 50) / 100, 1, u32::from(u8::MAX)) as u8; - }) + }); }); JpegEncoder { @@ -696,7 +695,7 @@ fn build_frame_header( m.extend_from_slice(&width.to_be_bytes()); m.push(components.len() as u8); - for &comp in components.iter() { + for &comp in components { let hv = (comp.h << 4) | comp.v; m.extend_from_slice(&[comp.id, hv, comp.tq]); } @@ -707,7 +706,7 @@ fn build_scan_header(m: &mut Vec, components: &[Component]) { m.push(components.len() as u8); - for &comp in components.iter() { + for &comp in components { let tables = (comp.dc_table << 4) | comp.ac_table; m.extend_from_slice(&[comp.id, tables]); } diff --git a/src/codecs/openexr.rs b/src/codecs/openexr.rs index 4ddffe3a41..3fee1e7f9a 100644 --- a/src/codecs/openexr.rs +++ b/src/codecs/openexr.rs @@ -155,9 +155,10 @@ impl ImageDecoder for OpenExrDecoder { // therefore data is too small, so it is invalid. .unwrap_or(true); - if has_invalid_size_or_overflowed { - panic!("byte buffer not large enough for the specified dimensions and f32 pixels"); - } + assert!( + !has_invalid_size_or_overflowed, + "byte buffer not large enough for the specified dimensions and f32 pixels" + ) } let result = read() @@ -273,10 +274,7 @@ fn write_buffer( unsupported_color_type => { return Err(ImageError::Encoding(EncodingError::new( ImageFormatHint::Exact(ImageFormat::OpenExr), - format!( - "writing color type {:?} not yet supported", - unsupported_color_type - ), + format!("writing color type {unsupported_color_type:?} not yet supported"), ))) } } diff --git a/src/codecs/png.rs b/src/codecs/png.rs index 7ecfc96b56..9258ab72da 100644 --- a/src/codecs/png.rs +++ b/src/codecs/png.rs @@ -129,7 +129,7 @@ impl PngDecoder { .reader .info() .source_gamma - .map(|x| x.into_scaled() as f64 / 100000.0)) + .map(|x| f64::from(x.into_scaled()) / 100_000.0)) } /// Turn this into an iterator over the animation frames. @@ -192,7 +192,7 @@ impl ImageDecoder for PngDecoder { 1 => (), // No reodering necessary for u8 2 => buf.chunks_exact_mut(2).for_each(|c| { let v = BigEndian::read_u16(c); - NativeEndian::write_u16(c, v) + NativeEndian::write_u16(c, v); }), _ => unreachable!(), } @@ -597,7 +597,7 @@ impl ImageEncoder for PngEncoder { /// Write a PNG image with the specified width, height, and color type. /// /// For color types with 16-bit per channel or larger, the contents of `buf` should be in - /// native endian. PngEncoder will automatically convert to big endian as required by the + /// native endian. `PngEncoder` will automatically convert to big endian as required by the /// underlying PNG format. #[track_caller] fn write_image( @@ -671,11 +671,9 @@ impl ImageError { impl fmt::Display for BadPngRepresentation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - Self::ColorType(color_type) => write!( - f, - "The color {:?} can not be represented in PNG.", - color_type - ), + Self::ColorType(color_type) => { + write!(f, "The color {color_type:?} can not be represented in PNG.") + } } } } diff --git a/src/codecs/pnm/decoder.rs b/src/codecs/pnm/decoder.rs index 05bd7cda35..c3a76bc9f7 100644 --- a/src/codecs/pnm/decoder.rs +++ b/src/codecs/pnm/decoder.rs @@ -87,11 +87,11 @@ impl Display for DecoderError { magic[0], magic[1] )), DecoderError::UnparsableValue(src, data, err) => { - f.write_fmt(format_args!("Error parsing {:?} as {}: {}", data, src, err)) + f.write_fmt(format_args!("Error parsing {data:?} as {src}: {err}")) } DecoderError::NonAsciiByteInHeader(c) => { - f.write_fmt(format_args!("Non-ASCII character {:#04X?} in header", c)) + f.write_fmt(format_args!("Non-ASCII character {c:#04X?} in header")) } DecoderError::NonAsciiLineInPamHeader => f.write_str("Non-ASCII line in PAM header"), DecoderError::NonAsciiSample => { @@ -99,17 +99,15 @@ impl Display for DecoderError { } DecoderError::NotNewlineAfterP7Magic(c) => f.write_fmt(format_args!( - "Expected newline after P7 magic, got {:#04X?}", - c + "Expected newline after P7 magic, got {c:#04X?}" )), DecoderError::UnexpectedPnmHeaderEnd => f.write_str("Unexpected end of PNM header"), DecoderError::HeaderLineDuplicated(line) => { - f.write_fmt(format_args!("Duplicate {} line", line)) + f.write_fmt(format_args!("Duplicate {line} line")) } DecoderError::HeaderLineUnknown(identifier) => f.write_fmt(format_args!( - "Unknown header line with identifier {:?}", - identifier + "Unknown header line with identifier {identifier:?}" )), DecoderError::HeaderLineMissing { height, @@ -117,19 +115,17 @@ impl Display for DecoderError { depth, maxval, } => f.write_fmt(format_args!( - "Missing header line: have height={:?}, width={:?}, depth={:?}, maxval={:?}", - height, width, depth, maxval + "Missing header line: have height={height:?}, width={width:?}, depth={depth:?}, maxval={maxval:?}" )), DecoderError::InputTooShort => { f.write_str("Not enough data was provided to the Decoder to decode the image") } DecoderError::UnexpectedByteInRaster(c) => f.write_fmt(format_args!( - "Unexpected character {:#04X?} within sample raster", - c + "Unexpected character {c:#04X?} within sample raster" )), DecoderError::SampleOutOfBounds(val) => { - f.write_fmt(format_args!("Sample value {} outside of bounds", val)) + f.write_fmt(format_args!("Sample value {val} outside of bounds")) } DecoderError::MaxvalZero => f.write_str("Image MAXVAL is zero"), DecoderError::MaxvalTooBig(maxval) => { @@ -235,7 +231,7 @@ trait Sample { /// Representation size in bytes fn sample_size() -> u32 { - std::mem::size_of::() as u32 + size_of::() as u32 } fn bytelen(width: u32, height: u32, samples: u32) -> ImageResult { Ok((width * height * samples * Self::sample_size()) as usize) @@ -386,7 +382,7 @@ trait HeaderReader: Read { for (_, byte) in mark_comments.filter(|e| e.0) { match byte { - Ok(b'\t') | Ok(b'\n') | Ok(b'\x0b') | Ok(b'\x0c') | Ok(b'\r') | Ok(b' ') => { + Ok(b'\t' | b'\n' | b'\x0b' | b'\x0c' | b'\r' | b' ') => { if !bytes.is_empty() { break; // We're done as we already have some content } @@ -442,8 +438,8 @@ trait HeaderReader: Read { let height = self.read_next_u32()?; Ok(BitmapHeader { encoding, - width, height, + width, }) } @@ -469,8 +465,8 @@ trait HeaderReader: Read { let maxval = self.read_next_u32()?; Ok(PixmapHeader { encoding, - width, height, + width, maxval, }) } @@ -667,12 +663,12 @@ impl PnmDecoder { if S::sample_size() == 1 { buf.iter_mut().for_each(|v| { - *v = (*v as f32 * factor).round() as u8; - }) + *v = (f32::from(*v) * factor).round() as u8; + }); } else if S::sample_size() == 2 { for chunk in buf.chunks_exact_mut(2) { let v = NativeEndian::read_u16(chunk); - NativeEndian::write_u16(chunk, (v as f32 * factor).round() as u16); + NativeEndian::write_u16(chunk, (f32::from(v) * factor).round() as u16); } } } @@ -698,8 +694,8 @@ where let token = reader .bytes() - .skip_while(|v| v.as_ref().ok().map(is_separator).unwrap_or(false)) - .take_while(|v| v.as_ref().ok().map(|c| !is_separator(c)).unwrap_or(false)) + .skip_while(|v| v.as_ref().ok().map_or(false, is_separator)) + .take_while(|v| v.as_ref().ok().map_or(false, |c| !is_separator(c))) .collect::, _>>()?; if !token.is_ascii() { @@ -760,13 +756,13 @@ impl Sample for PbmBit { fn bytelen(width: u32, height: u32, samples: u32) -> ImageResult { let count = width * samples; - let linelen = (count / 8) + ((count % 8) != 0) as u32; + let linelen = (count / 8) + u32::from((count % 8) != 0); Ok((linelen * height) as usize) } fn from_bytes(bytes: &[u8], row_size: usize, output_buf: &mut [u8]) -> ImageResult<()> { let mut expanded = utils::expand_bits(1, row_size.try_into().unwrap(), bytes); - for b in expanded.iter_mut() { + for b in &mut expanded { *b = !*b; } output_buf.copy_from_slice(&expanded); @@ -917,7 +913,7 @@ impl DecodableImageHeader for ArbitraryHeader { Some(ArbitraryTuplType::Custom(ref custom)) => Err(ImageError::Unsupported( UnsupportedError::from_format_and_kind( ImageFormat::Pnm.into(), - UnsupportedErrorKind::GenericFeature(format!("Tuple type {:?}", custom)), + UnsupportedErrorKind::GenericFeature(format!("Tuple type {custom:?}")), ), )), None => Err(DecoderError::TupleTypeUnrecognised.into()), @@ -1065,7 +1061,7 @@ ENDHDR fn pbm_binary() { // The data contains two rows of the image (each line is padded to the full byte). For // comments on its format, see documentation of `impl SampleType for PbmBit`. - let pbmbinary = [&b"P4 6 2\n"[..], &[0b01101100_u8, 0b10110111]].concat(); + let pbmbinary = [&b"P4 6 2\n"[..], &[0b0110_1100_u8, 0b1011_0111]].concat(); let decoder = PnmDecoder::new(&pbmbinary[..]).unwrap(); assert_eq!(decoder.color_type(), ColorType::L8); assert_eq!(decoder.original_color_type(), ExtendedColorType::L1); diff --git a/src/codecs/pnm/encoder.rs b/src/codecs/pnm/encoder.rs index b1ca5d93f4..bb80ad2027 100644 --- a/src/codecs/pnm/encoder.rs +++ b/src/codecs/pnm/encoder.rs @@ -79,7 +79,7 @@ enum TupleEncoding<'a> { } impl PnmEncoder { - /// Create new PnmEncoder from the `writer`. + /// Create new `PnmEncoder` from the `writer`. /// /// The encoded images will have some `pnm` format. If more control over the image type is /// required, use either one of `with_subtype` or `with_header`. For more information on the @@ -238,15 +238,16 @@ impl PnmEncoder { }), encoded: None, }, - (PnmSubtype::Bitmap(encoding), ExtendedColorType::L8) - | (PnmSubtype::Bitmap(encoding), ExtendedColorType::L1) => PnmHeader { - decoded: HeaderRecord::Bitmap(BitmapHeader { - encoding, - width, - height, - }), - encoded: None, - }, + (PnmSubtype::Bitmap(encoding), ExtendedColorType::L8 | ExtendedColorType::L1) => { + PnmHeader { + decoded: HeaderRecord::Bitmap(BitmapHeader { + encoding, + height, + width, + }), + encoded: None, + } + } (_, _) => { return Err(ImageError::Parameter(ParameterError::from_kind( ParameterErrorKind::Generic( @@ -423,8 +424,7 @@ impl<'a> CheckedDimensions<'a> { _ if depth != components => { return Err(ImageError::Parameter(ParameterError::from_kind( ParameterErrorKind::Generic(format!( - "Depth mismatch: header {} vs. color {}", - depth, components + "Depth mismatch: header {depth} vs. color {components}" )), ))) } @@ -530,7 +530,7 @@ impl<'a> SampleWriter<'a> { { let mut auto_break_writer = AutoBreak::new(self.0, 70); for value in samples { - write!(auto_break_writer, "{} ", value)?; + write!(auto_break_writer, "{value} ")?; } auto_break_writer.flush() } @@ -553,11 +553,11 @@ impl<'a> SampleWriter<'a> { // Black pixels are encoded as 1s if let Some(&v) = byte_bits.get(i) { if v == V::default() { - byte |= 1u8 << (7 - i) + byte |= 1u8 << (7 - i); } } } - line_buffer.push(byte) + line_buffer.push(byte); } self.0.write_all(line_buffer.as_slice())?; line_buffer.clear(); diff --git a/src/codecs/pnm/header.rs b/src/codecs/pnm/header.rs index 443a701905..fa981f351e 100644 --- a/src/codecs/pnm/header.rs +++ b/src/codecs/pnm/header.rs @@ -149,6 +149,7 @@ impl ArbitraryTuplType { impl PnmSubtype { /// Get the two magic constant bytes corresponding to this format subtype. + #[must_use] pub fn magic_constant(self) -> &'static [u8; 2] { match self { PnmSubtype::Bitmap(SampleEncoding::Ascii) => b"P1", @@ -162,6 +163,7 @@ impl PnmSubtype { } /// Whether samples are stored as binary or as decimal ascii + #[must_use] pub fn sample_encoding(self) -> SampleEncoding { match self { PnmSubtype::ArbitraryMap => SampleEncoding::Binary, @@ -174,6 +176,7 @@ impl PnmSubtype { impl PnmHeader { /// Retrieve the format subtype from which the header was created. + #[must_use] pub fn subtype(&self) -> PnmSubtype { match self.decoded { HeaderRecord::Bitmap(BitmapHeader { encoding, .. }) => PnmSubtype::Bitmap(encoding), @@ -184,6 +187,7 @@ impl PnmHeader { } /// The width of the image this header is for. + #[must_use] pub fn width(&self) -> u32 { match self.decoded { HeaderRecord::Bitmap(BitmapHeader { width, .. }) => width, @@ -194,6 +198,7 @@ impl PnmHeader { } /// The height of the image this header is for. + #[must_use] pub fn height(&self) -> u32 { match self.decoded { HeaderRecord::Bitmap(BitmapHeader { height, .. }) => height, @@ -204,6 +209,7 @@ impl PnmHeader { } /// The biggest value a sample can have. In other words, the colour resolution. + #[must_use] pub fn maximal_sample(&self) -> u32 { match self.decoded { HeaderRecord::Bitmap(BitmapHeader { .. }) => 1, @@ -214,6 +220,7 @@ impl PnmHeader { } /// Retrieve the underlying bitmap header if any + #[must_use] pub fn as_bitmap(&self) -> Option<&BitmapHeader> { match self.decoded { HeaderRecord::Bitmap(ref bitmap) => Some(bitmap), @@ -222,6 +229,7 @@ impl PnmHeader { } /// Retrieve the underlying graymap header if any + #[must_use] pub fn as_graymap(&self) -> Option<&GraymapHeader> { match self.decoded { HeaderRecord::Graymap(ref graymap) => Some(graymap), @@ -230,6 +238,7 @@ impl PnmHeader { } /// Retrieve the underlying pixmap header if any + #[must_use] pub fn as_pixmap(&self) -> Option<&PixmapHeader> { match self.decoded { HeaderRecord::Pixmap(ref pixmap) => Some(pixmap), @@ -238,6 +247,7 @@ impl PnmHeader { } /// Retrieve the underlying arbitrary header if any + #[must_use] pub fn as_arbitrary(&self) -> Option<&ArbitraryHeader> { match self.decoded { HeaderRecord::Arbitrary(ref arbitrary) => Some(arbitrary), @@ -261,7 +271,7 @@ impl PnmHeader { height, }), .. - } => writeln!(writer, "\n{} {}", width, height), + } => writeln!(writer, "\n{width} {height}"), PnmHeader { decoded: HeaderRecord::Graymap(GraymapHeader { @@ -271,7 +281,7 @@ impl PnmHeader { maxwhite, }), .. - } => writeln!(writer, "\n{} {} {}", width, height, maxwhite), + } => writeln!(writer, "\n{width} {height} {maxwhite}"), PnmHeader { decoded: HeaderRecord::Pixmap(PixmapHeader { @@ -281,7 +291,7 @@ impl PnmHeader { maxval, }), .. - } => writeln!(writer, "\n{} {} {}", width, height, maxval), + } => writeln!(writer, "\n{width} {height} {maxval}"), PnmHeader { decoded: HeaderRecord::Arbitrary(ArbitraryHeader { diff --git a/src/codecs/qoi.rs b/src/codecs/qoi.rs index 809b9f9131..f42d21a470 100644 --- a/src/codecs/qoi.rs +++ b/src/codecs/qoi.rs @@ -1,7 +1,7 @@ //! Decoding and encoding of QOI images +use crate::error::{DecodingError, EncodingError}; use crate::{ - error::{DecodingError, EncodingError}, ColorType, ExtendedColorType, ImageDecoder, ImageEncoder, ImageError, ImageFormat, ImageResult, }; use std::io::{Read, Write}; diff --git a/src/codecs/tga/decoder.rs b/src/codecs/tga/decoder.rs index a0fcb534c9..33045934ff 100644 --- a/src/codecs/tga/decoder.rs +++ b/src/codecs/tga/decoder.rs @@ -195,7 +195,7 @@ impl TgaDecoder { #[inline] fn bytes_to_index(bytes: &[u8]) -> usize { let mut result = 0usize; - for byte in bytes.iter() { + for byte in bytes { result = result << 8 | *byte as usize; } result diff --git a/src/codecs/tga/encoder.rs b/src/codecs/tga/encoder.rs index ec74c905f8..0e83924075 100644 --- a/src/codecs/tga/encoder.rs +++ b/src/codecs/tga/encoder.rs @@ -18,10 +18,8 @@ enum EncoderError { impl fmt::Display for EncoderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - EncoderError::WidthInvalid(s) => f.write_fmt(format_args!("Invalid TGA width: {}", s)), - EncoderError::HeightInvalid(s) => { - f.write_fmt(format_args!("Invalid TGA height: {}", s)) - } + EncoderError::WidthInvalid(s) => f.write_fmt(format_args!("Invalid TGA width: {s}")), + EncoderError::HeightInvalid(s) => f.write_fmt(format_args!("Invalid TGA height: {s}")), } } } diff --git a/src/codecs/tga/header.rs b/src/codecs/tga/header.rs index 26588b6246..4dff32e777 100644 --- a/src/codecs/tga/header.rs +++ b/src/codecs/tga/header.rs @@ -1,7 +1,5 @@ -use crate::{ - error::{UnsupportedError, UnsupportedErrorKind}, - ExtendedColorType, ImageError, ImageFormat, ImageResult, -}; +use crate::error::{UnsupportedError, UnsupportedErrorKind}; +use crate::{ExtendedColorType, ImageError, ImageFormat, ImageResult}; use byteorder_lite::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::io::{Read, Write}; diff --git a/src/codecs/tiff.rs b/src/codecs/tiff.rs index a04fe52e0e..fb3d7b6a2e 100644 --- a/src/codecs/tiff.rs +++ b/src/codecs/tiff.rs @@ -36,7 +36,7 @@ impl TiffDecoder where R: BufRead + Seek, { - /// Create a new TiffDecoder. + /// Create a new `TiffDecoder`. pub fn new(r: R) -> Result, ImageError> { let mut inner = tiff::decoder::Decoder::new(r).map_err(ImageError::from_tiff_decode)?; @@ -107,8 +107,7 @@ fn check_sample_format(sample_format: u16) -> Result<(), ImageError> { UnsupportedError::from_format_and_kind( ImageFormat::Tiff.into(), UnsupportedErrorKind::GenericFeature(format!( - "Unhandled TIFF sample format {:?}", - other + "Unhandled TIFF sample format {other:?}" )), ), )), @@ -129,9 +128,9 @@ impl ImageError { fn from_tiff_decode(err: tiff::TiffError) -> ImageError { match err { tiff::TiffError::IoError(err) => ImageError::IoError(err), - err @ tiff::TiffError::FormatError(_) - | err @ tiff::TiffError::IntSizeError - | err @ tiff::TiffError::UsageError(_) => { + err @ (tiff::TiffError::FormatError(_) + | tiff::TiffError::IntSizeError + | tiff::TiffError::UsageError(_)) => { ImageError::Decoding(DecodingError::new(ImageFormat::Tiff.into(), err)) } tiff::TiffError::UnsupportedError(desc) => { @@ -149,9 +148,9 @@ impl ImageError { fn from_tiff_encode(err: tiff::TiffError) -> ImageError { match err { tiff::TiffError::IoError(err) => ImageError::IoError(err), - err @ tiff::TiffError::FormatError(_) - | err @ tiff::TiffError::IntSizeError - | err @ tiff::TiffError::UsageError(_) => { + err @ (tiff::TiffError::FormatError(_) + | tiff::TiffError::IntSizeError + | tiff::TiffError::UsageError(_)) => { ImageError::Encoding(EncodingError::new(ImageFormat::Tiff.into(), err)) } tiff::TiffError::UnsupportedError(desc) => { @@ -173,6 +172,7 @@ impl Read for TiffReader { fn read(&mut self, buf: &mut [u8]) -> io::Result { self.0.read(buf) } + fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { if self.0.position() == 0 && buf.is_empty() { mem::swap(buf, self.0.get_mut()); @@ -285,10 +285,10 @@ pub struct TiffEncoder { } fn cmyk_to_rgb(cmyk: &[u8]) -> [u8; 3] { - let c = cmyk[0] as f32; - let m = cmyk[1] as f32; - let y = cmyk[2] as f32; - let kf = 1. - cmyk[3] as f32 / 255.; + let c = f32::from(cmyk[0]); + let m = f32::from(cmyk[1]); + let y = f32::from(cmyk[2]); + let kf = 1. - f32::from(cmyk[3]) / 255.; [ ((255. - c) * kf) as u8, ((255. - m) * kf) as u8, @@ -305,7 +305,7 @@ fn u8_slice_as_u16(buf: &[u8]) -> ImageResult<&[u16]> { // `Error` and `Display` trait. // See . ImageError::Parameter(ParameterError::from_kind(ParameterErrorKind::Generic( - format!("{:?}", err), + format!("{err:?}"), ))) }) } diff --git a/src/codecs/webp/decoder.rs b/src/codecs/webp/decoder.rs index dd148a820b..584f20ac2f 100644 --- a/src/codecs/webp/decoder.rs +++ b/src/codecs/webp/decoder.rs @@ -11,7 +11,7 @@ pub struct WebPDecoder { } impl WebPDecoder { - /// Create a new WebPDecoder from the Reader ```r```. + /// Create a new `WebPDecoder` from the Reader ```r```. /// This function takes ownership of the Reader. pub fn new(r: R) -> ImageResult { Ok(Self { diff --git a/src/codecs/webp/encoder.rs b/src/codecs/webp/encoder.rs index fbc87fddb5..10f5803305 100644 --- a/src/codecs/webp/encoder.rs +++ b/src/codecs/webp/encoder.rs @@ -2,10 +2,8 @@ use std::io::Write; -use crate::{ - error::{EncodingError, UnsupportedError, UnsupportedErrorKind}, - ExtendedColorType, ImageEncoder, ImageError, ImageFormat, ImageResult, -}; +use crate::error::{EncodingError, UnsupportedError, UnsupportedErrorKind}; +use crate::{ExtendedColorType, ImageEncoder, ImageError, ImageFormat, ImageResult}; /// WebP Encoder. pub struct WebPEncoder { diff --git a/src/color.rs b/src/color.rs index 2002a27f14..1027611858 100644 --- a/src/color.rs +++ b/src/color.rs @@ -34,6 +34,7 @@ pub enum ColorType { impl ColorType { /// Returns the number of bytes contained in a pixel of `ColorType` ```c``` + #[must_use] pub fn bytes_per_pixel(self) -> u8 { match self { ColorType::L8 => 1, @@ -48,6 +49,7 @@ impl ColorType { } /// Returns if there is an alpha channel. + #[must_use] pub fn has_alpha(self) -> bool { use ColorType::*; match self { @@ -57,6 +59,7 @@ impl ColorType { } /// Returns false if the color scheme is grayscale, true otherwise. + #[must_use] pub fn has_color(self) -> bool { use ColorType::*; match self { @@ -67,11 +70,13 @@ impl ColorType { /// Returns the number of bits contained in a pixel of `ColorType` ```c``` (which will always be /// a multiple of 8). + #[must_use] pub fn bits_per_pixel(self) -> u16 { >::from(self.bytes_per_pixel()) * 8 } /// Returns the number of color channels that make up this pixel + #[must_use] pub fn channel_count(self) -> u8 { let e: ExtendedColorType = self.into(); e.channel_count() @@ -156,6 +161,7 @@ impl ExtendedColorType { /// /// Note that the `Unknown` variant returns a value of `1` since pixels can only be treated as /// an opaque datum by the library. + #[must_use] pub fn channel_count(self) -> u8 { match self { ExtendedColorType::A8 @@ -189,6 +195,7 @@ impl ExtendedColorType { } /// Returns the number of bits per pixel for this color type. + #[must_use] pub fn bits_per_pixel(&self) -> u16 { match *self { ExtendedColorType::A8 => 8, @@ -541,7 +548,7 @@ where T: FromPrimitive, { fn from_color(&mut self, other: &LumaA) { - self.channels_mut()[0] = T::from_primitive(other.channels()[0]) + self.channels_mut()[0] = T::from_primitive(other.channels()[0]); } } @@ -764,13 +771,13 @@ impl Blend for LumaA { *self = LumaA([ NumCast::from(max_t * out_luma).unwrap(), NumCast::from(max_t * alpha_final).unwrap(), - ]) + ]); } } impl Blend for Luma { fn blend(&mut self, other: &Luma) { - *self = *other + *self = *other; } } @@ -834,13 +841,13 @@ impl Blend for Rgba { NumCast::from(max_t * out_g).unwrap(), NumCast::from(max_t * out_b).unwrap(), NumCast::from(max_t * alpha_final).unwrap(), - ]) + ]); } } impl Blend for Rgb { fn blend(&mut self, other: &Rgb) { - *self = *other + *self = *other; } } @@ -855,7 +862,7 @@ impl Invert for LumaA { let l = self.0; let max = T::DEFAULT_MAX_VALUE; - *self = LumaA([max - l[0], l[1]]) + *self = LumaA([max - l[0], l[1]]); } } @@ -866,7 +873,7 @@ impl Invert for Luma { let max = T::DEFAULT_MAX_VALUE; let l1 = max - l[0]; - *self = Luma([l1]) + *self = Luma([l1]); } } @@ -876,7 +883,7 @@ impl Invert for Rgba { let max = T::DEFAULT_MAX_VALUE; - *self = Rgba([max - rgba[0], max - rgba[1], max - rgba[2], rgba[3]]) + *self = Rgba([max - rgba[0], max - rgba[1], max - rgba[2], rgba[3]]); } } @@ -890,7 +897,7 @@ impl Invert for Rgb { let g1 = max - rgb[1]; let b1 = max - rgb[2]; - *self = Rgb([r1, g1, b1]) + *self = Rgb([r1, g1, b1]); } } diff --git a/src/dynimage.rs b/src/dynimage.rs index c7d9df12b3..93e3d03689 100644 --- a/src/dynimage.rs +++ b/src/dynimage.rs @@ -137,6 +137,7 @@ impl Clone for DynamicImage { impl DynamicImage { /// Creates a dynamic image backed by a buffer depending on /// the color type given. + #[must_use] pub fn new(w: u32, h: u32, color: color::ColorType) -> DynamicImage { use color::ColorType::*; match color { @@ -154,53 +155,63 @@ impl DynamicImage { } /// Creates a dynamic image backed by a buffer of gray pixels. + #[must_use] pub fn new_luma8(w: u32, h: u32) -> DynamicImage { DynamicImage::ImageLuma8(ImageBuffer::new(w, h)) } /// Creates a dynamic image backed by a buffer of gray /// pixels with transparency. + #[must_use] pub fn new_luma_a8(w: u32, h: u32) -> DynamicImage { DynamicImage::ImageLumaA8(ImageBuffer::new(w, h)) } /// Creates a dynamic image backed by a buffer of RGB pixels. + #[must_use] pub fn new_rgb8(w: u32, h: u32) -> DynamicImage { DynamicImage::ImageRgb8(ImageBuffer::new(w, h)) } /// Creates a dynamic image backed by a buffer of RGBA pixels. + #[must_use] pub fn new_rgba8(w: u32, h: u32) -> DynamicImage { DynamicImage::ImageRgba8(ImageBuffer::new(w, h)) } /// Creates a dynamic image backed by a buffer of gray pixels. + #[must_use] pub fn new_luma16(w: u32, h: u32) -> DynamicImage { DynamicImage::ImageLuma16(ImageBuffer::new(w, h)) } /// Creates a dynamic image backed by a buffer of gray /// pixels with transparency. + #[must_use] pub fn new_luma_a16(w: u32, h: u32) -> DynamicImage { DynamicImage::ImageLumaA16(ImageBuffer::new(w, h)) } /// Creates a dynamic image backed by a buffer of RGB pixels. + #[must_use] pub fn new_rgb16(w: u32, h: u32) -> DynamicImage { DynamicImage::ImageRgb16(ImageBuffer::new(w, h)) } /// Creates a dynamic image backed by a buffer of RGBA pixels. + #[must_use] pub fn new_rgba16(w: u32, h: u32) -> DynamicImage { DynamicImage::ImageRgba16(ImageBuffer::new(w, h)) } /// Creates a dynamic image backed by a buffer of RGB pixels. + #[must_use] pub fn new_rgb32f(w: u32, h: u32) -> DynamicImage { DynamicImage::ImageRgb32F(ImageBuffer::new(w, h)) } /// Creates a dynamic image backed by a buffer of RGBA pixels. + #[must_use] pub fn new_rgba32f(w: u32, h: u32) -> DynamicImage { DynamicImage::ImageRgba32F(ImageBuffer::new(w, h)) } @@ -211,61 +222,73 @@ impl DynamicImage { } /// Returns a copy of this image as an RGB image. + #[must_use] pub fn to_rgb8(&self) -> RgbImage { dynamic_map!(*self, ref p, p.convert()) } /// Returns a copy of this image as an RGB image. + #[must_use] pub fn to_rgb16(&self) -> Rgb16Image { dynamic_map!(*self, ref p, p.convert()) } /// Returns a copy of this image as an RGB image. + #[must_use] pub fn to_rgb32f(&self) -> Rgb32FImage { dynamic_map!(*self, ref p, p.convert()) } /// Returns a copy of this image as an RGBA image. + #[must_use] pub fn to_rgba8(&self) -> RgbaImage { dynamic_map!(*self, ref p, p.convert()) } /// Returns a copy of this image as an RGBA image. + #[must_use] pub fn to_rgba16(&self) -> Rgba16Image { dynamic_map!(*self, ref p, p.convert()) } /// Returns a copy of this image as an RGBA image. + #[must_use] pub fn to_rgba32f(&self) -> Rgba32FImage { dynamic_map!(*self, ref p, p.convert()) } /// Returns a copy of this image as a Luma image. + #[must_use] pub fn to_luma8(&self) -> GrayImage { dynamic_map!(*self, ref p, p.convert()) } /// Returns a copy of this image as a Luma image. + #[must_use] pub fn to_luma16(&self) -> Gray16Image { dynamic_map!(*self, ref p, p.convert()) } /// Returns a copy of this image as a Luma image. + #[must_use] pub fn to_luma32f(&self) -> ImageBuffer, Vec> { dynamic_map!(*self, ref p, p.convert()) } - /// Returns a copy of this image as a LumaA image. + /// Returns a copy of this image as a `LumaA` image. + #[must_use] pub fn to_luma_alpha8(&self) -> GrayAlphaImage { dynamic_map!(*self, ref p, p.convert()) } - /// Returns a copy of this image as a LumaA image. + /// Returns a copy of this image as a `LumaA` image. + #[must_use] pub fn to_luma_alpha16(&self) -> GrayAlpha16Image { dynamic_map!(*self, ref p, p.convert()) } - /// Returns a copy of this image as a LumaA image. + /// Returns a copy of this image as a `LumaA` image. + #[must_use] pub fn to_luma_alpha32f(&self) -> ImageBuffer, Vec> { dynamic_map!(*self, ref p, p.convert()) } @@ -274,6 +297,7 @@ impl DynamicImage { /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. + #[must_use] pub fn into_rgb8(self) -> RgbImage { match self { DynamicImage::ImageRgb8(x) => x, @@ -285,6 +309,7 @@ impl DynamicImage { /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. + #[must_use] pub fn into_rgb16(self) -> Rgb16Image { match self { DynamicImage::ImageRgb16(x) => x, @@ -296,6 +321,7 @@ impl DynamicImage { /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. + #[must_use] pub fn into_rgb32f(self) -> Rgb32FImage { match self { DynamicImage::ImageRgb32F(x) => x, @@ -307,6 +333,7 @@ impl DynamicImage { /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. + #[must_use] pub fn into_rgba8(self) -> RgbaImage { match self { DynamicImage::ImageRgba8(x) => x, @@ -318,6 +345,7 @@ impl DynamicImage { /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. + #[must_use] pub fn into_rgba16(self) -> Rgba16Image { match self { DynamicImage::ImageRgba16(x) => x, @@ -329,6 +357,7 @@ impl DynamicImage { /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. + #[must_use] pub fn into_rgba32f(self) -> Rgba32FImage { match self { DynamicImage::ImageRgba32F(x) => x, @@ -340,6 +369,7 @@ impl DynamicImage { /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. + #[must_use] pub fn into_luma8(self) -> GrayImage { match self { DynamicImage::ImageLuma8(x) => x, @@ -351,6 +381,7 @@ impl DynamicImage { /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. + #[must_use] pub fn into_luma16(self) -> Gray16Image { match self { DynamicImage::ImageLuma16(x) => x, @@ -358,10 +389,11 @@ impl DynamicImage { } } - /// Consume the image and returns a LumaA image. + /// Consume the image and returns a `LumaA` image. /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. + #[must_use] pub fn into_luma_alpha8(self) -> GrayAlphaImage { match self { DynamicImage::ImageLumaA8(x) => x, @@ -369,10 +401,11 @@ impl DynamicImage { } } - /// Consume the image and returns a LumaA image. + /// Consume the image and returns a `LumaA` image. /// /// If the image was already the correct format, it is returned as is. /// Otherwise, a copy is created. + #[must_use] pub fn into_luma_alpha16(self) -> GrayAlpha16Image { match self { DynamicImage::ImageLumaA16(x) => x, @@ -396,6 +429,7 @@ impl DynamicImage { } /// Return a reference to an 8bit RGB image + #[must_use] pub fn as_rgb8(&self) -> Option<&RgbImage> { match *self { DynamicImage::ImageRgb8(ref p) => Some(p), @@ -412,6 +446,7 @@ impl DynamicImage { } /// Return a reference to an 8bit RGBA image + #[must_use] pub fn as_rgba8(&self) -> Option<&RgbaImage> { match *self { DynamicImage::ImageRgba8(ref p) => Some(p), @@ -428,6 +463,7 @@ impl DynamicImage { } /// Return a reference to an 8bit Grayscale image + #[must_use] pub fn as_luma8(&self) -> Option<&GrayImage> { match *self { DynamicImage::ImageLuma8(ref p) => Some(p), @@ -444,6 +480,7 @@ impl DynamicImage { } /// Return a reference to an 8bit Grayscale image with an alpha channel + #[must_use] pub fn as_luma_alpha8(&self) -> Option<&GrayAlphaImage> { match *self { DynamicImage::ImageLumaA8(ref p) => Some(p), @@ -460,6 +497,7 @@ impl DynamicImage { } /// Return a reference to an 16bit RGB image + #[must_use] pub fn as_rgb16(&self) -> Option<&Rgb16Image> { match *self { DynamicImage::ImageRgb16(ref p) => Some(p), @@ -476,6 +514,7 @@ impl DynamicImage { } /// Return a reference to an 16bit RGBA image + #[must_use] pub fn as_rgba16(&self) -> Option<&Rgba16Image> { match *self { DynamicImage::ImageRgba16(ref p) => Some(p), @@ -492,6 +531,7 @@ impl DynamicImage { } /// Return a reference to an 32bit RGB image + #[must_use] pub fn as_rgb32f(&self) -> Option<&Rgb32FImage> { match *self { DynamicImage::ImageRgb32F(ref p) => Some(p), @@ -508,6 +548,7 @@ impl DynamicImage { } /// Return a reference to an 32bit RGBA image + #[must_use] pub fn as_rgba32f(&self) -> Option<&Rgba32FImage> { match *self { DynamicImage::ImageRgba32F(ref p) => Some(p), @@ -524,6 +565,7 @@ impl DynamicImage { } /// Return a reference to an 16bit Grayscale image + #[must_use] pub fn as_luma16(&self) -> Option<&Gray16Image> { match *self { DynamicImage::ImageLuma16(ref p) => Some(p), @@ -540,6 +582,7 @@ impl DynamicImage { } /// Return a reference to an 16bit Grayscale image with an alpha channel + #[must_use] pub fn as_luma_alpha16(&self) -> Option<&GrayAlpha16Image> { match *self { DynamicImage::ImageLumaA16(ref p) => Some(p), @@ -556,6 +599,7 @@ impl DynamicImage { } /// Return a view on the raw sample buffer for 8 bit per channel images. + #[must_use] pub fn as_flat_samples_u8(&self) -> Option> { match *self { DynamicImage::ImageLuma8(ref p) => Some(p.as_flat_samples()), @@ -567,6 +611,7 @@ impl DynamicImage { } /// Return a view on the raw sample buffer for 16 bit per channel images. + #[must_use] pub fn as_flat_samples_u16(&self) -> Option> { match *self { DynamicImage::ImageLuma16(ref p) => Some(p.as_flat_samples()), @@ -578,6 +623,7 @@ impl DynamicImage { } /// Return a view on the raw sample buffer for 32bit per channel images. + #[must_use] pub fn as_flat_samples_f32(&self) -> Option> { match *self { DynamicImage::ImageRgb32F(ref p) => Some(p.as_flat_samples()), @@ -587,6 +633,7 @@ impl DynamicImage { } /// Return this image's pixels as a native endian byte slice. + #[must_use] pub fn as_bytes(&self) -> &[u8] { // we can do this because every variant contains an `ImageBuffer<_, Vec<_>>` dynamic_map!( @@ -609,6 +656,7 @@ impl DynamicImage { /// Return this image's pixels as a byte vector. If the `ImageBuffer` /// container is `Vec`, this operation is free. Otherwise, a copy /// is returned. + #[must_use] pub fn into_bytes(self) -> Vec { // we can do this because every variant contains an `ImageBuffer<_, Vec<_>>` dynamic_map!(self, image_buffer, { @@ -627,6 +675,7 @@ impl DynamicImage { } /// Return this image's color type. + #[must_use] pub fn color(&self) -> color::ColorType { match *self { DynamicImage::ImageLuma8(_) => color::ColorType::L8, @@ -643,11 +692,13 @@ impl DynamicImage { } /// Returns the width of the underlying image + #[must_use] pub fn width(&self) -> u32 { dynamic_map!(*self, ref p, { p.width() }) } /// Returns the height of the underlying image + #[must_use] pub fn height(&self) -> u32 { dynamic_map!(*self, ref p, { p.height() }) } @@ -686,7 +737,7 @@ impl DynamicImage { /// Invert the colors of this image. /// This method operates inplace. pub fn invert(&mut self) { - dynamic_map!(*self, ref mut p, imageops::invert(p)) + dynamic_map!(*self, ref mut p, imageops::invert(p)); } /// Resize this image using the specified filter algorithm. @@ -791,9 +842,7 @@ impl DynamicImage { /// Filters this image with the specified 3x3 kernel. #[must_use] pub fn filter3x3(&self, kernel: &[f32]) -> DynamicImage { - if kernel.len() != 9 { - panic!("filter must be 3 x 3") - } + assert_eq!(9, kernel.len(), "filter must be 3 x 3"); dynamic_map!(*self, ref p => imageops::filter3x3(p, kernel)) } @@ -1007,7 +1056,7 @@ impl GenericImage for DynamicImage { DynamicImage::ImageRgba8(ref mut p) => p.put_pixel(x, y, pixel), DynamicImage::ImageLuma16(ref mut p) => p.put_pixel(x, y, pixel.to_luma().into_color()), DynamicImage::ImageLumaA16(ref mut p) => { - p.put_pixel(x, y, pixel.to_luma_alpha().into_color()) + p.put_pixel(x, y, pixel.to_luma_alpha().into_color()); } DynamicImage::ImageRgb16(ref mut p) => p.put_pixel(x, y, pixel.to_rgb().into_color()), DynamicImage::ImageRgba16(ref mut p) => p.put_pixel(x, y, pixel.into_color()), @@ -1023,15 +1072,15 @@ impl GenericImage for DynamicImage { DynamicImage::ImageRgb8(ref mut p) => p.blend_pixel(x, y, pixel.to_rgb()), DynamicImage::ImageRgba8(ref mut p) => p.blend_pixel(x, y, pixel), DynamicImage::ImageLuma16(ref mut p) => { - p.blend_pixel(x, y, pixel.to_luma().into_color()) + p.blend_pixel(x, y, pixel.to_luma().into_color()); } DynamicImage::ImageLumaA16(ref mut p) => { - p.blend_pixel(x, y, pixel.to_luma_alpha().into_color()) + p.blend_pixel(x, y, pixel.to_luma_alpha().into_color()); } DynamicImage::ImageRgb16(ref mut p) => p.blend_pixel(x, y, pixel.to_rgb().into_color()), DynamicImage::ImageRgba16(ref mut p) => p.blend_pixel(x, y, pixel.into_color()), DynamicImage::ImageRgb32F(ref mut p) => { - p.blend_pixel(x, y, pixel.to_rgb().into_color()) + p.blend_pixel(x, y, pixel.to_rgb().into_color()); } DynamicImage::ImageRgba32F(ref mut p) => p.blend_pixel(x, y, pixel.into_color()), } diff --git a/src/error.rs b/src/error.rs index 3a259e4628..5201c7b8c8 100644 --- a/src/error.rs +++ b/src/error.rs @@ -194,16 +194,19 @@ impl UnsupportedError { /// /// If the operation was not connected to a particular image format then the hint may be /// `Unknown`. + #[must_use] pub fn from_format_and_kind(format: ImageFormatHint, kind: UnsupportedErrorKind) -> Self { UnsupportedError { format, kind } } /// Returns the corresponding `UnsupportedErrorKind` of the error. + #[must_use] pub fn kind(&self) -> UnsupportedErrorKind { self.kind.clone() } /// Returns the image format associated with this error. + #[must_use] pub fn format_hint(&self) -> ImageFormatHint { self.format.clone() } @@ -221,6 +224,7 @@ impl DecodingError { /// Create a `DecodingError` for an image format. /// /// The error will not contain any further information but is very easy to create. + #[must_use] pub fn from_format_hint(format: ImageFormatHint) -> Self { DecodingError { format, @@ -229,6 +233,7 @@ impl DecodingError { } /// Returns the image format associated with this error. + #[must_use] pub fn format_hint(&self) -> ImageFormatHint { self.format.clone() } @@ -246,6 +251,7 @@ impl EncodingError { /// Create an `EncodingError` for an image format. /// /// The error will not contain any further information but is very easy to create. + #[must_use] pub fn from_format_hint(format: ImageFormatHint) -> Self { EncodingError { format, @@ -254,6 +260,7 @@ impl EncodingError { } /// Return the image format associated with this error. + #[must_use] pub fn format_hint(&self) -> ImageFormatHint { self.format.clone() } @@ -261,6 +268,7 @@ impl EncodingError { impl ParameterError { /// Construct a `ParameterError` directly from a corresponding kind. + #[must_use] pub fn from_kind(kind: ParameterErrorKind) -> Self { ParameterError { kind, @@ -269,6 +277,7 @@ impl ParameterError { } /// Returns the corresponding `ParameterErrorKind` of the error. + #[must_use] pub fn kind(&self) -> ParameterErrorKind { self.kind.clone() } @@ -276,11 +285,13 @@ impl ParameterError { impl LimitError { /// Construct a generic `LimitError` directly from a corresponding kind. + #[must_use] pub fn from_kind(kind: LimitErrorKind) -> Self { LimitError { kind } } /// Returns the corresponding `LimitErrorKind` of the error. + #[must_use] pub fn kind(&self) -> LimitErrorKind { self.kind.clone() } @@ -353,11 +364,10 @@ impl fmt::Display for UnsupportedError { } UnsupportedErrorKind::Format(format @ ImageFormatHint::PathExtension(_)) => write!( fmt, - "The file extension {} was not recognized as an image format", - format, + "The file extension {format} was not recognized as an image format", ), UnsupportedErrorKind::Format(format) => { - write!(fmt, "The image format {} is not supported", format,) + write!(fmt, "The image format {format} is not supported",) } UnsupportedErrorKind::Color(color) => write!( fmt, @@ -367,13 +377,11 @@ impl fmt::Display for UnsupportedError { UnsupportedErrorKind::GenericFeature(message) => match &self.format { ImageFormatHint::Unknown => write!( fmt, - "The decoder does not support the format feature {}", - message, + "The decoder does not support the format feature {message}", ), other => write!( fmt, - "The decoder for {} does not support the format features {}", - other, message, + "The decoder for {other} does not support the format features {message}", ), }, } @@ -395,13 +403,13 @@ impl fmt::Display for ParameterError { "The end the image stream has been reached due to a previous error" ), ParameterErrorKind::Generic(message) => { - write!(fmt, "The parameter is malformed: {}", message,) + write!(fmt, "The parameter is malformed: {message}",) } ParameterErrorKind::NoMoreData => write!(fmt, "The end of the image has been reached",), }?; if let Some(underlying) = &self.underlying { - write!(fmt, "\n{}", underlying)?; + write!(fmt, "\n{underlying}")?; } Ok(()) @@ -480,9 +488,9 @@ impl Error for LimitError {} impl fmt::Display for ImageFormatHint { fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { - ImageFormatHint::Exact(format) => write!(fmt, "{:?}", format), - ImageFormatHint::Name(name) => write!(fmt, "`{}`", name), - ImageFormatHint::PathExtension(ext) => write!(fmt, "`.{:?}`", ext), + ImageFormatHint::Exact(format) => write!(fmt, "{format:?}"), + ImageFormatHint::Name(name) => write!(fmt, "`{name}`"), + ImageFormatHint::PathExtension(ext) => write!(fmt, "`.{ext:?}`"), ImageFormatHint::Unknown => write!(fmt, "`Unknown`"), } } @@ -491,11 +499,11 @@ impl fmt::Display for ImageFormatHint { #[cfg(test)] mod tests { use super::*; - use std::mem; + use std::mem::size_of; #[allow(dead_code)] // This will fail to compile if the size of this type is large. - const ASSERT_SMALLISH: usize = [0][(mem::size_of::() >= 200) as usize]; + const ASSERT_SMALLISH: usize = [0][(size_of::() >= 200) as usize]; #[test] fn test_send_sync_stability() { diff --git a/src/flat.rs b/src/flat.rs index d54b8c6539..9883e94191 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -141,6 +141,7 @@ impl SampleLayout { /// On platforms where `usize` has the same size as `u32` this panics when the resulting stride /// in the `height` direction would be larger than `usize::MAX`. On other platforms /// where it can surely accommodate `u8::MAX * u32::MAX, this can never happen. + #[must_use] pub fn row_major_packed(channels: u8, width: u32, height: u32) -> Self { let height_stride = (channels as usize).checked_mul(width as usize).expect( "Row major packed image can not be described because it does not fit into memory", @@ -171,6 +172,7 @@ impl SampleLayout { /// On platforms where `usize` has the same size as `u32` this panics when the resulting stride /// in the `width` direction would be larger than `usize::MAX`. On other platforms /// where it can surely accommodate `u8::MAX * u32::MAX, this can never happen. + #[must_use] pub fn column_major_packed(channels: u8, width: u32, height: u32) -> Self { let width_stride = (channels as usize).checked_mul(height as usize).expect( "Column major packed image can not be described because it does not fit into memory", @@ -189,6 +191,7 @@ impl SampleLayout { /// /// For a row-major layout with grouped samples, this tuple is strictly /// increasing. + #[must_use] pub fn strides_cwh(&self) -> (usize, usize, usize) { (self.channel_stride, self.width_stride, self.height_stride) } @@ -197,6 +200,7 @@ impl SampleLayout { /// /// The interface is optimized for use with `strides_cwh` instead. The channel extent will be /// before width and height. + #[must_use] pub fn extents(&self) -> (usize, usize, usize) { ( self.channels as usize, @@ -209,6 +213,7 @@ impl SampleLayout { /// /// This function should be used whenever working with image coordinates opposed to buffer /// coordinates. The only difference compared to `extents` is the output type. + #[must_use] pub fn bounds(&self) -> (u8, u32, u32) { (self.channels, self.width, self.height) } @@ -264,6 +269,7 @@ impl SampleLayout { /// This time 'one-past-the-end' is not even simply the largest stride times the extent of its /// dimension. That still points inside the image because `height*height_stride = 4` but also /// `index_of(1, 2) = 4`. + #[must_use] pub fn min_length(&self) -> Option { if self.width == 0 || self.height == 0 || self.channels == 0 { return Some(0); @@ -274,8 +280,9 @@ impl SampleLayout { } /// Check if a buffer of length `len` is large enough. + #[must_use] pub fn fits(&self, len: usize) -> bool { - self.min_length().map(|min| len >= min).unwrap_or(false) + self.min_length().map_or(false, |min| len >= min) } /// The extents of this array, in order of increasing strides. @@ -300,6 +307,7 @@ impl SampleLayout { /// If this is not the case, it would always be safe to allow mutable access to two different /// samples at the same time. Otherwise, this operation would need additional checks. When one /// dimension overflows `usize` with its stride we also consider this aliasing. + #[must_use] pub fn has_aliased_samples(&self) -> bool { let grouped = self.increasing_stride_dims(); let (min_dim, mid_dim, max_dim) = (grouped[0], grouped[1], grouped[2]); @@ -330,6 +338,7 @@ impl SampleLayout { /// checks can all be done in constant time and will not inspect the buffer content. You can /// perform these checks yourself when the conversion is not required at this moment but maybe /// still performed later. + #[must_use] pub fn is_normal(&self, form: NormalForm) -> bool { if self.has_aliased_samples() { return false; @@ -385,6 +394,7 @@ impl SampleLayout { /// An in-bound coordinate does not yet guarantee that the corresponding calculation of a /// buffer index does not overflow. However, if such a buffer large enough to hold all samples /// actually exists in memory, this property of course follows. + #[must_use] pub fn in_bounds(&self, channel: u8, x: u32, y: u32) -> bool { channel < self.channels && x < self.width && y < self.height } @@ -392,6 +402,7 @@ impl SampleLayout { /// Resolve the index of a particular sample. /// /// `None` if the index is outside the bounds or does not fit into a `usize`. + #[must_use] pub fn index(&self, channel: u8, x: u32, y: u32) -> Option { if !self.in_bounds(channel, x, y) { return None; @@ -405,6 +416,7 @@ impl SampleLayout { /// The 'check' is for overflow during index calculation, not that it is contained in the /// image. Two samples may return the same index, even when one of them is out of bounds. This /// happens when all strides are `0`, i.e. the image is an arbitrarily large monochrome image. + #[must_use] pub fn index_ignoring_bounds(&self, channel: usize, x: usize, y: usize) -> Option { let idx_c = channel.checked_mul(self.channel_stride); let idx_x = x.checked_mul(self.width_stride); @@ -429,6 +441,7 @@ impl SampleLayout { /// /// Behavior is *unspecified* if the index is out of bounds or this sample layout would require /// a buffer larger than `isize::MAX` bytes. + #[must_use] pub fn in_bounds_index(&self, c: u8, x: u32, y: u32) -> usize { let (c_stride, x_stride, y_stride) = self.strides_cwh(); (y as usize * y_stride) + (x as usize * x_stride) + (c as usize * c_stride) @@ -921,7 +934,7 @@ impl FlatSamples { /// created by the shrinking operation. Shrinking could also lead to an non-aliasing image when /// samples had aliased each other before. pub fn shrink_to(&mut self, channels: u8, width: u32, height: u32) { - self.layout.shrink_to(channels, width, height) + self.layout.shrink_to(channels, width, height); } } @@ -1043,7 +1056,7 @@ pub enum Error { /// care about the value of the alpha channel even though you need `Rgba`. ChannelCountMismatch(u8, u8), - /// Deprecated - ChannelCountMismatch is used instead + /// Deprecated - `ChannelCountMismatch` is used instead WrongColor(ColorType), } @@ -1184,7 +1197,7 @@ where /// Note that you can not change the number of channels as an intrinsic property of `P`. pub fn shrink_to(&mut self, width: u32, height: u32) { let channels = self.inner.layout.channels; - self.inner.shrink_to(channels, width, height) + self.inner.shrink_to(channels, width, height); } /// Try to convert this into an image with mutable pixels. @@ -1313,7 +1326,7 @@ where /// Note that you can not change the number of channels as an intrinsic property of `P`. pub fn shrink_to(&mut self, width: u32, height: u32) { let channels = self.inner.layout.channels; - self.inner.shrink_to(channels, width, height) + self.inner.shrink_to(channels, width, height); } } @@ -1519,16 +1532,12 @@ impl fmt::Display for Error { NormalForm::Unaliased => "not have any aliasing channels", } ), - Error::ChannelCountMismatch(layout_channels, pixel_channels) => write!( - f, - "The channel count of the chosen pixel (={}) does agree with the layout (={})", - pixel_channels, layout_channels - ), - Error::WrongColor(color) => write!( - f, - "The chosen color type does not match the hint {:?}", - color - ), + Error::ChannelCountMismatch(layout_channels, pixel_channels) => { + write!(f, "The channel count of the chosen pixel (={pixel_channels}) does agree with the layout (={layout_channels})") + } + Error::WrongColor(color) => { + write!(f, "The chosen color type does not match the hint {color:?}") + } } } } diff --git a/src/image.rs b/src/image.rs index 97a2ed0351..754f438253 100644 --- a/src/image.rs +++ b/src/image.rs @@ -201,6 +201,7 @@ impl ImageFormat { /// let mime_type = ImageFormat::Png.to_mime_type(); /// assert_eq!(mime_type, "image/png"); /// ``` + #[must_use] pub fn to_mime_type(&self) -> &'static str { match self { ImageFormat::Avif => "image/avif", @@ -226,8 +227,9 @@ impl ImageFormat { } } - /// Return if the ImageFormat can be decoded by the lib. + /// Return if the `ImageFormat` can be decoded by the lib. #[inline] + #[must_use] pub fn can_read(&self) -> bool { // Needs to be updated once a new variant's decoder is added to free_functions.rs::load match self { @@ -249,8 +251,9 @@ impl ImageFormat { } } - /// Return if the ImageFormat can be encoded by the lib. + /// Return if the `ImageFormat` can be encoded by the lib. #[inline] + #[must_use] pub fn can_write(&self) -> bool { // Needs to be updated once a new variant's encoder is added to free_functions.rs::save_buffer_with_format_impl match self { @@ -281,6 +284,7 @@ impl ImageFormat { /// /// The method name `extensions` remains reserved for introducing another method in the future /// that yields a slice of `OsStr` which is blocked by several features of const evaluation. + #[must_use] pub fn extensions_str(self) -> &'static [&'static str] { match self { ImageFormat::Png => &["png"], @@ -302,8 +306,9 @@ impl ImageFormat { } } - /// Return the ImageFormats which are enabled for reading. + /// Return the `ImageFormat`s which are enabled for reading. #[inline] + #[must_use] pub fn reading_enabled(&self) -> bool { match self { ImageFormat::Png => cfg!(feature = "png"), @@ -324,8 +329,9 @@ impl ImageFormat { } } - /// Return the ImageFormats which are enabled for writing. + /// Return the `ImageFormat`s which are enabled for writing. #[inline] + #[must_use] pub fn writing_enabled(&self) -> bool { match self { ImageFormat::Gif => cfg!(feature = "gif"), @@ -346,7 +352,7 @@ impl ImageFormat { } } - /// Return all ImageFormats + /// Return all `ImageFormat`s pub fn all() -> impl Iterator { [ ImageFormat::Gif, @@ -383,9 +389,9 @@ pub(crate) struct ImageReadBuffer { offset: u64, } impl ImageReadBuffer { - /// Create a new ImageReadBuffer. + /// Create a new `ImageReadBuffer`. /// - /// Panics if scanline_bytes doesn't fit into a usize, because that would mean reading anything + /// Panics if `scanline_bytes` doesn't fit into a usize, because that would mean reading anything /// from the image would take more RAM than the entire virtual address space. In other words, /// actually using this struct would instantly OOM so just get it out of the way now. #[allow(dead_code)] @@ -481,13 +487,12 @@ where let row_bytes = bytes_per_pixel * u64::from(dimensions.0); let total_bytes = width * height * bytes_per_pixel; - if buf.len() < usize::try_from(total_bytes).unwrap_or(usize::MAX) { - panic!( - "output buffer too short\n expected `{}`, provided `{}`", - total_bytes, - buf.len() - ); - } + assert!( + buf.len() >= usize::try_from(total_bytes).unwrap_or(usize::MAX), + "output buffer too short\n expected `{}`, provided `{}`", + total_bytes, + buf.len() + ); let mut current_scanline = 0; let mut tmp = Vec::new(); @@ -597,7 +602,7 @@ where ))); } - let mut buf = vec![num_traits::Zero::zero(); total_bytes.unwrap() / std::mem::size_of::()]; + let mut buf = vec![num_traits::Zero::zero(); total_bytes.unwrap() / size_of::()]; decoder.read_image(bytemuck::cast_slice_mut(buf.as_mut_slice()))?; Ok(buf) } @@ -625,9 +630,9 @@ pub trait ImageDecoder { /// Returns the total number of bytes in the decoded image. /// /// This is the size of the buffer that must be passed to `read_image` or - /// `read_image_with_progress`. The returned value may exceed usize::MAX, in + /// `read_image_with_progress`. The returned value may exceed `usize::MAX`, in /// which case it isn't actually possible to construct a buffer to decode all the image data - /// into. If, however, the size does not fit in a u64 then u64::MAX is returned. + /// into. If, however, the size does not fit in a u64 then `u64::MAX` is returned. fn total_bytes(&self) -> u64 { let dimensions = self.dimensions(); let total_pixels = u64::from(dimensions.0) * u64::from(dimensions.1); @@ -644,7 +649,7 @@ pub trait ImageDecoder { /// /// # Panics /// - /// This function panics if buf.len() != self.total_bytes(). + /// This function panics if `buf.len() != self.total_bytes()`. /// /// # Examples /// @@ -741,7 +746,7 @@ pub trait ImageDecoderRect: ImageDecoder { ) -> ImageResult<()>; } -/// AnimationDecoder trait +/// `AnimationDecoder` trait pub trait AnimationDecoder<'a> { /// Consume the decoder producing a series of frames. fn into_frames(self) -> Frames<'a>; @@ -887,8 +892,8 @@ pub trait GenericImageView { where Self: Sized, { - assert!(x as u64 + width as u64 <= self.width() as u64); - assert!(y as u64 + height as u64 <= self.height() as u64); + assert!(u64::from(x) + u64::from(width) <= u64::from(self.width())); + assert!(u64::from(y) + u64::from(height) <= u64::from(self.height())); SubImage::new(self, x, y, width, height) } } @@ -1029,13 +1034,13 @@ pub trait GenericImage: GenericImageView { /// Returns a mutable subimage that is a view into this image. /// If you want an immutable subimage instead, use [`GenericImageView::view`] - /// The coordinates set the position of the top left corner of the SubImage. + /// The coordinates set the position of the top left corner of the `SubImage`. fn sub_image(&mut self, x: u32, y: u32, width: u32, height: u32) -> SubImage<&mut Self> where Self: Sized, { - assert!(x as u64 + width as u64 <= self.width() as u64); - assert!(y as u64 + height as u64 <= self.height() as u64); + assert!(u64::from(x) + u64::from(width) <= u64::from(self.width())); + assert!(u64::from(y) + u64::from(height) <= u64::from(self.height())); SubImage::new(self, x, y, width, height) } } @@ -1087,7 +1092,7 @@ type DerefSubpixel = as Pixel>::Subpixel; impl SubImage { /// Construct a new subimage - /// The coordinates set the position of the top left corner of the SubImage. + /// The coordinates set the position of the top left corner of the `SubImage`. pub fn new(image: I, x: u32, y: u32, width: u32, height: u32) -> SubImage { SubImage { inner: SubImageInner { @@ -1113,14 +1118,14 @@ impl SubImage { (self.inner.xoffset, self.inner.yoffset) } - /// Convert this subimage to an ImageBuffer + /// Convert this subimage to an `ImageBuffer` pub fn to_image(&self) -> ImageBuffer, Vec>> where I: Deref, I::Target: GenericImageView + 'static, { let mut out = ImageBuffer::new(self.inner.xstride, self.inner.ystride); - let borrowed = self.inner.image.deref(); + let borrowed = &*self.inner.image; for y in 0..self.inner.ystride { for x in 0..self.inner.xstride { @@ -1159,8 +1164,8 @@ where /// ``` pub fn view(&self, x: u32, y: u32, width: u32, height: u32) -> SubImage<&I::Target> { use crate::GenericImageView as _; - assert!(x as u64 + width as u64 <= self.inner.width() as u64); - assert!(y as u64 + height as u64 <= self.inner.height() as u64); + assert!(u64::from(x) + u64::from(width) <= u64::from(self.inner.width())); + assert!(u64::from(y) + u64::from(height) <= u64::from(self.inner.height())); let x = self.inner.xoffset.saturating_add(x); let y = self.inner.yoffset.saturating_add(y); SubImage::new(&*self.inner.image, x, y, width, height) @@ -1187,8 +1192,8 @@ where width: u32, height: u32, ) -> SubImage<&mut I::Target> { - assert!(x as u64 + width as u64 <= self.inner.width() as u64); - assert!(y as u64 + height as u64 <= self.inner.height() as u64); + assert!(u64::from(x) + u64::from(width) <= u64::from(self.inner.width())); + assert!(u64::from(y) + u64::from(height) <= u64::from(self.inner.height())); let x = self.inner.xoffset.saturating_add(x); let y = self.inner.yoffset.saturating_add(y); SubImage::new(&mut *self.inner.image, x, y, width, height) @@ -1248,13 +1253,13 @@ where fn put_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) { self.image - .put_pixel(x + self.xoffset, y + self.yoffset, pixel) + .put_pixel(x + self.xoffset, y + self.yoffset, pixel); } /// DEPRECATED: This method will be removed. Blend the pixel directly instead. fn blend_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) { self.image - .blend_pixel(x + self.xoffset, y + self.yoffset, pixel) + .blend_pixel(x + self.xoffset, y + self.yoffset, pixel); } } @@ -1776,7 +1781,7 @@ mod tests { ColorType::Rgb8 } fn dimensions(&self) -> (u32, u32) { - (0xffffffff, 0xffffffff) + (0xffff_ffff, 0xffff_ffff) } fn read_image(self, _buf: &mut [u8]) -> ImageResult<()> { unimplemented!() diff --git a/src/image_reader/free_functions.rs b/src/image_reader/free_functions.rs index f353236535..7a9bb34400 100644 --- a/src/image_reader/free_functions.rs +++ b/src/image_reader/free_functions.rs @@ -118,7 +118,7 @@ pub(crate) fn write_buffer_impl( _ => Err(ImageError::Unsupported( UnsupportedError::from_format_and_kind( ImageFormatHint::Unknown, - UnsupportedErrorKind::Format(ImageFormatHint::Name(format!("{:?}", format))), + UnsupportedErrorKind::Format(ImageFormatHint::Name(format!("{format:?}"))), ), )), } diff --git a/src/image_reader/image_reader_type.rs b/src/image_reader/image_reader_type.rs index 594786bddb..479316f191 100644 --- a/src/image_reader/image_reader_type.rs +++ b/src/image_reader/image_reader_type.rs @@ -134,7 +134,7 @@ impl<'a, R: 'a + BufRead + Seek> ImageReader { /// Makes a decoder. /// /// For all formats except PNG, the limits are ignored and can be set with - /// ImageDecoder::set_limits after calling this function. PNG is handled specially because that + /// `ImageDecoder::set_limits` after calling this function. PNG is handled specially because that /// decoder has a different API which does not allow setting limits after construction. fn make_decoder( format: ImageFormat, diff --git a/src/image_reader/mod.rs b/src/image_reader/mod.rs index 0086ab154f..a1673a3cec 100644 --- a/src/image_reader/mod.rs +++ b/src/image_reader/mod.rs @@ -22,7 +22,7 @@ pub struct LimitSupport {} /// rely on these limits being supported. For strict limits, the library makes a stronger /// guarantee that the limit will not be exceeded. Exceeding a strict limit is considered /// a critical bug. If a decoder cannot guarantee that it will uphold a strict limit, it -/// *must* fail with [error::LimitErrorKind::Unsupported]. +/// *must* fail with [`error::LimitErrorKind::Unsupported`]. /// /// The only currently supported strict limits are the `max_image_width` and `max_image_height` /// limits, but more will be added in the future. [`LimitSupport`] will default to support @@ -61,6 +61,7 @@ impl Default for Limits { impl Limits { /// Disable all limits. + #[must_use] pub fn no_limits() -> Limits { Limits { max_image_width: None, @@ -140,8 +141,8 @@ impl Limits { color_type: ColorType, ) -> ImageResult<()> { self.check_dimensions(width, height)?; - let in_memory_size = (width as u64) - .saturating_mul(height as u64) + let in_memory_size = u64::from(width) + .saturating_mul(u64::from(height)) .saturating_mul(color_type.bytes_per_pixel().into()); self.reserve(in_memory_size)?; Ok(()) diff --git a/src/imageops/colorops.rs b/src/imageops/colorops.rs index 86d53ecaf5..0c746db109 100644 --- a/src/imageops/colorops.rs +++ b/src/imageops/colorops.rs @@ -355,12 +355,12 @@ pub trait ColorMap { /// in the color map. fn index_of(&self, color: &Self::Color) -> usize; /// Looks up color by index in the color map. If `idx` is out of range for the color map, or - /// ColorMap doesn't implement `lookup` `None` is returned. + /// `ColorMap` doesn't implement `lookup` `None` is returned. fn lookup(&self, index: usize) -> Option { let _ = index; None } - /// Determine if this implementation of ColorMap overrides the default `lookup`. + /// Determine if this implementation of `ColorMap` overrides the default `lookup`. fn has_lookup(&self) -> bool { false } @@ -422,7 +422,7 @@ impl ColorMap for BiLevel { } } - /// Indicate NeuQuant implements `lookup`. + /// Indicate `NeuQuant` implements `lookup`. fn has_lookup(&self) -> bool { true } @@ -537,7 +537,7 @@ where { let mut indices = ImageBuffer::new(image.width(), image.height()); for (pixel, idx) in image.pixels().zip(indices.pixels_mut()) { - *idx = Luma([color_map.index_of(pixel) as u8]) + *idx = Luma([color_map.index_of(pixel) as u8]); } indices } diff --git a/src/imageops/mod.rs b/src/imageops/mod.rs index 9b296100b0..54074218e3 100644 --- a/src/imageops/mod.rs +++ b/src/imageops/mod.rs @@ -132,6 +132,7 @@ fn crop_dimms( /// ``` /// /// Proof is the same for height. +#[must_use] pub fn overlay_bounds( (bottom_width, bottom_height): (u32, u32), (top_width, top_height): (u32, u32), diff --git a/src/lib.rs b/src/lib.rs index 6a9293f3c3..72f1109c0c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -55,12 +55,12 @@ //! //! The two main types for storing images: //! * [`ImageBuffer`] which holds statically typed image contents. -//! * [`DynamicImage`] which is an enum over the supported ImageBuffer formats +//! * [`DynamicImage`] which is an enum over the supported `ImageBuffer` formats //! and supports conversions between them. //! //! As well as a few more specialized options: //! * [`GenericImage`] trait for a mutable image buffer. -//! * [`GenericImageView`] trait for read only references to a GenericImage. +//! * [`GenericImageView`] trait for read only references to a `GenericImage`. //! * [`flat`] module containing types for interoperability with generic channel //! matrices and foreign interfaces. //! diff --git a/src/math/utils.rs b/src/math/utils.rs index a592c28737..47f01efa6b 100644 --- a/src/math/utils.rs +++ b/src/math/utils.rs @@ -16,8 +16,8 @@ pub(crate) fn resize_dimensions( nheight: u32, fill: bool, ) -> (u32, u32) { - let wratio = nwidth as f64 / width as f64; - let hratio = nheight as f64 / height as f64; + let wratio = f64::from(nwidth) / f64::from(width); + let hratio = f64::from(nheight) / f64::from(height); let ratio = if fill { f64::max(wratio, hratio) @@ -25,15 +25,15 @@ pub(crate) fn resize_dimensions( f64::min(wratio, hratio) }; - let nw = max((width as f64 * ratio).round() as u64, 1); - let nh = max((height as f64 * ratio).round() as u64, 1); + let nw = max((f64::from(width) * ratio).round() as u64, 1); + let nh = max((f64::from(height) * ratio).round() as u64, 1); if nw > u64::from(u32::MAX) { - let ratio = u32::MAX as f64 / width as f64; - (u32::MAX, max((height as f64 * ratio).round() as u32, 1)) + let ratio = f64::from(u32::MAX) / f64::from(width); + (u32::MAX, max((f64::from(height) * ratio).round() as u32, 1)) } else if nh > u64::from(u32::MAX) { - let ratio = u32::MAX as f64 / height as f64; - (max((width as f64 * ratio).round() as u32, 1), u32::MAX) + let ratio = f64::from(u32::MAX) / f64::from(height); + (max((f64::from(width) * ratio).round() as u32, 1), u32::MAX) } else { (nw as u32, nh as u32) } diff --git a/src/traits.rs b/src/traits.rs index a993a3350c..325926d2ad 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -5,10 +5,8 @@ use num_traits::{Bounded, Num, NumCast}; use std::ops::AddAssign; -use crate::{ - color::{Luma, LumaA, Rgb, Rgba}, - ExtendedColorType, -}; +use crate::color::{Luma, LumaA, Rgb, Rgba}; +use crate::ExtendedColorType; /// Types which are safe to treat as an immutable byte slice in a pixel layout /// for image encoding. @@ -70,7 +68,7 @@ declare_primitive!(i64: (Self::MIN)..Self::MAX); declare_primitive!(f32: (0.0)..1.0); declare_primitive!(f64: (0.0)..1.0); -/// An Enlargable::Larger value should be enough to calculate +/// An `Enlargable::Larger` value should be enough to calculate /// the sum (average) of a few hundred or thousand Enlargeable values. pub trait Enlargeable: Sized + Bounded + NumCast { type Larger: Copy + NumCast + Num + PartialOrd + Clone + Bounded + AddAssign; diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 7313eab75a..dff6cc760a 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -26,7 +26,7 @@ where for ((shift, i), j_inv) in i.zip(j_inv) { let j = buf_len - j_inv; let pixel = (buf[i] & (mask << shift)) >> shift; - func(pixel, &mut buf[j..(j + channels)]) + func(pixel, &mut buf[j..(j + channels)]); } } @@ -66,7 +66,7 @@ pub(crate) fn expand_bits(bit_depth: u8, row_size: u32, buf: &[u8]) -> Vec { #[allow(dead_code)] // When no image formats that use it are enabled pub(crate) fn check_dimension_overflow(width: u32, height: u32, bytes_per_pixel: u8) -> bool { - width as u64 * height as u64 > u64::MAX / bytes_per_pixel as u64 + u64::from(width) * u64::from(height) > u64::MAX / u64::from(bytes_per_pixel) } #[allow(dead_code)] diff --git a/tests/reference_images.rs b/tests/reference_images.rs index 02ef47d1d5..da573b1ad2 100644 --- a/tests/reference_images.rs +++ b/tests/reference_images.rs @@ -34,7 +34,7 @@ where ); let pattern = &*format!("{}", path.display()); for path in glob::glob(pattern).unwrap().filter_map(Result::ok) { - func(&base, path, decoder) + func(&base, path, decoder); } } } @@ -45,7 +45,7 @@ fn render_images() { process_images(IMAGE_DIR, None, |base, path, decoder| { println!("render_images {}", path.display()); let img = match image::open(&path) { - Ok(DynamicImage::ImageRgb32F(_)) | Ok(DynamicImage::ImageRgba32F(_)) => { + Ok(DynamicImage::ImageRgb32F(_) | DynamicImage::ImageRgba32F(_)) => { println!("Skipping {} - HDR codec is not enabled", path.display()); return; } @@ -57,7 +57,7 @@ fn render_images() { println!("UNSUPPORTED {}: {}", path.display(), e); return; } - Err(err) => panic!("decoding of {:?} failed with: {}", path, err), + Err(err) => panic!("decoding of {path:?} failed with: {err}"), }; let mut crc = Crc32::new(); crc.update(img.as_bytes()); @@ -78,7 +78,7 @@ fn render_images() { crc.finalize(), )); img.save(out_path).unwrap(); - }) + }); } /// Describes a single test case of `check_references`. @@ -201,7 +201,7 @@ fn check_references() { Ok(decoder) => decoder, Err(image::ImageError::Unsupported(_)) => return, Err(err) => { - panic!("decoding of {:?} failed with: {}", img_path, err) + panic!("decoding of {img_path:?} failed with: {err}") } }; @@ -209,7 +209,7 @@ fn check_references() { Ok(frames) => frames, Err(image::ImageError::Unsupported(_)) => return, Err(err) => { - panic!("collecting frames of {:?} failed with: {}", img_path, err) + panic!("collecting frames of {img_path:?} failed with: {err}") } }; @@ -229,7 +229,7 @@ fn check_references() { Ok(decoder) => decoder.apng().unwrap(), Err(image::ImageError::Unsupported(_)) => return, Err(err) => { - panic!("decoding of {:?} failed with: {}", img_path, err) + panic!("decoding of {img_path:?} failed with: {err}") } }; @@ -237,7 +237,7 @@ fn check_references() { Ok(frames) => frames, Err(image::ImageError::Unsupported(_)) => return, Err(err) => { - panic!("collecting frames of {:?} failed with: {}", img_path, err) + panic!("collecting frames of {img_path:?} failed with: {err}") } }; @@ -262,7 +262,7 @@ fn check_references() { // This might happen because the testsuite contains unsupported images // or because a specific decoder included via a feature. Err(image::ImageError::Unsupported(_)) => return, - Err(err) => panic!("decoding of {:?} failed with: {}", img_path, err), + Err(err) => panic!("decoding of {img_path:?} failed with: {err}"), }; } } @@ -297,19 +297,19 @@ fn check_references() { hasher.finalize() }; - if test_crc_actual != case.crc { - panic!( - "{}: The decoded image's hash does not match (expected = {:08x}, actual = {:08x}).", - img_path.display(), - case.crc, - test_crc_actual - ); - } + assert!( + test_crc_actual == case.crc, + "{}: The decoded image's hash does not match (expected = {:08x}, actual = {:08x}).", + img_path.display(), + case.crc, + test_crc_actual + ); - if ref_img.as_bytes() != test_img.as_bytes() { - panic!("Reference rendering does not match."); - } - }) + assert!( + ref_img.as_bytes() == test_img.as_bytes(), + "Reference rendering does not match." + ); + }); } #[cfg(feature = "hdr")] @@ -358,9 +358,10 @@ fn check_hdr_references() { .iter() .rev() { - match *c { - Normal(name) => ref_path.push(name), - _ => panic!(), + if let Normal(name) = *c { + ref_path.push(name) + } else { + panic!() } } ref_path.set_extension("raw"); diff --git a/tests/regression.rs b/tests/regression.rs index a86fa220dc..78ff0321e5 100644 --- a/tests/regression.rs +++ b/tests/regression.rs @@ -1,8 +1,6 @@ -use std::{ - fs::{self, File}, - io::{BufReader, Cursor}, - path::PathBuf, -}; +use std::fs::{self, File}; +use std::io::{BufReader, Cursor}; +use std::path::PathBuf; #[cfg(feature = "webp")] use image::{codecs::webp::WebPDecoder, AnimationDecoder}; @@ -33,7 +31,7 @@ where ); let pattern = &*format!("{}", path.display()); for path in glob::glob(pattern).unwrap().filter_map(Result::ok) { - func(path) + func(path); } } } @@ -42,7 +40,7 @@ where fn check_regressions() { process_images(REGRESSION_DIR, None, |path| { let _ = image::open(path); - }) + }); } /// Check that the WEBP frames iterator returns the right amount of frames. #[test] diff --git a/tests/truncate_images.rs b/tests/truncate_images.rs index 3347f2296c..de2bbefddd 100644 --- a/tests/truncate_images.rs +++ b/tests/truncate_images.rs @@ -32,57 +32,57 @@ where ); let pattern = &*format!("{}", path.display()); for path in glob::glob(pattern).unwrap().filter_map(Result::ok) { - func(path) + func(path); } } } fn truncate_images(decoder: &str) { process_images(IMAGE_DIR, Some(decoder), |path| { - println!("{:?}", path); + println!("{path:?}"); let fin = fs::File::open(&path).unwrap(); let max_length = 1000; let mut buf = Vec::with_capacity(max_length); fin.take(max_length as u64).read_to_end(&mut buf).unwrap(); for i in (0..buf.len()).step_by(37) { - image::load_from_memory(&buf[..i + 1]).ok(); + image::load_from_memory(&buf[..=i]).ok(); } - }) + }); } #[test] fn truncate_tga() { - truncate_images("tga") + truncate_images("tga"); } #[test] fn truncate_tiff() { - truncate_images("tiff") + truncate_images("tiff"); } #[test] fn truncate_png() { - truncate_images("png") + truncate_images("png"); } #[test] fn truncate_gif() { - truncate_images("gif") + truncate_images("gif"); } #[test] fn truncate_bmp() { - truncate_images("bmp") + truncate_images("bmp"); } #[test] fn truncate_ico() { - truncate_images("ico") + truncate_images("ico"); } #[test] fn truncate_jpg() { - truncate_images("jpg") + truncate_images("jpg"); } #[test]