use std::io::{Cursor, Seek, Write};
use zip::write::SimpleFileOptions;
use zip::{ZipArchive, ZipWriter};
use crate::Result;
use crate::package::validation::validate_part_name;
use crate::package::{PackageError, PackageSource, PackageWriter};
pub struct ZipPackageWriter<W: Write + Seek> {
zip: ZipWriter<W>,
}
impl<W: Write + Seek + std::fmt::Debug> std::fmt::Debug for ZipPackageWriter<W> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ZipPackageWriter").finish()
}
}
impl<W: Write + Seek> ZipPackageWriter<W> {
pub fn new(writer: W) -> Self {
Self {
zip: ZipWriter::new(writer),
}
}
pub fn finish_into_inner(self) -> Result<W> {
self.zip
.finish()
.map_err(|_| crate::package::PackageError::MalformedArchive.into())
}
fn file_options() -> SimpleFileOptions {
SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated)
}
}
impl<W: Write + Seek> PackageWriter for ZipPackageWriter<W> {
fn write_part(&mut self, name: &str, contents: &[u8]) -> Result<()> {
validate_part_name(name)?;
self.zip
.start_file(name, Self::file_options())
.map_err(|_| PackageError::MalformedArchive)?;
self.zip.write_all(contents)?;
Ok(())
}
fn copy_part(&mut self, source: &dyn PackageSource, name: &str) -> Result<()> {
validate_part_name(name)?;
if let Some(raw) = source.raw_archive_bytes() {
let cursor = Cursor::new(raw);
if let Ok(mut archive) = ZipArchive::new(cursor)
&& let Ok(zip_file) = archive.by_name(name)
&& self.zip.raw_copy_file(zip_file).is_ok()
{
return Ok(());
}
}
let data = source
.read_part(name)?
.ok_or_else(|| PackageError::MissingRequiredPart(name.to_owned()))?;
self.write_part(name, &data)
}
fn finish(self) -> Result<()> {
self.finish_into_inner().map(|_| ())
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
use super::*;
use crate::package::memory_source::InMemoryPackageSource;
fn in_memory_writer() -> ZipPackageWriter<std::io::Cursor<Vec<u8>>> {
ZipPackageWriter::new(std::io::Cursor::new(Vec::new()))
}
#[test]
fn write_single_part_and_read_back() {
let mut w = in_memory_writer();
w.write_part("word/document.xml", b"<doc/>").unwrap();
let cursor = w.finish_into_inner().unwrap();
let src = crate::package::ZipPackageSource::from_bytes(cursor.into_inner()).unwrap();
let data = src.read_part("word/document.xml").unwrap().unwrap();
assert_eq!(data, b"<doc/>");
}
#[test]
fn copy_part_from_memory_source() {
let mut mem = InMemoryPackageSource::new();
mem.add_part("word/document.xml", b"<doc/>".to_vec());
let mut w = in_memory_writer();
w.copy_part(&mem, "word/document.xml").unwrap();
let cursor = w.finish_into_inner().unwrap();
let src = crate::package::ZipPackageSource::from_bytes(cursor.into_inner()).unwrap();
assert_eq!(
src.read_part("word/document.xml").unwrap().unwrap(),
b"<doc/>"
);
}
#[test]
fn copy_part_missing_returns_error() {
let mem = InMemoryPackageSource::new();
let mut w = in_memory_writer();
let err = w.copy_part(&mem, "word/document.xml").unwrap_err();
assert!(err.to_string().contains("word/document.xml"));
}
#[test]
fn write_part_rejects_traversal_name() {
let mut w = in_memory_writer();
let err = w.write_part("../secret.txt", b"oops").unwrap_err();
assert!(err.to_string().contains("unsupported ZIP entry"));
}
#[test]
fn finish_produces_valid_zip() {
let mut w = in_memory_writer();
w.write_part("[Content_Types].xml", b"<ct/>").unwrap();
w.write_part("_rels/.rels", b"<rels/>").unwrap();
w.write_part("word/document.xml", b"<body/>").unwrap();
let cursor = w.finish_into_inner().unwrap();
let src = crate::package::ZipPackageSource::from_bytes(cursor.into_inner()).unwrap();
let names = src.part_names().unwrap();
assert_eq!(names.len(), 3);
}
#[test]
fn raw_copy_produces_identical_content() {
let mut src_writer = in_memory_writer();
src_writer
.write_part("[Content_Types].xml", b"<ct/>")
.unwrap();
src_writer.write_part("_rels/.rels", b"<rels/>").unwrap();
src_writer
.write_part("word/document.xml", b"<doc/>")
.unwrap();
let src_bytes = src_writer.finish_into_inner().unwrap().into_inner();
let src = crate::package::ZipPackageSource::from_bytes(src_bytes).unwrap();
let mut dst_writer = in_memory_writer();
for name in src.part_names().unwrap() {
dst_writer.copy_part(&src, &name).unwrap();
}
let dst_bytes = dst_writer.finish_into_inner().unwrap().into_inner();
let dst = crate::package::ZipPackageSource::from_bytes(dst_bytes).unwrap();
for name in src.part_names().unwrap() {
let original = src.read_part(&name).unwrap().unwrap();
let copied = dst.read_part(&name).unwrap().unwrap();
assert_eq!(
original, copied,
"part {name} content changed after raw copy"
);
}
}
}