1use crate::error::{Error, Result};
7use std::fs::{File, create_dir_all};
8use std::io::{Read, Write};
9use std::path::Path;
10
11#[cfg(feature = "zip")]
12use zip::{CompressionMethod, ZipArchive, ZipWriter, write::FileOptions};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum CompressionFormat {
17 Zip,
19 Gzip,
21 Tar,
23 TarGz,
25}
26
27impl CompressionFormat {
28 pub fn extension(self) -> &'static str {
30 match self {
31 Self::Zip => "zip",
32 Self::Gzip => "gz",
33 Self::Tar => "tar",
34 Self::TarGz => "tar.gz",
35 }
36 }
37
38 pub fn from_extension(ext: &str) -> Option<Self> {
40 match ext.to_lowercase().as_str() {
41 "zip" => Some(Self::Zip),
42 "gz" | "gzip" => Some(Self::Gzip),
43 "tar" => Some(Self::Tar),
44 "tar.gz" | "tgz" => Some(Self::TarGz),
45 _ => None,
46 }
47 }
48
49 pub fn from_path<P: AsRef<Path>>(path: P) -> Option<Self> {
51 let path_str = path.as_ref().to_string_lossy().to_lowercase();
52
53 if path_str.ends_with(".tar.gz") || path_str.ends_with(".tgz") {
54 Some(Self::TarGz)
55 } else if let Some(ext) = path.as_ref().extension() {
56 Self::from_extension(&ext.to_string_lossy())
57 } else {
58 None
59 }
60 }
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum CompressionLevel {
66 None,
68 Fastest,
70 Balanced,
72 Best,
74}
75
76impl CompressionLevel {
77 #[cfg(feature = "zip")]
79 fn to_zip_level(self) -> i32 {
80 match self {
81 Self::None => 0,
82 Self::Fastest => 1,
83 Self::Balanced => 6,
84 Self::Best => 9,
85 }
86 }
87}
88
89#[derive(Debug, Clone)]
91pub struct CompressionStats {
92 pub original_size: u64,
94 pub compressed_size: u64,
96 pub compression_ratio: f64,
98 pub space_saved: u64,
100 pub space_saved_percentage: f64,
102 pub file_count: usize,
104}
105
106impl CompressionStats {
107 pub fn new(original_size: u64, compressed_size: u64, file_count: usize) -> Self {
109 let compression_ratio = if original_size > 0 {
110 if original_size == 0 {
111 0.0
112 } else {
113 (compressed_size as f64) / (original_size as f64)
114 }
115 } else {
116 0.0
117 };
118
119 let space_saved = original_size.saturating_sub(compressed_size);
120 let space_saved_percentage = if original_size > 0 {
121 if original_size == 0 {
122 0.0
123 } else {
124 ((space_saved as f64) / (original_size as f64)) * 100.0
125 }
126 } else {
127 0.0
128 };
129
130 Self {
131 original_size,
132 compressed_size,
133 compression_ratio,
134 space_saved,
135 space_saved_percentage,
136 file_count,
137 }
138 }
139}
140
141impl std::fmt::Display for CompressionStats {
142 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143 writeln!(f, "Compression Statistics:")?;
144 writeln!(f, " Files processed: {}", self.file_count)?;
145 writeln!(f, " Original size: {} bytes", self.original_size)?;
146 writeln!(f, " Compressed size: {} bytes", self.compressed_size)?;
147 writeln!(f, " Compression ratio: {:.2}", self.compression_ratio)?;
148 writeln!(
149 f,
150 " Space saved: {} bytes ({:.1}%)",
151 self.space_saved, self.space_saved_percentage
152 )?;
153 Ok(())
154 }
155}
156
157pub struct CompressionUtil;
159
160impl CompressionUtil {
161 #[cfg(feature = "zip")]
175 pub fn compress_zip<P: AsRef<Path>, Q: AsRef<Path>>(
176 source: P,
177 destination: Q,
178 level: CompressionLevel,
179 ) -> Result<CompressionStats> {
180 let source_path = source.as_ref();
181 let destination_path = destination.as_ref();
182
183 if !source_path.exists() {
184 return Err(Error::not_found(format!(
185 "Source path does not exist: {:?}",
186 source_path
187 )));
188 }
189
190 let file = File::create(destination_path)
191 .map_err(|e| Error::validation(format!("Failed to create ZIP file: {e}")))?;
192
193 let mut zip = ZipWriter::new(file);
194 let options = FileOptions::<()>::default()
195 .compression_method(CompressionMethod::Deflated)
196 .compression_level(Some(level.to_zip_level() as i64));
197
198 let mut original_size = 0u64;
199 let mut file_count = 0usize;
200
201 if source_path.is_file() {
202 let file_name = source_path
204 .file_name()
205 .ok_or_else(|| Error::validation("Invalid file name".to_string()))?
206 .to_string_lossy();
207
208 zip.start_file(&file_name, options)
209 .map_err(|e| Error::validation(format!("Failed to start ZIP file entry: {e}")))?;
210
211 let mut source_file = File::open(source_path)
212 .map_err(|e| Error::validation(format!("Failed to open source file: {e}")))?;
213
214 let mut buffer = Vec::new();
215 source_file
216 .read_to_end(&mut buffer)
217 .map_err(|e| Error::validation(format!("Failed to read source file: {e}")))?;
218
219 original_size += buffer.len() as u64;
220 file_count += 1;
221
222 zip.write_all(&buffer)
223 .map_err(|e| Error::validation(format!("Failed to write to ZIP: {e}")))?;
224 } else if source_path.is_dir() {
225 Self::compress_directory_to_zip(
227 &mut zip,
228 source_path,
229 source_path,
230 options,
231 &mut original_size,
232 &mut file_count,
233 )?;
234 }
235
236 let zip_file = zip
237 .finish()
238 .map_err(|e| Error::validation(format!("Failed to finish ZIP file: {e}")))?;
239
240 let compressed_size = zip_file
241 .metadata()
242 .map_err(|e| Error::validation(format!("Failed to get ZIP file metadata: {e}")))?
243 .len();
244
245 Ok(CompressionStats::new(
246 original_size,
247 compressed_size,
248 file_count,
249 ))
250 }
251
252 #[cfg(feature = "zip")]
254 pub fn decompress_zip<P: AsRef<Path>, Q: AsRef<Path>>(
255 source: P,
256 destination: Q,
257 ) -> Result<CompressionStats> {
258 let source_path = source.as_ref();
259 let destination_path = destination.as_ref();
260
261 if !source_path.exists() {
262 return Err(Error::not_found(format!(
263 "ZIP file does not exist: {:?}",
264 source_path
265 )));
266 }
267
268 let file = File::open(source_path)
269 .map_err(|e| Error::validation(format!("Failed to open ZIP file: {e}")))?;
270
271 let mut archive = ZipArchive::new(file)
272 .map_err(|e| Error::validation(format!("Failed to read ZIP archive: {e}")))?;
273
274 let mut original_size = 0u64;
275 let mut compressed_size = 0u64;
276 let file_count = archive.len();
277
278 for i in 0..archive.len() {
279 let mut file = archive
280 .by_index(i)
281 .map_err(|e| Error::validation(format!("Failed to read ZIP entry {i}: {e}")))?;
282
283 let outpath = destination_path.join(file.name());
284
285 compressed_size += file.compressed_size();
286 original_size += file.size();
287
288 if file.name().ends_with('/') {
289 create_dir_all(&outpath)
291 .map_err(|e| Error::validation(format!("Failed to create directory: {e}")))?;
292 } else {
293 if let Some(parent) = outpath.parent() {
295 create_dir_all(parent).map_err(|e| {
296 Error::validation(format!("Failed to create parent directory: {e}"))
297 })?;
298 }
299
300 let mut outfile = File::create(&outpath)
301 .map_err(|e| Error::validation(format!("Failed to create output file: {e}")))?;
302
303 std::io::copy(&mut file, &mut outfile)
304 .map_err(|e| Error::validation(format!("Failed to extract file: {e}")))?;
305 }
306 }
307
308 Ok(CompressionStats::new(
309 original_size,
310 compressed_size,
311 file_count,
312 ))
313 }
314
315 #[cfg(feature = "flate2")]
317 pub fn compress_gzip(data: &[u8]) -> Result<Vec<u8>> {
318 use flate2::{Compression, write::GzEncoder};
319
320 let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
321 encoder
322 .write_all(data)
323 .map_err(|e| Error::validation(format!("Failed to compress with GZIP: {e}")))?;
324
325 encoder
326 .finish()
327 .map_err(|e| Error::validation(format!("Failed to finish GZIP compression: {e}")))
328 }
329
330 #[cfg(feature = "flate2")]
332 pub fn decompress_gzip(data: &[u8]) -> Result<Vec<u8>> {
333 use flate2::read::GzDecoder;
334
335 let mut decoder = GzDecoder::new(data);
336 let mut decompressed = Vec::new();
337 decoder
338 .read_to_end(&mut decompressed)
339 .map_err(|e| Error::validation(format!("Failed to decompress GZIP: {}", e)))?;
340
341 Ok(decompressed)
342 }
343
344 #[cfg(feature = "flate2")]
346 pub fn compress_file_gzip<P: AsRef<Path>, Q: AsRef<Path>>(
347 source: P,
348 destination: Q,
349 ) -> Result<CompressionStats> {
350 use flate2::{Compression, write::GzEncoder};
351
352 let source_path = source.as_ref();
353 let destination_path = destination.as_ref();
354
355 if !source_path.exists() {
356 return Err(Error::not_found(format!(
357 "Source file does not exist: {:?}",
358 source_path
359 )));
360 }
361
362 let mut source_file = File::open(source_path)
363 .map_err(|e| Error::validation(format!("Failed to open source file: {e}")))?;
364
365 let destination_file = File::create(destination_path)
366 .map_err(|e| Error::validation(format!("Failed to create destination file: {e}")))?;
367
368 let mut encoder = GzEncoder::new(destination_file, Compression::default());
369
370 let original_size = std::io::copy(&mut source_file, &mut encoder)
371 .map_err(|e| Error::validation(format!("Failed to compress file: {}", e)))?;
372
373 encoder
374 .finish()
375 .map_err(|e| Error::validation(format!("Failed to finish compression: {}", e)))?;
376
377 let compressed_size = std::fs::metadata(destination_path)
378 .map_err(|e| Error::validation(format!("Failed to get compressed file size: {}", e)))?
379 .len();
380
381 Ok(CompressionStats::new(original_size, compressed_size, 1))
382 }
383
384 #[cfg(feature = "flate2")]
386 pub fn decompress_file_gzip<P: AsRef<Path>, Q: AsRef<Path>>(
387 source: P,
388 destination: Q,
389 ) -> Result<CompressionStats> {
390 use flate2::read::GzDecoder;
391
392 let source_path = source.as_ref();
393 let destination_path = destination.as_ref();
394
395 if !source_path.exists() {
396 return Err(Error::not_found(format!(
397 "GZIP file does not exist: {source_path:?}"
398 )));
399 }
400
401 let source_file = File::open(source_path)
402 .map_err(|e| Error::validation(format!("Failed to open GZIP file: {e}")))?;
403
404 let mut decoder = GzDecoder::new(source_file);
405
406 let mut destination_file = File::create(destination_path)
407 .map_err(|e| Error::validation(format!("Failed to create destination file: {e}")))?;
408
409 let original_size = std::io::copy(&mut decoder, &mut destination_file)
410 .map_err(|e| Error::validation(format!("Failed to decompress file: {e}")))?;
411
412 let compressed_size = std::fs::metadata(source_path)
413 .map_err(|e| Error::validation(format!("Failed to get source file size: {e}")))?
414 .len();
415
416 Ok(CompressionStats::new(original_size, compressed_size, 1))
417 }
418
419 #[cfg(feature = "zip")]
421 fn compress_directory_to_zip(
422 zip: &mut ZipWriter<File>,
423 base_path: &Path,
424 current_path: &Path,
425 options: FileOptions<()>,
426 total_size: &mut u64,
427 file_count: &mut usize,
428 ) -> Result<()> {
429 let entries = std::fs::read_dir(current_path)
430 .map_err(|e| Error::validation(format!("Failed to read directory: {e}")))?;
431
432 for entry in entries {
433 let entry = entry
434 .map_err(|e| Error::validation(format!("Failed to read directory entry: {e}")))?;
435 let path = entry.path();
436
437 let relative_path = path
438 .strip_prefix(base_path)
439 .map_err(|e| Error::validation(format!("Failed to create relative path: {e}")))?;
440
441 let name = relative_path.to_string_lossy().replace('\\', "/");
442
443 if path.is_file() {
444 zip.start_file(&name, options).map_err(|e| {
445 Error::validation(format!("Failed to start ZIP file entry: {e}"))
446 })?;
447
448 let mut file = File::open(&path)
449 .map_err(|e| Error::validation(format!("Failed to open file: {e}")))?;
450
451 let mut buffer = Vec::new();
452 file.read_to_end(&mut buffer)
453 .map_err(|e| Error::validation(format!("Failed to read file: {e}")))?;
454
455 *total_size += buffer.len() as u64;
456 *file_count += 1;
457
458 zip.write_all(&buffer)
459 .map_err(|e| Error::validation(format!("Failed to write to ZIP: {e}")))?;
460 } else if path.is_dir() {
461 zip.add_directory(format!("{name}/"), options)
463 .map_err(|e| {
464 Error::validation(format!("Failed to add directory to ZIP: {e}"))
465 })?;
466
467 Self::compress_directory_to_zip(
469 zip, base_path, &path, options, total_size, file_count,
470 )?;
471 }
472 }
473
474 Ok(())
475 }
476
477 #[cfg(feature = "zip")]
486 pub fn zip_info<P: AsRef<Path>>(path: P) -> Result<ZipInfo> {
487 let file = File::open(&path)
488 .map_err(|e| Error::validation(format!("Failed to open ZIP file: {e}")))?;
489
490 let mut archive = ZipArchive::new(file)
491 .map_err(|e| Error::validation(format!("Failed to read ZIP archive: {e}")))?;
492
493 let mut files = Vec::new();
494 let mut total_compressed_size = 0u64;
495 let mut total_uncompressed_size = 0u64;
496
497 for i in 0..archive.len() {
498 let file = archive
499 .by_index(i)
500 .map_err(|e| Error::validation(format!("Failed to read ZIP entry {i}: {e}")))?;
501
502 let info = ZipFileInfo {
503 name: file.name().to_string(),
504 compressed_size: file.compressed_size(),
505 uncompressed_size: file.size(),
506 is_directory: file.name().ends_with('/'),
507 compression_method: format!("{:?}", file.compression()),
508 };
509
510 total_compressed_size += file.compressed_size();
511 total_uncompressed_size += file.size();
512 files.push(info);
513 }
514
515 Ok(ZipInfo {
516 file_count: archive.len(),
517 total_compressed_size,
518 total_uncompressed_size,
519 compression_ratio: if total_uncompressed_size > 0 {
520 if total_uncompressed_size == 0 {
521 0.0
522 } else {
523 (total_compressed_size as f64) / (total_uncompressed_size as f64)
524 }
525 } else {
526 0.0
527 },
528 files,
529 })
530 }
531
532 #[cfg(feature = "zip")]
534 pub fn list_zip<P: AsRef<Path>>(path: P) -> Result<Vec<String>> {
535 let file = File::open(&path)
536 .map_err(|e| Error::validation(format!("Failed to open ZIP file: {e}")))?;
537
538 let mut archive = ZipArchive::new(file)
539 .map_err(|e| Error::validation(format!("Failed to read ZIP archive: {e}")))?;
540
541 let mut files = Vec::new();
542 for i in 0..archive.len() {
543 let file = archive
544 .by_index(i)
545 .map_err(|e| Error::validation(format!("Failed to read ZIP entry {i}: {e}")))?;
546 files.push(file.name().to_string());
547 }
548
549 Ok(files)
550 }
551
552 #[cfg(feature = "zip")]
554 pub fn extract_file_from_zip<P: AsRef<Path>, Q: AsRef<Path>>(
555 zip_path: P,
556 file_name: &str,
557 destination: Q,
558 ) -> Result<()> {
559 let file = File::open(&zip_path)
560 .map_err(|e| Error::validation(format!("Failed to open ZIP file: {e}")))?;
561
562 let mut archive = ZipArchive::new(file)
563 .map_err(|e| Error::validation(format!("Failed to read ZIP archive: {e}")))?;
564
565 let mut zip_file = archive
566 .by_name(file_name)
567 .map_err(|e| Error::not_found(format!("File '{file_name}' not found in ZIP: {e}")))?;
568
569 let mut output_file = File::create(destination)
570 .map_err(|e| Error::validation(format!("Failed to create output file: {e}")))?;
571
572 std::io::copy(&mut zip_file, &mut output_file)
573 .map_err(|e| Error::validation(format!("Failed to extract file: {e}")))?;
574
575 Ok(())
576 }
577
578 pub fn calculate_compression_ratio(original_size: u64, compressed_size: u64) -> f64 {
580 if original_size > 0 {
581 if original_size == 0 {
582 0.0
583 } else {
584 (compressed_size as f64) / (original_size as f64)
585 }
586 } else {
587 0.0
588 }
589 }
590
591 pub fn estimate_compression_ratio(file_type: &str) -> f64 {
593 match file_type.to_lowercase().as_str() {
594 "txt" | "csv" | "json" | "xml" | "html" | "css" | "js" => 0.2, "log" => 0.1, "sql" => 0.3,
597 "pdf" => 0.9, "jpg" | "jpeg" | "png" | "gif" | "webp" => 0.95, "mp3" | "mp4" | "avi" | "mkv" => 0.98, "zip" | "rar" | "7z" | "gz" | "bz2" => 0.99, "exe" | "dll" | "so" => 0.7, "doc" | "docx" | "xls" | "xlsx" | "ppt" | "pptx" => 0.6, _ => 0.5, }
605 }
606}
607
608#[derive(Debug, Clone)]
610pub struct ZipInfo {
611 pub file_count: usize,
613 pub total_compressed_size: u64,
615 pub total_uncompressed_size: u64,
617 pub compression_ratio: f64,
619 pub files: Vec<ZipFileInfo>,
621}
622
623#[derive(Debug, Clone)]
625pub struct ZipFileInfo {
626 pub name: String,
628 pub compressed_size: u64,
630 pub uncompressed_size: u64,
632 pub is_directory: bool,
634 pub compression_method: String,
636}
637
638impl std::fmt::Display for ZipInfo {
639 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
640 writeln!(f, "ZIP Archive Information:")?;
641 writeln!(f, " Files: {}", self.file_count)?;
642 writeln!(f, " Compressed size: {} bytes", self.total_compressed_size)?;
643 writeln!(
644 f,
645 " Uncompressed size: {} bytes",
646 self.total_uncompressed_size
647 )?;
648 writeln!(f, " Compression ratio: {:.2}", self.compression_ratio)?;
649 writeln!(
650 f,
651 " Space saved: {:.1}%",
652 (1.0 - self.compression_ratio) * 100.0
653 )?;
654 Ok(())
655 }
656}
657
658#[cfg(test)]
659mod tests {
660 use super::*;
661
662 #[test]
663 fn test_compression_format_extension() {
664 assert_eq!(CompressionFormat::Zip.extension(), "zip");
665 assert_eq!(CompressionFormat::Gzip.extension(), "gz");
666 assert_eq!(CompressionFormat::Tar.extension(), "tar");
667 assert_eq!(CompressionFormat::TarGz.extension(), "tar.gz");
668 }
669
670 #[test]
671 fn test_compression_format_from_extension() {
672 assert_eq!(
673 CompressionFormat::from_extension("zip"),
674 Some(CompressionFormat::Zip)
675 );
676 assert_eq!(
677 CompressionFormat::from_extension("gz"),
678 Some(CompressionFormat::Gzip)
679 );
680 assert_eq!(
681 CompressionFormat::from_extension("tar"),
682 Some(CompressionFormat::Tar)
683 );
684 assert_eq!(CompressionFormat::from_extension("unknown"), None);
685 }
686
687 #[test]
688 fn test_compression_format_from_path() {
689 assert_eq!(
690 CompressionFormat::from_path("test.zip"),
691 Some(CompressionFormat::Zip)
692 );
693 assert_eq!(
694 CompressionFormat::from_path("test.tar.gz"),
695 Some(CompressionFormat::TarGz)
696 );
697 assert_eq!(
698 CompressionFormat::from_path("test.tgz"),
699 Some(CompressionFormat::TarGz)
700 );
701 assert_eq!(CompressionFormat::from_path("test.txt"), None);
702 }
703
704 #[test]
705 fn test_compression_stats() {
706 let stats = CompressionStats::new(1000, 600, 5);
707 assert_eq!(stats.original_size, 1000);
708 assert_eq!(stats.compressed_size, 600);
709 assert_eq!(stats.compression_ratio, 0.6);
710 assert_eq!(stats.space_saved, 400);
711 assert_eq!(stats.space_saved_percentage, 40.0);
712 assert_eq!(stats.file_count, 5);
713 }
714
715 #[test]
716 fn test_compression_stats_display() {
717 let stats = CompressionStats::new(1000, 600, 3);
718 let display = stats.to_string();
719 assert!(display.contains("Files processed: 3"));
720 assert!(display.contains("Original size: 1000 bytes"));
721 assert!(display.contains("Compressed size: 600 bytes"));
722 assert!(display.contains("40.0%"));
723 }
724
725 #[test]
726 fn test_calculate_compression_ratio() {
727 assert_eq!(CompressionUtil::calculate_compression_ratio(1000, 600), 0.6);
728 assert_eq!(CompressionUtil::calculate_compression_ratio(0, 100), 0.0);
729 assert_eq!(CompressionUtil::calculate_compression_ratio(100, 0), 0.0);
730 }
731
732 #[test]
733 fn test_estimate_compression_ratio() {
734 assert!(CompressionUtil::estimate_compression_ratio("txt") < 0.5);
735 assert!(CompressionUtil::estimate_compression_ratio("json") < 0.5);
736 assert!(CompressionUtil::estimate_compression_ratio("jpg") > 0.9);
737 assert!(CompressionUtil::estimate_compression_ratio("mp3") > 0.9);
738 assert!(CompressionUtil::estimate_compression_ratio("zip") > 0.9);
739 assert_eq!(CompressionUtil::estimate_compression_ratio("unknown"), 0.5);
740 }
741
742 #[cfg(feature = "flate2")]
743 #[test]
744 fn test_gzip_compression() {
745 let data = b"Hello, World! This is a test string for compression.".repeat(100);
746
747 let compressed = CompressionUtil::compress_gzip(&data).unwrap();
748 assert!(compressed.len() < data.len());
749
750 let decompressed = CompressionUtil::decompress_gzip(&compressed).unwrap();
751 assert_eq!(decompressed, data);
752 }
753
754 }