| 1 |
use std::{ |
| 2 |
env, |
| 3 |
fs::File, |
| 4 |
io::{self, prelude::*}, |
| 5 |
}; |
| 6 |
|
| 7 |
#[cfg(feature = "std")] |
| 8 |
use log::info; |
| 9 |
|
| 10 |
fn main() { |
| 11 |
let options = zopfli::Options::default(); |
| 12 |
let output_type = zopfli::Format::Gzip; |
| 13 |
|
| 14 |
// TODO: CLI arguments |
| 15 |
// TODO: Allow specifying output to STDOUT |
| 16 |
|
| 17 |
let extension = match output_type { |
| 18 |
zopfli::Format::Gzip => ".gz", |
| 19 |
zopfli::Format::Zlib => ".zlib", |
| 20 |
zopfli::Format::Deflate => ".deflate", |
| 21 |
}; |
| 22 |
|
| 23 |
for filename in env::args().skip(1) { |
| 24 |
let file = |
| 25 |
File::open(&filename).unwrap_or_else(|why| panic!("couldn't open {filename}: {why}")); |
| 26 |
let filesize = file.metadata().map(|x| x.len()).unwrap() as usize; |
| 27 |
|
| 28 |
let out_filename = format!("{filename}{extension}"); |
| 29 |
|
| 30 |
// Attempt to create the output file, panic if the output file could not be opened |
| 31 |
let out_file = File::create(&out_filename) |
| 32 |
.unwrap_or_else(|why| panic!("couldn't create output file {out_filename}: {why}")); |
| 33 |
let mut out_file = WriteStatistics::new(out_file); |
| 34 |
|
| 35 |
zopfli::compress(options, output_type, &file, &mut out_file) |
| 36 |
.unwrap_or_else(|why| panic!("couldn't write to output file {out_filename}: {why}")); |
| 37 |
|
| 38 |
let out_size = out_file.count; |
| 39 |
info!( |
| 40 |
"Original Size: {}, Compressed: {}, Compression: {}% Removed", |
| 41 |
filesize, |
| 42 |
out_size, |
| 43 |
100.0 * (filesize - out_size) as f64 / filesize as f64 |
| 44 |
); |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
struct WriteStatistics<W> { |
| 49 |
inner: W, |
| 50 |
count: usize, |
| 51 |
} |
| 52 |
|
| 53 |
impl<W> WriteStatistics<W> { |
| 54 |
const fn new(inner: W) -> Self { |
| 55 |
Self { inner, count: 0 } |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
impl<W: Write> Write for WriteStatistics<W> { |
| 60 |
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 61 |
let res = self.inner.write(buf); |
| 62 |
if let Ok(size) = res { |
| 63 |
self.count += size; |
| 64 |
} |
| 65 |
res |
| 66 |
} |
| 67 |
|
| 68 |
fn flush(&mut self) -> io::Result<()> { |
| 69 |
self.inner.flush() |
| 70 |
} |
| 71 |
} |