Skip to content

Commit

Permalink
Merge pull request #23 from MaxVerevkin/misc
Browse files Browse the repository at this point in the history
Remove a few allocations
  • Loading branch information
esposm03 authored Aug 12, 2024
2 parents b862d20 + 2671da7 commit f11edab
Showing 1 changed file with 10 additions and 11 deletions.
21 changes: 10 additions & 11 deletions src/parser.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use std::{
convert::TryInto,
fmt::{self, Debug, Formatter},
io::{Cursor, Error, ErrorKind, Read, Result as IoResult, Seek, SeekFrom},
mem::size_of,
};

#[derive(Debug, Clone, Eq, PartialEq)]
Expand Down Expand Up @@ -56,7 +54,7 @@ impl std::fmt::Display for Image {
}

fn parse_header(i: &mut impl Read) -> IoResult<(u32, u32)> {
i.tag(b"Xcur")?;
i.tag(*b"Xcur")?;
let header = i.u32_le()?;
let _version = i.u32_le()?;
let ntoc = i.u32_le()?;
Expand All @@ -77,10 +75,10 @@ fn parse_toc(i: &mut impl Read) -> IoResult<Toc> {
}

fn parse_img(i: &mut impl Read) -> IoResult<Image> {
i.tag(&[0x24, 0x00, 0x00, 0x00])?; // Header size
i.tag(&[0x02, 0x00, 0xfd, 0xff])?; // Type
i.tag([0x24, 0x00, 0x00, 0x00])?; // Header size
i.tag([0x02, 0x00, 0xfd, 0xff])?; // Type
let size = i.u32_le()?;
i.tag(&[0x01, 0x00, 0x00, 0x00])?; // Image version (1)
i.tag([0x01, 0x00, 0x00, 0x00])?; // Image version (1)
let width = i.u32_le()?;
let height = i.u32_le()?;
let xhot = i.u32_le()?;
Expand Down Expand Up @@ -164,7 +162,7 @@ pub fn parse_xcursor_stream<R: Read + Seek>(input: &mut R) -> IoResult<Vec<Image

trait StreamExt {
/// Parse a series of bytes, returning `None` if it doesn't exist.
fn tag(&mut self, tag: &[u8]) -> IoResult<()>;
fn tag(&mut self, tag: [u8; 4]) -> IoResult<()>;

/// Take a slice of bytes.
fn take_bytes(&mut self, len: usize) -> IoResult<Vec<u8>>;
Expand All @@ -174,8 +172,8 @@ trait StreamExt {
}

impl<R: Read> StreamExt for R {
fn tag(&mut self, tag: &[u8]) -> IoResult<()> {
let mut data = vec![0; tag.len()];
fn tag(&mut self, tag: [u8; 4]) -> IoResult<()> {
let mut data = [0u8; 4];
self.read_exact(&mut data)?;
if data != tag {
Err(Error::new(ErrorKind::Other, "Tag mismatch"))
Expand All @@ -191,8 +189,9 @@ impl<R: Read> StreamExt for R {
}

fn u32_le(&mut self) -> IoResult<u32> {
self.take_bytes(size_of::<u32>())
.map(|bytes| u32::from_le_bytes(bytes.as_slice().try_into().unwrap()))
let mut data = [0u8; 4];
self.read_exact(&mut data)?;
Ok(u32::from_le_bytes(data))
}
}

Expand Down

0 comments on commit f11edab

Please sign in to comment.