Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

PSD: avoid cloning layer data when padding and presize the output buffer (#3687) (#3707)

Valentin Klein7893a6e04d71
diff --git a/crates/psd/src/file.rs b/crates/psd/src/file.rs
index 3c621bb25..330940e7a 100644
--- a/crates/psd/src/file.rs
+++ b/crates/psd/src/file.rs
@@ -137,7 +137,11 @@ impl PsdFile {
pub fn to_bytes(&self) -> Result<Vec<u8>> {
let v = self.header.version;
let psb = v.is_psb();
+ // Reserve the pixel data up front: appending it to an empty Vec reallocates and copies
+ // repeatedly. Everything else (headers, resources, records) is small by comparison.
+ let hint = self.layer_info.as_ref().map_or(0, LayerInfo::channel_data_len).saturating_add(self.image_data.data.len());
let mut out = Vec::new();
+ out.try_reserve(hint).map_err(|_| PsdError::LimitExceeded("not enough memory to serialize the file"))?;
self.header.write(&mut out);
out.put_len(self.color_mode_data.len() as u64, false)?;
out.put(&self.color_mode_data);
diff --git a/crates/psd/src/layer.rs b/crates/psd/src/layer.rs
index cee675826..5450ed7e6 100644
--- a/crates/psd/src/layer.rs
+++ b/crates/psd/src/layer.rs
@@ -684,15 +684,25 @@ impl LayerInfo {
/// block in 4-byte units (psd-tools) misread the blocks after a body that
/// is only padded to even.
pub fn pad_to(&mut self, version: Version, align: u64) -> Result<()> {
+ self.padding = Some(vec![0; self.pad_len(version, align)?]);
+ Ok(())
+ }
+
+ /// Number of zero bytes [`Self::pad_to`] would set, without touching `self`.
+ pub(crate) fn pad_len(&self, version: Version, align: u64) -> Result<usize> {
let align = align.max(1);
let len = self.unpadded_len(version)?;
- self.padding = Some(vec![0; ((align - len % align) % align) as usize]);
- Ok(())
+ Ok(((align - len % align) % align) as usize)
}
- /// Serializes the body (without a length field).
- pub(crate) fn write_body(&self, out: &mut Vec<u8>, version: Version) -> Result<()> {
- let start = out.len();
+ /// Bytes of channel data and their compression fields: the part of the body worth reserving up
+ /// front (the records are small next to the pixels). Saturates instead of overflowing.
+ pub(crate) fn channel_data_len(&self) -> usize {
+ self.layers.iter().flat_map(|l| &l.channels).filter(|c| c.compression.is_some()).fold(0usize, |n, c| n.saturating_add(2).saturating_add(c.data.len()))
+ }
+
+ /// Serializes the body without any trailing padding (the padding field is ignored).
+ pub(crate) fn write_unpadded(&self, out: &mut Vec<u8>, version: Version) -> Result<()> {
let n = i16::try_from(self.layers.len()).map_err(|_| PsdError::LimitExceeded("more than 32767 layers"))?;
out.put_i16(if self.merged_alpha { -n } else { n });
for l in &self.layers {
@@ -706,6 +716,13 @@ impl LayerInfo {
}
}
}
+ Ok(())
+ }
+
+ /// Serializes the body (without a length field).
+ pub(crate) fn write_body(&self, out: &mut Vec<u8>, version: Version) -> Result<()> {
+ let start = out.len();
+ self.write_unpadded(out, version)?;
match &self.padding {
Some(p) => out.put(p),
None => {
@@ -1022,6 +1039,37 @@ mod tests {
assert_eq!(info.layers[0].decode_channel(0, 8, Version::Psd).unwrap(), Vec::<u8>::new());
}
+ /// Padding without cloning the layers writes the same bytes as `pad_to` on a clone, and the
+ /// channel data length hint is exact.
+ #[test]
+ fn unpadded_write_matches_pad_to_on_a_clone() {
+ use crate::{ColorMode, Compression, testgen};
+ for version in [Version::Psd, Version::Psb] {
+ for depth in [8u16, 16, 32] {
+ for compression in [Compression::Raw, Compression::Rle] {
+ let file = testgen::layered(version, ColorMode::Rgb, depth, compression);
+ let mut info = file.layer_info.clone().unwrap();
+ for align in [1u64, 2, 4, 8] {
+ let mut cloned = info.clone();
+ cloned.pad_to(version, align).unwrap();
+ let mut want = Vec::new();
+ cloned.write_body(&mut want, version).unwrap();
+ let pad = info.pad_len(version, align).unwrap();
+ let mut got = Vec::new();
+ info.write_unpadded(&mut got, version).unwrap();
+ assert!(got.len() >= info.channel_data_len());
+ got.resize(got.len() + pad, 0);
+ assert_eq!(got, want, "{version:?} {depth} {compression:?} align {align}");
+ }
+ info.padding = Some(vec![7, 7]);
+ let mut with_padding = Vec::new();
+ info.write_body(&mut with_padding, version).unwrap();
+ assert!(with_padding.ends_with(&[7, 7]));
+ }
+ }
+ }
+ }
+
#[test]
fn nondefault_padding_kept() {
let info = LayerInfo { padding: Some(vec![0, 0]), ..Default::default() };
diff --git a/crates/psd/src/tiff.rs b/crates/psd/src/tiff.rs
index 0d8f36888..7c8b1940d 100644
--- a/crates/psd/src/tiff.rs
+++ b/crates/psd/src/tiff.rs
@@ -155,10 +155,12 @@ impl ImageSourceData {
let version = self.version;
let mut blocks = Vec::with_capacity(self.global_blocks.len() + 2);
if let Some(info) = &self.layer_info {
- let mut info = info.clone();
- info.pad_to(version, 4)?;
+ // Pad to 4 without cloning the layers (and all their pixel data) just to set `padding`.
+ let pad = info.pad_len(version, 4)?;
let mut data = Vec::new();
- info.write_body(&mut data, version)?;
+ data.try_reserve(info.channel_data_len().saturating_add(pad)).map_err(|_| PsdError::LimitExceeded("not enough memory for the layer data"))?;
+ info.write_unpadded(&mut data, version)?;
+ data.resize(data.len() + pad, 0);
blocks.push(padded_block(self.layer_info_key, data));
}
if let Some(m) = &self.global_layer_mask {