Skip to content

Commit

Permalink
Clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
kornelski committed Jan 10, 2024
1 parent c33079b commit a9a0e46
Show file tree
Hide file tree
Showing 8 changed files with 64 additions and 59 deletions.
26 changes: 16 additions & 10 deletions src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ pub enum DisposalMethod {

impl DisposalMethod {
/// Converts `u8` to `Option<Self>`
#[must_use]
pub fn from_u8(n: u8) -> Option<DisposalMethod> {
match n {
0 => Some(DisposalMethod::Any),
1 => Some(DisposalMethod::Keep),
2 => Some(DisposalMethod::Background),
3 => Some(DisposalMethod::Previous),
_ => None
_ => None,
}
}
}
Expand Down Expand Up @@ -52,12 +53,13 @@ pub enum Block {

impl Block {
/// Converts `u8` to `Option<Self>`
#[must_use]
pub fn from_u8(n: u8) -> Option<Block> {
match n {
0x2C => Some(Block::Image),
0x21 => Some(Block::Extension),
0x3B => Some(Block::Trailer),
_ => None
_ => None,
}
}
}
Expand Down Expand Up @@ -102,6 +104,7 @@ pub enum Extension {

impl AnyExtension {
/// Decode the label as a known extension.
#[must_use]
pub fn into_known(self) -> Option<Extension> {
Extension::from_u8(self.0)
}
Expand All @@ -115,13 +118,14 @@ impl From<Extension> for AnyExtension {

impl Extension {
/// Converts `u8` to a `Extension` if it is known.
#[must_use]
pub fn from_u8(n: u8) -> Option<Extension> {
match n {
0x01 => Some(Extension::Text),
0xF9 => Some(Extension::Control),
0xFE => Some(Extension::Comment),
0xFF => Some(Extension::Application),
_ => None
_ => None,
}
}
}
Expand Down Expand Up @@ -151,7 +155,7 @@ pub struct Frame<'a> {
pub palette: Option<Vec<u8>>,
/// Buffer containing the image data.
/// Only indices unless configured differently.
pub buffer: Cow<'a, [u8]>
pub buffer: Cow<'a, [u8]>,
}

impl<'a> Default for Frame<'a> {
Expand All @@ -167,7 +171,7 @@ impl<'a> Default for Frame<'a> {
height: 0,
interlaced: false,
palette: None,
buffer: Cow::Borrowed(&[])
buffer: Cow::Borrowed(&[]),
}
}
}
Expand Down Expand Up @@ -212,7 +216,7 @@ impl Frame<'static> {
if pix[3] != 0 {
pix[3] = 0xFF;
} else {
transparent = Some([pix[0], pix[1], pix[2], pix[3]])
transparent = Some([pix[0], pix[1], pix[2], pix[3]]);
}
}

Expand Down Expand Up @@ -251,7 +255,7 @@ impl Frame<'static> {
palette: Some(palette),
transparent: transparent.map(|t| index_of(&t)),
..Frame::default()
}
};
}

/// Creates a frame from a palette and indexed pixels.
Expand Down Expand Up @@ -286,7 +290,7 @@ impl Frame<'static> {
Frame {
width,
height,
buffer: Cow::Owned(pixels.to_vec()),
buffer: Cow::Owned(pixels.clone()),
palette: None,
transparent,
..Frame::default()
Expand All @@ -304,6 +308,7 @@ impl Frame<'static> {
/// # Panics:
/// * If the length of pixels does not equal `width * height * 3`.
#[cfg(feature = "color_quant")]
#[must_use]
pub fn from_rgb(width: u16, height: u16, pixels: &[u8]) -> Frame<'static> {
Frame::from_rgb_speed(width, height, pixels, 1)
}
Expand All @@ -323,12 +328,13 @@ impl Frame<'static> {
/// * If the length of pixels does not equal `width * height * 3`.
/// * If `speed < 1` or `speed > 30`
#[cfg(feature = "color_quant")]
#[must_use]
pub fn from_rgb_speed(width: u16, height: u16, pixels: &[u8], speed: i32) -> Frame<'static> {
assert_eq!(width as usize * height as usize * 3, pixels.len(), "Too much or too little pixel data for the given width and height to create a GIF Frame");
let mut vec: Vec<u8> = Vec::new();
vec.try_reserve_exact(pixels.len() + width as usize * height as usize).expect("OOM");
for v in pixels.chunks_exact(3) {
vec.extend_from_slice(&[v[0], v[1], v[2], 0xFF])
vec.extend_from_slice(&[v[0], v[1], v[2], 0xFF]);
}
Frame::from_rgba_speed(width, height, &mut vec, speed)
}
Expand All @@ -342,5 +348,5 @@ impl Frame<'static> {
fn rgba_speed_avoid_panic_256_colors() {
let side = 16;
let pixel_data: Vec<u8> = (0..=255).map(|a| vec![a, a, a]).flatten().collect();
Frame::from_rgb(side, side, &pixel_data);
let _ = Frame::from_rgb(side, side, &pixel_data);
}
43 changes: 17 additions & 26 deletions src/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ pub enum Repeat {
/// Finite number of repetitions
Finite(u16),
/// Infinite number of repetitions
Infinite
Infinite,
}

/// Extension data.
Expand All @@ -104,33 +104,29 @@ pub enum ExtensionData {
/// Frame delay.
delay: u16,
/// Transparent index.
trns: u8
trns: u8,
},
/// Sets the number of repetitions
Repetitions(Repeat)
Repetitions(Repeat),
}

impl ExtensionData {
/// Constructor for control extension data.
///
/// `delay` is given in units of 10 ms.
pub fn new_control_ext(delay: u16, dispose: DisposalMethod,
#[must_use] pub fn new_control_ext(delay: u16, dispose: DisposalMethod,
needs_user_input: bool, trns: Option<u8>) -> ExtensionData {
let mut flags = 0;
let trns = match trns {
Some(trns) => {
flags |= 1;
trns as u8
trns
},
None => 0
};
flags |= u8::from(needs_user_input) << 1;
flags |= (dispose as u8) << 2;
ExtensionData::Control {
flags: flags,
delay: delay,
trns: trns
}
ExtensionData::Control { flags, delay, trns }
}
}

Expand Down Expand Up @@ -184,16 +180,12 @@ impl<W: Write> Encoder<W> {
}

fn write_frame_header(&mut self, frame: &Frame<'_>) -> Result<(), EncodingError> {
// TODO commented off to pass test in lib.rs
//if frame.delay > 0 || frame.transparent.is_some() {
self.write_extension(ExtensionData::new_control_ext(
frame.delay,
frame.dispose,
frame.needs_user_input,
frame.transparent

))?;
//}
self.write_extension(ExtensionData::new_control_ext(
frame.delay,
frame.dispose,
frame.needs_user_input,
frame.transparent,
))?;
let writer = self.w.as_mut().unwrap();
writer.write_le(Block::Image as u8)?;
writer.write_le(frame.left)?;
Expand Down Expand Up @@ -238,7 +230,7 @@ impl<W: Write> Encoder<W> {
// Write blocks. `chunks_exact` seems to be slightly faster
// than `chunks` according to both Rust docs and benchmark results.
let mut iter = data.chunks_exact(0xFF);
while let Some(full_block) = iter.next() {
for full_block in iter.by_ref() {
writer.write_le(0xFFu8)?;
writer.write_all(full_block)?;
}
Expand All @@ -260,7 +252,7 @@ impl<W: Write> Encoder<W> {
writer.write_all(&table[..num_colors * 3])?;
// Waste some space as of gif spec
for _ in 0..((2 << size) - num_colors) {
writer.write_all(&[0, 0, 0])?
writer.write_all(&[0, 0, 0])?;
}
Ok(())
}
Expand All @@ -273,7 +265,7 @@ impl<W: Write> Encoder<W> {
// 0 finite repetitions can only be achieved
// if the corresponting extension is not written
if let Repetitions(Repeat::Finite(0)) = extension {
return Ok(())
return Ok(());
}
let writer = self.w.as_mut().unwrap();
writer.write_le(Block::Extension as u8)?;
Expand Down Expand Up @@ -376,7 +368,7 @@ impl<W: Write> Encoder<W> {
fn lzw_encode(data: &[u8], buffer: &mut Vec<u8>) {
let min_code_size = match flag_size(1 + data.iter().copied().max().unwrap_or(0) as usize) + 1 {
1 => 2, // As per gif spec: The minimal code size has to be >= 2
n => n
n => n,
};
buffer.push(min_code_size);
let mut enc = LzwEncoder::new(BitOrder::Lsb, min_code_size);
Expand All @@ -401,11 +393,10 @@ pub struct Encoder<W: Write> {
global_palette: bool,
width: u16,
height: u16,
buffer: Vec<u8>
buffer: Vec<u8>,
}

impl<W: Write> Drop for Encoder<W> {

#[cfg(feature = "raii_no_panic")]
fn drop(&mut self) {
if self.w.is_some() {
Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ mod encoder;
pub use crate::common::{AnyExtension, Block, Extension, DisposalMethod, Frame};

pub use crate::reader::{StreamingDecoder, Decoded, DecodingError, DecodingFormatError};
/// StreamingDecoder configuration parameters
/// `StreamingDecoder` configuration parameters
pub use crate::reader::{ColorOutput, MemoryLimit, Extensions};
pub use crate::reader::{DecodeOptions, Decoder, Version};

Expand All @@ -140,7 +140,7 @@ fn round_trip() {
let mut encoder = Encoder::new(&mut data2, frame.width, frame.height, &palette).unwrap();
encoder.write_frame(frame).unwrap();
}
assert_eq!(&data[..], &data2[..])
assert_eq!(&data[..], &data2[..]);
}

macro_rules! insert_as_doc {
Expand Down
24 changes: 15 additions & 9 deletions src/reader/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ impl LzwReader {
}

pub fn decode_bytes(&mut self, lzw_data: &[u8], decode_buffer: &mut OutputBuffer<'_>) -> io::Result<(usize, usize)> {
let decoder = self.decoder.as_mut().ok_or_else(|| io::ErrorKind::Unsupported)?;
let decoder = self.decoder.as_mut().ok_or(io::ErrorKind::Unsupported)?;

let decode_buffer = match decode_buffer {
OutputBuffer::Slice(buf) => &mut **buf,
Expand All @@ -256,7 +256,7 @@ impl LzwReader {
let decoded = decoder.decode_bytes(lzw_data, decode_buffer);

match decoded.status {
Ok(LzwStatus::Done) | Ok(LzwStatus::Ok) => {},
Ok(LzwStatus::Done | LzwStatus::Ok) => {},
Ok(LzwStatus::NoProgress) => {
if self.check_for_end_code {
return Err(io::Error::new(io::ErrorKind::InvalidData, "No end code in lzw stream"));
Expand Down Expand Up @@ -316,6 +316,7 @@ pub enum OutputBuffer<'a> {

impl StreamingDecoder {
/// Creates a new streaming decoder
#[must_use]
pub fn new() -> StreamingDecoder {
let options = DecodeOptions::new();
Self::with_options(&options)
Expand Down Expand Up @@ -352,7 +353,7 @@ impl StreamingDecoder {
// NOTE: Do not change the function signature without double-checking the
// unsafe block!
let len = buf.len();
while buf.len() > 0 {
while !buf.is_empty() {
// This dead code is a compile-check for lifetimes that otherwise aren't checked
// due to the `mem::transmute` used later.
// Keep it in sync with the other call to `next_state`.
Expand All @@ -366,7 +367,7 @@ impl StreamingDecoder {
// if the state has already been set to `None`.
match self.next_state(buf, write_into) {
Ok((bytes, Decoded::Nothing)) => {
buf = &buf[bytes..]
buf = &buf[bytes..];
}
Ok((bytes, result)) => {
buf = &buf[bytes..];
Expand All @@ -393,6 +394,7 @@ impl StreamingDecoder {
}

/// Returns the data of the last extension that has been decoded.
#[must_use]
pub fn last_ext(&self) -> (AnyExtension, &[u8], bool) {
(self.ext.id, &self.ext.data, self.ext.is_block_end)
}
Expand All @@ -406,16 +408,19 @@ impl StreamingDecoder {
/// Current frame info as a ref.
#[inline(always)]
#[track_caller]
pub fn current_frame<'a>(&'a self) -> &'a Frame<'static> {
#[must_use]
pub fn current_frame(&self) -> &Frame<'static> {
self.current.as_ref().unwrap()
}

/// Width of the image
#[must_use]
pub fn width(&self) -> u16 {
self.width
}

/// Height of the image
#[must_use]
pub fn height(&self) -> u16 {
self.height
}
Expand All @@ -424,6 +429,7 @@ impl StreamingDecoder {
///
/// We suppose a minimum of `V87a` compatibility. This value will be reported until we have
/// read the version information in the magic header bytes.
#[must_use]
pub fn version(&self) -> Version {
self.version
}
Expand Down Expand Up @@ -476,7 +482,7 @@ impl StreamingDecoder {
U16(next) => goto!(U16Byte1(next, b)),
U16Byte1(next, value) => {
use self::U16Value::*;
let value = ((b as u16) << 8) | value as u16;
let value = (u16::from(b) << 8) | u16::from(value);
match (next, value) {
(ScreenWidth, width) => {
self.width = width;
Expand Down Expand Up @@ -539,7 +545,7 @@ impl StreamingDecoder {
let control_flags = b;
if control_flags & 1 != 0 {
// Set to Some(...), gets overwritten later
frame.transparent = Some(0)
frame.transparent = Some(0);
}
frame.needs_user_input =
control_flags & 0b10 != 0;
Expand All @@ -554,7 +560,7 @@ impl StreamingDecoder {
TransparentIdx => {
self.ext.data.push(b);
if let Some(ref mut idx) = self.current_frame_mut().transparent {
*idx = b
*idx = b;
}
goto!(SkipBlock(0))
}
Expand Down Expand Up @@ -777,7 +783,7 @@ impl StreamingDecoder {

fn add_frame(&mut self) {
if self.current.is_none() {
self.current = Some(Frame::default())
self.current = Some(Frame::default());
}
}
}
Expand Down
Loading

0 comments on commit a9a0e46

Please sign in to comment.