Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(farbfeld): use the built-in methods to convert the bytes between different representations #2071

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 9 additions & 14 deletions src/codecs/farbfeld.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,10 @@
//! # Related Links
//! * <https://tools.suckless.org/farbfeld/> - the farbfeld specification

use std::convert::TryFrom;
use std::convert::{TryFrom, TryInto};
use std::i64;
use std::io::{self, Read, Seek, SeekFrom, Write};

use byteorder::{BigEndian, ByteOrder, NativeEndian};

use crate::color::ColorType;
use crate::error::{
DecodingError, ImageError, ImageResult, UnsupportedError, UnsupportedErrorKind,
Expand All @@ -45,7 +43,7 @@ impl<R: Read> FarbfeldReader<R> {
from.read_exact(&mut buf).map_err(|err| {
ImageError::Decoding(DecodingError::new(ImageFormat::Farbfeld.into(), err))
})?;
Ok(BigEndian::read_u32(&buf))
Ok(u32::from_be_bytes(buf))
}

let mut magic = [0u8; 8];
Expand Down Expand Up @@ -169,10 +167,11 @@ impl<R: Read + Seek> Seek for FarbfeldReader<R> {
}
}

fn consume_channel<R: Read>(from: &mut R, to: &mut [u8]) -> io::Result<()> {
fn consume_channel<R: Read>(from: &mut R, mut to: &mut [u8]) -> io::Result<()> {
let mut ibuf = [0u8; 2];
from.read_exact(&mut ibuf)?;
NativeEndian::write_u16(to, BigEndian::read_u16(&ibuf));
to.write_all(&u16::from_be_bytes(ibuf).to_ne_bytes())?;

Ok(())
}

Expand Down Expand Up @@ -274,16 +273,12 @@ impl<W: Write> FarbfeldEncoder<W> {
fn encode_impl(mut self, data: &[u8], width: u32, height: u32) -> io::Result<()> {
self.w.write_all(b"farbfeld")?;

let mut buf = [0u8; 4];
BigEndian::write_u32(&mut buf, width);
self.w.write_all(&buf)?;

BigEndian::write_u32(&mut buf, height);
self.w.write_all(&buf)?;
self.w.write_all(&width.to_be_bytes())?;
self.w.write_all(&height.to_be_bytes())?;

for channel in data.chunks_exact(2) {
BigEndian::write_u16(&mut buf, NativeEndian::read_u16(channel));
self.w.write_all(&buf[..2])?;
self.w
.write_all(&u16::from_ne_bytes(channel.try_into().unwrap()).to_be_bytes())?;
}

Ok(())
Expand Down
Loading