Skip to content

Commit

Permalink
refactor(farbfeld): use the built-in methods to convert the bytes bet…
Browse files Browse the repository at this point in the history
…ween different representations (#2071)
  • Loading branch information
0x61nas authored Dec 15, 2023
1 parent 3dcd4da commit d970bf7
Showing 1 changed file with 9 additions and 14 deletions.
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

0 comments on commit d970bf7

Please sign in to comment.