From dfc989e7b1636b5ea73226fd2a3f13d8747f78a6 Mon Sep 17 00:00:00 2001 From: Lukasz Anforowicz Date: Tue, 14 Nov 2023 18:59:23 +0000 Subject: [PATCH] Reuse `encoder::write_chunk` from `test_utils::write_chunk`. --- src/test_utils.rs | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/src/test_utils.rs b/src/test_utils.rs index 0e14e74f..ab750e74 100644 --- a/src/test_utils.rs +++ b/src/test_utils.rs @@ -1,6 +1,13 @@ //! A set of test utilities. +//! +//! There is some overlap between the `test_utils::write_...` functions and the code in the +//! `encoder.rs` module. The main difference is that the `test_utils` function perform no +//! validation - this allows testcases to construct arbitrary, potentially invalid PNG inputs. +//! OTOH, we should try to reuse code whenever possible - e.g. `test_utils::write_chunk` is just a +//! thin wrapper around `encoder::write_chunk`. use byteorder::WriteBytesExt; +use std::convert::TryInto; use std::io::Write; /// Generates a store-only, non-compressed image: @@ -37,20 +44,12 @@ pub fn write_png_sig(w: &mut impl Write) { /// Writes an arbitrary PNG chunk. pub fn write_chunk(w: &mut impl Write, chunk_type: &[u8], data: &[u8]) { - assert_eq!(chunk_type.len(), 4); - let crc = { - let input = chunk_type - .iter() - .copied() - .chain(data.iter().copied()) - .collect::>(); - crc32fast::hash(input.as_slice()) - }; - w.write_u32::(data.len() as u32) - .unwrap(); - w.write_all(chunk_type).unwrap(); - w.write_all(data).unwrap(); - w.write_u32::(crc).unwrap(); + let chunk_type = crate::chunk::ChunkType( + chunk_type + .try_into() + .expect("`chunk_type` needs to be 4 bytes long"), + ); + crate::encoder::write_chunk(w, chunk_type, data).unwrap(); } /// Writes an IHDR chunk that indicates a non-interlaced RGBA8 that uses the same height and