Last active
August 17, 2022 20:52
-
-
Save mtkennerly/981622694bb9313253a91ea8e4ebde9d to your computer and use it in GitHub Desktop.
Rust unzipped file having different content
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "zip-repro" | |
version = "0.1.0" | |
edition = "2021" | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] | |
zip = "0.6.2" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{error::Error, io::Write}; | |
use std::io::Read; | |
use zip::{CompressionMethod, ZipArchive, ZipWriter, read::ZipFile, write::FileOptions}; | |
use std::fs::File; | |
use std::io::BufReader; | |
use std::fs::read; | |
const ARCHIVE_FILE: &str = "assets/archive.zip"; | |
const PAIRS: &[(&str, &str)] = &[ | |
("assets/text.txt", "text.txt"), | |
("assets/line.jpg", "line.jpg"), | |
("assets/screenshot.jpg", "screenshot.jpg"), | |
]; | |
fn try_same_content_as_zip(original: &str, archived: &mut ZipFile) -> Result<bool, Box<dyn Error>> { | |
let handle = File::open(original)?; | |
let mut reader = BufReader::new(handle); | |
let mut disk_buffer = [0; 1024]; | |
let mut zip_buffer = [0; 1024]; | |
loop { | |
let read_disk = reader.read(&mut disk_buffer[..])?; | |
let read_zip = archived.read(&mut zip_buffer[..])?; | |
if read_disk != read_zip || disk_buffer.iter().zip(zip_buffer.iter()).any(|(a, b)| a != b) { | |
return Ok(false); | |
} | |
if read_disk == 0 || read_zip == 0 { | |
break; | |
} | |
} | |
Ok(true) | |
} | |
fn main() -> Result<(), Box<dyn Error>> { | |
// Write: | |
let options = FileOptions::default() | |
.compression_method(CompressionMethod::Deflated) | |
.large_file(true); | |
let handle = File::create(ARCHIVE_FILE)?; | |
let mut archive = ZipWriter::new(handle); | |
for (original, archived) in PAIRS { | |
archive.start_file(*archived, options)?; | |
archive.write_all(&read(original)?)?; | |
} | |
archive.finish()?; | |
// Read: | |
let handle = File::open(ARCHIVE_FILE)?; | |
let mut archive = ZipArchive::new(handle)?; | |
for (original, archived) in PAIRS { | |
println!("{} matches = {}", &original, try_same_content_as_zip(original, &mut archive.by_name(archived)?)?); | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment