Skip to content

Commit

Permalink
Formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
kornelski committed Jan 10, 2024
1 parent a9a0e46 commit df83d2d
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 72 deletions.
26 changes: 13 additions & 13 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
//! # GIF en- and decoding library [![Build Status](https://github.com/image-rs/image-gif/workflows/Rust%20CI/badge.svg)](https://github.com/image-rs/image-gif/actions)
//!
//!
//! GIF en- and decoder written in Rust ([API Documentation](https://docs.rs/gif)).
//!
//!
//! # GIF encoding and decoding library
//!
//!
//! This library provides all functions necessary to de- and encode GIF files.
//!
//!
//! ## High level interface
//!
//!
//! The high level interface consists of the two types
//! [`Encoder`](struct.Encoder.html) and [`Decoder`](struct.Decoder.html).
//!
//!
//! ### Decoding GIF files
//!
//!
//! ```rust
//! // Open the file
//! use std::fs::File;
Expand All @@ -26,18 +26,18 @@
//! // Process every frame
//! }
//! ```
//!
//!
//!
//!
//!
//!
//! ### Encoding GIF files
//!
//! The encoder can be used so save simple computer generated images:
//!
//!
//! ```rust
//! use gif::{Frame, Encoder, Repeat};
//! use std::fs::File;
//! use std::borrow::Cow;
//!
//!
//! let color_map = &[0xFF, 0xFF, 0xFF, 0, 0, 0];
//! let (width, height) = (6, 6);
//! let mut beacon_states = [[
Expand Down Expand Up @@ -73,7 +73,7 @@
//! ```rust
//! # #[cfg(feature = "color_quant")] {
//! use std::fs::File;
//!
//!
//! // Get pixel data from some source
//! let mut pixels: Vec<u8> = vec![0; 30_000];
//! // Create frame from data
Expand Down
59 changes: 28 additions & 31 deletions src/reader/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub const PLTE_CHANNELS: usize = 3;
/// An error returned in the case of the image not being formatted properly.
#[derive(Debug)]
pub struct DecodingFormatError {
underlying: Box<dyn error::Error + Send + Sync + 'static>
underlying: Box<dyn error::Error + Send + Sync + 'static>,
}

impl fmt::Display for DecodingFormatError {
Expand Down Expand Up @@ -107,7 +107,7 @@ pub enum Extensions {
Save,
/// Skips the data of unknown extensions
/// and extracts the data from known ones
Skip
Skip,
}

#[derive(Debug, Copy, Clone)]
Expand Down Expand Up @@ -171,7 +171,7 @@ enum State {
/// Keeps LZW compressed
CopySubBlock(usize),
FrameDecoded,
Trailer
Trailer,
}
use self::State::*;

Expand Down Expand Up @@ -224,9 +224,7 @@ impl LzwReader {
pub fn reset(&mut self, min_code_size: u8) -> Result<(), DecodingError> {
// LZW spec: max 12 bits per code
if min_code_size > 11 {
return Err(DecodingError::format(
"invalid minimal code size"
))
return Err(DecodingError::format("invalid minimal code size"));
}

// The decoder can be reused if the code size stayed the same
Expand Down Expand Up @@ -340,16 +338,19 @@ impl StreamingDecoder {
data: Vec::with_capacity(256), // 0xFF + 1 byte length
is_block_end: true,
},
current: None
current: None,
}
}
/// Updates the internal state of the decoder.

/// Updates the internal state of the decoder.
///
/// Returns the number of bytes consumed from the input buffer
/// Returns the number of bytes consumed from the input buffer
/// and the last decoding result.
pub fn update<'a>(&'a mut self, mut buf: &[u8], write_into: &mut OutputBuffer<'_>)
-> Result<(usize, Decoded<'a>), DecodingError> {
pub fn update<'a>(
&'a mut self,
mut buf: &[u8],
write_into: &mut OutputBuffer<'_>,
) -> Result<(usize, Decoded<'a>), DecodingError> {
// NOTE: Do not change the function signature without double-checking the
// unsafe block!
let len = buf.len();
Expand Down Expand Up @@ -387,24 +388,24 @@ impl StreamingDecoder {
}
))
}
Err(err) => return Err(err)
Err(err) => return Err(err),
}
}
Ok((len-buf.len(), Decoded::Nothing))
Ok((len - buf.len(), Decoded::Nothing))
}

/// 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)
}

#[inline(always)]
/// Current frame info as a mutable ref.
pub fn current_frame_mut(&mut self) -> &mut Frame<'static> {
self.current.as_mut().unwrap()
}

/// Current frame info as a ref.
#[inline(always)]
#[track_caller]
Expand Down Expand Up @@ -560,14 +561,14 @@ 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))
}
ImageFlags => {
let local_table = (b & 0b1000_0000) != 0;
let interlaced = (b & 0b0100_0000) != 0;
let table_size = b & 0b0000_0111;
let interlaced = (b & 0b0100_0000) != 0;
let table_size = b & 0b0000_0111;
let check_frame_consistency = self.check_frame_consistency;
let (width, height) = (self.width, self.height);

Expand All @@ -592,8 +593,8 @@ impl StreamingDecoder {
} else {
goto!(Byte(CodeSize))
}
},
CodeSize => goto!(LzwInit(b))
}
CodeSize => goto!(LzwInit(b)),
}
}
GlobalPalette(left) => {
Expand Down Expand Up @@ -633,7 +634,7 @@ impl StreamingDecoder {
}
}
}
}
},
BlockEnd(terminator) => {
if terminator == 0 {
if b == Block::Trailer as u8 {
Expand Down Expand Up @@ -764,23 +765,19 @@ impl StreamingDecoder {
self.current = None;
goto!(BlockEnd(b), emit Decoded::DataEnd)
}
Trailer => {
Ok((0, Decoded::Trailer))
}
Trailer => Ok((0, Decoded::Trailer)),
}
}

fn read_control_extension(&mut self, b: u8) -> Result<State, DecodingError> {
self.add_frame();
self.ext.data.push(b);
if b != 4 {
return Err(DecodingError::format(
"control extension has wrong length"
))
return Err(DecodingError::format("control extension has wrong length"));
}
Ok(Byte(ByteValue::ControlFlags))
}

fn add_frame(&mut self) {
if self.current.is_none() {
self.current = Some(Frame::default());
Expand Down
44 changes: 21 additions & 23 deletions src/reader/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ impl DecodeOptions {
struct ReadDecoder<R: Read> {
reader: io::BufReader<R>,
decoder: StreamingDecoder,
at_eof: bool
at_eof: bool,
}

impl<R: Read> ReadDecoder<R> {
Expand Down Expand Up @@ -264,7 +264,7 @@ impl<R> Decoder<R> where R: Read {
current_frame_data_type: FrameDataType::Pixels,
}
}

fn init(mut self) -> Result<Self, DecodingError> {
loop {
match self.decoder.decode_next(&mut OutputBuffer::None)? {
Expand Down Expand Up @@ -297,7 +297,7 @@ impl<R> Decoder<R> where R: Read {
}
Ok(self)
}

/// Returns the next frame info
pub fn next_frame_info(&mut self) -> Result<Option<&Frame<'static>>, DecodingError> {
loop {
Expand All @@ -307,14 +307,13 @@ impl<R> Decoder<R> where R: Read {
self.current_frame_data_type = frame_data_type;
if frame.palette.is_none() && self.global_palette.is_none() {
return Err(DecodingError::format(
"no color table available for current frame"
))
"no color table available for current frame",
));
}
break
},
break;
}
Some(_) => (),
None => return Ok(None)

None => return Ok(None),
}
}
Ok(Some(&self.current_frame))
Expand Down Expand Up @@ -372,13 +371,13 @@ impl<R> Decoder<R> where R: Read {
// Handle a too-small buffer without panicking
let line = buf.get_mut(start .. start + width).ok_or_else(|| DecodingError::format("buffer too small"))?;
if !self.fill_buffer(line)? {
return Err(DecodingError::format("image truncated"))
return Err(DecodingError::format("image truncated"));
}
}
} else {
let buf = buf.get_mut(..self.buffer_size()).ok_or_else(|| DecodingError::format("buffer too small"))?;
if !self.fill_buffer(buf)? {
return Err(DecodingError::format("image truncated"))
return Err(DecodingError::format("image truncated"));
}
};
Ok(())
Expand Down Expand Up @@ -452,41 +451,40 @@ impl<R> Decoder<R> where R: Read {
}
}
if buf.is_empty() {
return Ok(true)
return Ok(true);
}
},
}
Some(_) => return Ok(false), // make sure that no important result is missed
None => return Ok(false)

None => return Ok(false),
}
}
}

/// Output buffer size
pub fn buffer_size(&self) -> usize {
self.line_length() * self.current_frame.height as usize
}

/// Line length of the current frame
pub fn line_length(&self) -> usize {
use self::ColorOutput::*;
match self.color_output {
RGBA => self.current_frame.width as usize * N_CHANNELS,
Indexed => self.current_frame.width as usize
Indexed => self.current_frame.width as usize,
}
}

/// Returns the color palette relevant for the current (next) frame
pub fn palette(&self) -> Result<&[u8], DecodingError> {
// TODO prevent planic
Ok(match self.current_frame.palette {
Some(ref table) => table,
None => self.global_palette.as_ref().ok_or(DecodingError::format(
"no color table available for current frame"
"no color table available for current frame",
))?,
})
}

/// The global color palette
pub fn global_palette(&self) -> Option<&[u8]> {
self.global_palette.as_deref()
Expand All @@ -511,7 +509,7 @@ impl<R> Decoder<R> where R: Read {
struct InterlaceIterator {
len: usize,
next: usize,
pass: usize
pass: usize,
}

impl iter::Iterator for InterlaceIterator {
Expand Down Expand Up @@ -540,7 +538,7 @@ mod test {
use std::fs::File;

use super::{Decoder, InterlaceIterator};

#[test]
fn test_simple_indexed() {
let mut decoder = Decoder::new(File::open("tests/samples/sample_1.gif").unwrap()).unwrap();
Expand Down
6 changes: 1 addition & 5 deletions src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,13 @@ impl<W: io::Write + ?Sized> WriteBytesExt<u8> for W {
#[inline]
fn write_le(&mut self, n: u8) -> io::Result<()> {
self.write_all(&[n])

}
}

impl<W: io::Write + ?Sized> WriteBytesExt<u16> for W {
#[inline]
fn write_le(&mut self, n: u16) -> io::Result<()> {
self.write_all(&[n as u8, (n>>8) as u8])

self.write_all(&[n as u8, (n >> 8) as u8])
}
}

Expand All @@ -35,7 +33,6 @@ impl<W: io::Write + ?Sized> WriteBytesExt<u32> for W {
fn write_le(&mut self, n: u32) -> io::Result<()> {
self.write_le(n as u16)?;
self.write_le((n >> 16) as u16)

}
}

Expand All @@ -44,6 +41,5 @@ impl<W: io::Write + ?Sized> WriteBytesExt<u64> for W {
fn write_le(&mut self, n: u64) -> io::Result<()> {
self.write_le(n as u32)?;
self.write_le((n >> 32) as u32)

}
}

0 comments on commit df83d2d

Please sign in to comment.