Skip to content

Commit 596ceab

Browse files
authored
Merge pull request #2797 from mstoeckl/pnm-reduce-alloc
pnm: Avoid allocations while parsing binary data
2 parents cdcc830 + 956bded commit 596ceab

3 files changed

Lines changed: 74 additions & 46 deletions

File tree

‎src/codecs/pnm/decoder.rs‎

Lines changed: 74 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ use crate::color::{ColorType, ExtendedColorType};
1111
use crate::error::{
1212
DecodingError, ImageError, ImageResult, UnsupportedError, UnsupportedErrorKind,
1313
};
14-
use crate::io::ReadExt;
1514
use crate::{utils, ImageDecoder, ImageFormat};
1615

1716
/// All errors that can occur when attempting to parse a PNM
@@ -239,10 +238,13 @@ trait Sample {
239238
fn sample_size() -> u32 {
240239
size_of::<Self::Representation>() as u32
241240
}
242-
fn bytelen(width: u32, height: u32, samples: u32) -> ImageResult<usize> {
243-
Ok((width * height * samples * Self::sample_size()) as usize)
244-
}
245-
fn from_bytes(bytes: &[u8], row_size: usize, output_buf: &mut [u8]) -> ImageResult<()>;
241+
fn from_bytes(
242+
reader: &mut dyn Read,
243+
output_buf: &mut [u8],
244+
width: u32,
245+
height: u32,
246+
components: u32,
247+
) -> ImageResult<()>;
246248
fn from_ascii(reader: &mut dyn Read, output_buf: &mut [u8]) -> ImageResult<()>;
247249
}
248250

@@ -651,27 +653,16 @@ impl<R: Read> PnmDecoder<R> {
651653
fn read_samples<S: Sample>(&mut self, components: u32, buf: &mut [u8]) -> ImageResult<()> {
652654
match self.subtype().sample_encoding() {
653655
SampleEncoding::Binary => {
654-
let width = self.header.width();
655-
let height = self.header.height();
656-
let bytecount = S::bytelen(width, height, components)?;
657-
658-
let mut bytes = vec![];
659-
self.reader.read_exact_vec(&mut bytes, bytecount)?;
660-
661-
let width: usize = width
662-
.try_into()
663-
.map_err(|_| DecoderError::Overflow(ErrorDataSource::Sample))?;
664-
let components: usize = components
665-
.try_into()
666-
.map_err(|_| DecoderError::Overflow(ErrorDataSource::Sample))?;
667-
let row_size = width
668-
.checked_mul(components)
669-
.ok_or(DecoderError::Overflow(ErrorDataSource::Sample))?;
670-
671-
S::from_bytes(&bytes, row_size, buf)?;
656+
S::from_bytes(
657+
&mut self.reader,
658+
buf,
659+
self.header.width(),
660+
self.header.height(),
661+
components,
662+
)?;
672663
}
673664
SampleEncoding::Ascii => {
674-
self.read_ascii::<S>(buf)?;
665+
S::from_ascii(&mut self.reader, buf)?;
675666
}
676667
}
677668

@@ -697,10 +688,6 @@ impl<R: Read> PnmDecoder<R> {
697688
Ok(())
698689
}
699690

700-
fn read_ascii<Basic: Sample>(&mut self, output_buf: &mut [u8]) -> ImageResult<()> {
701-
Basic::from_ascii(&mut self.reader, output_buf)
702-
}
703-
704691
/// Get the pnm subtype, depending on the magic constant contained in the header
705692
pub fn subtype(&self) -> PnmSubtype {
706693
self.header.subtype()
@@ -741,9 +728,14 @@ fn read_separated_ascii<T: TryFrom<u16>>(reader: &mut dyn Read) -> ImageResult<T
741728

742729
impl Sample for U8 {
743730
type Representation = u8;
744-
745-
fn from_bytes(bytes: &[u8], _row_size: usize, output_buf: &mut [u8]) -> ImageResult<()> {
746-
output_buf.copy_from_slice(bytes);
731+
fn from_bytes(
732+
reader: &mut dyn Read,
733+
output_buf: &mut [u8],
734+
_width: u32,
735+
_height: u32,
736+
_components: u32,
737+
) -> ImageResult<()> {
738+
reader.read_exact(output_buf)?;
747739
Ok(())
748740
}
749741

@@ -758,8 +750,14 @@ impl Sample for U8 {
758750
impl Sample for U16 {
759751
type Representation = u16;
760752

761-
fn from_bytes(bytes: &[u8], _row_size: usize, output_buf: &mut [u8]) -> ImageResult<()> {
762-
output_buf.copy_from_slice(bytes);
753+
fn from_bytes(
754+
reader: &mut dyn Read,
755+
output_buf: &mut [u8],
756+
_width: u32,
757+
_height: u32,
758+
_components: u32,
759+
) -> ImageResult<()> {
760+
reader.read_exact(output_buf)?;
763761
for chunk in output_buf.as_chunks_mut::<2>().0.iter_mut() {
764762
let v = u16::from_be_bytes(*chunk);
765763
chunk.copy_from_slice(&v.to_ne_bytes());
@@ -782,18 +780,42 @@ impl Sample for U16 {
782780
impl Sample for PbmBit {
783781
type Representation = u8;
784782

785-
fn bytelen(width: u32, height: u32, samples: u32) -> ImageResult<usize> {
786-
let count = width * samples;
787-
let linelen = (count / 8) + u32::from(!count.is_multiple_of(8));
788-
Ok((linelen * height) as usize)
789-
}
790-
791-
fn from_bytes(bytes: &[u8], row_size: usize, output_buf: &mut [u8]) -> ImageResult<()> {
792-
let mut expanded = utils::expand_bits(1, row_size.try_into().unwrap(), bytes);
793-
for b in &mut expanded {
794-
*b = !*b;
783+
fn from_bytes(
784+
reader: &mut dyn Read,
785+
output_buf: &mut [u8],
786+
width: u32,
787+
height: u32,
788+
components: u32,
789+
) -> ImageResult<()> {
790+
assert!(components == 1);
791+
792+
let width: usize = width
793+
.try_into()
794+
.map_err(|_| DecoderError::Overflow(ErrorDataSource::Sample))?;
795+
let height: usize = height
796+
.try_into()
797+
.map_err(|_| DecoderError::Overflow(ErrorDataSource::Sample))?;
798+
assert!(width.checked_mul(height) == Some(output_buf.len()));
799+
800+
let linelen = width.div_ceil(8);
801+
let bytecount = height
802+
.checked_mul(linelen)
803+
.filter(|l| *l <= output_buf.len())
804+
.expect("PBM packed data is never longer than unpacked");
805+
806+
reader.read_exact(&mut output_buf[..bytecount])?;
807+
808+
// Expand the PBM data in place. This can be done byte by byte with a single
809+
// backwards pass over the image. At all times, the position being read
810+
// from will not be after the position being written to, so no data is lost.
811+
812+
for y in (0..height).rev() {
813+
for x in (0..width).rev() {
814+
let shift = 7 - (x % 8);
815+
let v = (output_buf[y * linelen + x / 8] >> shift) & 0x1;
816+
output_buf[y * width + x] = 1 - v;
817+
}
795818
}
796-
output_buf.copy_from_slice(&expanded);
797819
Ok(())
798820
}
799821

@@ -823,8 +845,14 @@ impl Sample for PbmBit {
823845
impl Sample for BWBit {
824846
type Representation = u8;
825847

826-
fn from_bytes(bytes: &[u8], row_size: usize, output_buf: &mut [u8]) -> ImageResult<()> {
827-
U8::from_bytes(bytes, row_size, output_buf)?;
848+
fn from_bytes(
849+
reader: &mut dyn Read,
850+
output_buf: &mut [u8],
851+
width: u32,
852+
height: u32,
853+
components: u32,
854+
) -> ImageResult<()> {
855+
U8::from_bytes(reader, output_buf, width, height, components)?;
828856
if let Some(val) = output_buf.iter().find(|&val| *val > 1) {
829857
return Err(DecoderError::SampleOutOfBounds(*val).into());
830858
}

‎tests/images/pbm/images/narrow.pbm‎

16 Bytes
Binary file not shown.
73 Bytes
Loading

0 commit comments

Comments
 (0)