use std::io::Write;
const LOCAL_HEADER_SIG: u32 = 0x0403_4b50;
const CENTRAL_HEADER_SIG: u32 = 0x0201_4b50;
const END_OF_CENTRAL_DIR_SIG: u32 = 0x0605_4b50;
const VERSION_NEEDED: u16 = 20;
const METHOD_STORED: u16 = 0;
const METHOD_DEFLATE: u16 = 8;
const DOS_DATE: u16 = (1 << 5) | 1;
const DOS_TIME: u16 = 0;
const FLAG_UTF8: u16 = 1 << 11;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Compression {
Stored,
Deflated,
}
struct Entry {
name: String,
crc: u32,
compressed: u32,
size: u32,
method: u16,
offset: u32,
}
#[derive(Default)]
pub(crate) struct ZipWriter {
out: Vec<u8>,
entries: Vec<Entry>,
}
impl ZipWriter {
pub(crate) fn add(&mut self, name: &str, data: &[u8], compression: Compression) {
let (method, body) = match compression {
Compression::Stored => (METHOD_STORED, data.to_vec()),
Compression::Deflated => (METHOD_DEFLATE, deflate(data)),
};
let entry = Entry {
name: name.to_string(),
crc: crc32fast::hash(data),
compressed: u32::try_from(body.len()).expect("entry smaller than 4 GB"),
size: u32::try_from(data.len()).expect("entry smaller than 4 GB"),
method,
offset: u32::try_from(self.out.len()).expect("archive smaller than 4 GB"),
};
let out = &mut self.out;
put32(out, LOCAL_HEADER_SIG);
put16(out, VERSION_NEEDED);
write_common(out, &entry);
put16(out, 0); out.extend_from_slice(entry.name.as_bytes());
out.extend_from_slice(&body);
self.entries.push(entry);
}
pub(crate) fn finish(mut self) -> Vec<u8> {
let start = u32::try_from(self.out.len()).expect("archive smaller than 4 GB");
let out = &mut self.out;
for entry in &self.entries {
put32(out, CENTRAL_HEADER_SIG);
put16(out, VERSION_NEEDED); put16(out, VERSION_NEEDED);
write_common(out, entry);
put16(out, 0); put16(out, 0); put16(out, 0); put16(out, 0); put32(out, 0); put32(out, entry.offset);
out.extend_from_slice(entry.name.as_bytes());
}
let size = u32::try_from(out.len()).expect("archive smaller than 4 GB") - start;
let count = u16::try_from(self.entries.len()).expect("fewer than 65536 entries");
put32(out, END_OF_CENTRAL_DIR_SIG);
put16(out, 0); put16(out, 0); put16(out, count);
put16(out, count);
put32(out, size);
put32(out, start);
put16(out, 0); self.out
}
}
fn write_common(out: &mut Vec<u8>, entry: &Entry) {
let flags = if entry.name.is_ascii() { 0 } else { FLAG_UTF8 };
put16(out, flags);
put16(out, entry.method);
put16(out, DOS_TIME);
put16(out, DOS_DATE);
put32(out, entry.crc);
put32(out, entry.compressed);
put32(out, entry.size);
put16(
out,
u16::try_from(entry.name.len()).expect("file name shorter than 64 KB"),
);
}
fn deflate(data: &[u8]) -> Vec<u8> {
let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(data).expect("writing to memory");
encoder.finish().expect("writing to memory")
}
fn put16(out: &mut Vec<u8>, value: u16) {
out.extend_from_slice(&value.to_le_bytes());
}
fn put32(out: &mut Vec<u8>, value: u32) {
out.extend_from_slice(&value.to_le_bytes());
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
#[test]
fn entries_can_be_read_back() {
let mut zip = ZipWriter::default();
let text = "<a>hello</a>".repeat(50);
zip.add("word/document.xml", text.as_bytes(), Compression::Deflated);
zip.add("media/x.png", b"\x89PNG data", Compression::Stored);
let bytes = zip.finish();
let end = bytes.len() - 22;
assert_eq!(&bytes[end..end + 4], &END_OF_CENTRAL_DIR_SIG.to_le_bytes());
assert_eq!(u16::from_le_bytes([bytes[end + 10], bytes[end + 11]]), 2);
let name_len = usize::from(u16::from_le_bytes([bytes[26], bytes[27]]));
let size = u32::from_le_bytes(bytes[18..22].try_into().unwrap()) as usize;
let data = &bytes[30 + name_len..30 + name_len + size];
let mut inflated = String::new();
flate2::read::DeflateDecoder::new(data)
.read_to_string(&mut inflated)
.unwrap();
assert_eq!(inflated, text);
assert_eq!(
u32::from_le_bytes(bytes[14..18].try_into().unwrap()),
crc32fast::hash(text.as_bytes())
);
}
#[test]
fn same_input_gives_same_bytes() {
let build = || {
let mut zip = ZipWriter::default();
zip.add("a.xml", b"<a/>", Compression::Deflated);
zip.finish()
};
assert_eq!(build(), build());
}
}