summaryrefslogtreecommitdiffstats
path: root/third_party/rust/zip/examples
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 14:29:10 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 14:29:10 +0000
commit2aa4a82499d4becd2284cdb482213d541b8804dd (patch)
treeb80bf8bf13c3766139fbacc530efd0dd9d54394c /third_party/rust/zip/examples
parentInitial commit. (diff)
downloadfirefox-2aa4a82499d4becd2284cdb482213d541b8804dd.tar.xz
firefox-2aa4a82499d4becd2284cdb482213d541b8804dd.zip
Adding upstream version 86.0.1.upstream/86.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/zip/examples')
-rw-r--r--third_party/rust/zip/examples/extract.rs57
-rw-r--r--third_party/rust/zip/examples/extract_lorem.rs33
-rw-r--r--third_party/rust/zip/examples/stdin_info.rs31
-rw-r--r--third_party/rust/zip/examples/write_dir.rs96
-rw-r--r--third_party/rust/zip/examples/write_sample.rs75
5 files changed, 292 insertions, 0 deletions
diff --git a/third_party/rust/zip/examples/extract.rs b/third_party/rust/zip/examples/extract.rs
new file mode 100644
index 0000000000..3d3a0939d5
--- /dev/null
+++ b/third_party/rust/zip/examples/extract.rs
@@ -0,0 +1,57 @@
+extern crate zip;
+
+use std::io;
+use std::fs;
+
+fn main() {
+ std::process::exit(real_main());
+}
+
+fn real_main() -> i32 {
+ let args: Vec<_> = std::env::args().collect();
+ if args.len() < 2 {
+ println!("Usage: {} <filename>", args[0]);
+ return 1;
+ }
+ let fname = std::path::Path::new(&*args[1]);
+ let file = fs::File::open(&fname).unwrap();
+
+ let mut archive = zip::ZipArchive::new(file).unwrap();
+
+ for i in 0..archive.len() {
+ let mut file = archive.by_index(i).unwrap();
+ let outpath = file.sanitized_name();
+
+ {
+ let comment = file.comment();
+ if !comment.is_empty() {
+ println!("File {} comment: {}", i, comment);
+ }
+ }
+
+ if (&*file.name()).ends_with('/') {
+ println!("File {} extracted to \"{}\"", i, outpath.as_path().display());
+ fs::create_dir_all(&outpath).unwrap();
+ } else {
+ println!("File {} extracted to \"{}\" ({} bytes)", i, outpath.as_path().display(), file.size());
+ if let Some(p) = outpath.parent() {
+ if !p.exists() {
+ fs::create_dir_all(&p).unwrap();
+ }
+ }
+ let mut outfile = fs::File::create(&outpath).unwrap();
+ io::copy(&mut file, &mut outfile).unwrap();
+ }
+
+ // Get and Set permissions
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+
+ if let Some(mode) = file.unix_mode() {
+ fs::set_permissions(&outpath, fs::Permissions::from_mode(mode)).unwrap();
+ }
+ }
+ }
+ return 0;
+}
diff --git a/third_party/rust/zip/examples/extract_lorem.rs b/third_party/rust/zip/examples/extract_lorem.rs
new file mode 100644
index 0000000000..eb49bbe307
--- /dev/null
+++ b/third_party/rust/zip/examples/extract_lorem.rs
@@ -0,0 +1,33 @@
+use std::io::prelude::*;
+
+extern crate zip;
+
+fn main()
+{
+ std::process::exit(real_main());
+}
+
+fn real_main() -> i32
+{
+ let args: Vec<_> = std::env::args().collect();
+ if args.len() < 2 {
+ println!("Usage: {} <filename>", args[0]);
+ return 1;
+ }
+ let fname = std::path::Path::new(&*args[1]);
+ let zipfile = std::fs::File::open(&fname).unwrap();
+
+ let mut archive = zip::ZipArchive::new(zipfile).unwrap();
+
+ let mut file = match archive.by_name("test/lorem_ipsum.txt")
+ {
+ Ok(file) => file,
+ Err(..) => { println!("File test/lorem_ipsum.txt not found"); return 2;}
+ };
+
+ let mut contents = String::new();
+ file.read_to_string(&mut contents).unwrap();
+ println!("{}", contents);
+
+ return 0;
+}
diff --git a/third_party/rust/zip/examples/stdin_info.rs b/third_party/rust/zip/examples/stdin_info.rs
new file mode 100644
index 0000000000..910ba8e85e
--- /dev/null
+++ b/third_party/rust/zip/examples/stdin_info.rs
@@ -0,0 +1,31 @@
+extern crate zip;
+
+use std::io::{self, Read};
+
+fn main() {
+ std::process::exit(real_main());
+}
+
+fn real_main() -> i32 {
+ let stdin = io::stdin();
+ let mut stdin_handle = stdin.lock();
+ let mut buf = [0u8; 16];
+
+ loop {
+ match zip::read::read_zipfile_from_stream(&mut stdin_handle) {
+ Ok(Some(mut file)) => {
+ println!("{}: {} bytes ({} bytes packed)", file.name(), file.size(), file.compressed_size());
+ match file.read(&mut buf) {
+ Ok(n) => println!("The first {} bytes are: {:?}", n, &buf[0..n]),
+ Err(e) => println!("Could not read the file: {:?}", e),
+ };
+ },
+ Ok(None) => break,
+ Err(e) => {
+ println!("Error encountered while reading zip: {:?}", e);
+ return 1;
+ },
+ }
+ }
+ return 0;
+}
diff --git a/third_party/rust/zip/examples/write_dir.rs b/third_party/rust/zip/examples/write_dir.rs
new file mode 100644
index 0000000000..0e6f59bd24
--- /dev/null
+++ b/third_party/rust/zip/examples/write_dir.rs
@@ -0,0 +1,96 @@
+extern crate zip;
+extern crate walkdir;
+
+use std::io::prelude::*;
+use std::io::{Write, Seek};
+use std::iter::Iterator;
+use zip::write::FileOptions;
+use zip::result::ZipError;
+
+use walkdir::{WalkDir, DirEntry};
+use std::path::Path;
+use std::fs::File;
+
+fn main() {
+ std::process::exit(real_main());
+}
+
+const METHOD_STORED : Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Stored);
+
+#[cfg(feature = "flate2")]
+const METHOD_DEFLATED : Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Deflated);
+#[cfg(not(feature = "flate2"))]
+const METHOD_DEFLATED : Option<zip::CompressionMethod> = None;
+
+#[cfg(feature = "bzip2")]
+const METHOD_BZIP2 : Option<zip::CompressionMethod> = Some(zip::CompressionMethod::Bzip2);
+#[cfg(not(feature = "bzip2"))]
+const METHOD_BZIP2 : Option<zip::CompressionMethod> = None;
+
+fn real_main() -> i32 {
+ let args: Vec<_> = std::env::args().collect();
+ if args.len() < 3 {
+ println!("Usage: {} <source_directory> <destination_zipfile>",
+ args[0]);
+ return 1;
+ }
+
+ let src_dir = &*args[1];
+ let dst_file = &*args[2];
+ for &method in [METHOD_STORED, METHOD_DEFLATED, METHOD_BZIP2].iter() {
+ if method.is_none() { continue }
+ match doit(src_dir, dst_file, method.unwrap()) {
+ Ok(_) => println!("done: {} written to {}", src_dir, dst_file),
+ Err(e) => println!("Error: {:?}", e),
+ }
+ }
+
+ return 0;
+}
+
+fn zip_dir<T>(it: &mut Iterator<Item=DirEntry>, prefix: &str, writer: T, method: zip::CompressionMethod)
+ -> zip::result::ZipResult<()>
+ where T: Write+Seek
+{
+ let mut zip = zip::ZipWriter::new(writer);
+ let options = FileOptions::default()
+ .compression_method(method)
+ .unix_permissions(0o755);
+
+ let mut buffer = Vec::new();
+ for entry in it {
+ let path = entry.path();
+ let name = path.strip_prefix(Path::new(prefix))
+ .unwrap()
+ .to_str()
+ .unwrap();
+
+ if path.is_file() {
+ println!("adding {:?} as {:?} ...", path, name);
+ zip.start_file(name, options)?;
+ let mut f = File::open(path)?;
+
+ f.read_to_end(&mut buffer)?;
+ zip.write_all(&*buffer)?;
+ buffer.clear();
+ }
+ }
+ zip.finish()?;
+ Result::Ok(())
+}
+
+fn doit(src_dir: &str, dst_file: &str, method: zip::CompressionMethod) -> zip::result::ZipResult<()> {
+ if !Path::new(src_dir).is_dir() {
+ return Err(ZipError::FileNotFound);
+ }
+
+ let path = Path::new(dst_file);
+ let file = File::create(&path).unwrap();
+
+ let walkdir = WalkDir::new(src_dir.to_string());
+ let it = walkdir.into_iter();
+
+ zip_dir(&mut it.filter_map(|e| e.ok()), src_dir, file, method)?;
+
+ Ok(())
+} \ No newline at end of file
diff --git a/third_party/rust/zip/examples/write_sample.rs b/third_party/rust/zip/examples/write_sample.rs
new file mode 100644
index 0000000000..427bae64a0
--- /dev/null
+++ b/third_party/rust/zip/examples/write_sample.rs
@@ -0,0 +1,75 @@
+use std::io::prelude::*;
+use zip::write::FileOptions;
+
+extern crate zip;
+
+fn main()
+{
+ std::process::exit(real_main());
+}
+
+fn real_main() -> i32
+{
+ let args: Vec<_> = std::env::args().collect();
+ if args.len() < 2 {
+ println!("Usage: {} <filename>", args[0]);
+ return 1;
+ }
+
+ let filename = &*args[1];
+ match doit(filename)
+ {
+ Ok(_) => println!("File written to {}", filename),
+ Err(e) => println!("Error: {:?}", e),
+ }
+
+ return 0;
+}
+
+fn doit(filename: &str) -> zip::result::ZipResult<()>
+{
+ let path = std::path::Path::new(filename);
+ let file = std::fs::File::create(&path).unwrap();
+
+ let mut zip = zip::ZipWriter::new(file);
+
+ try!(zip.add_directory("test/", FileOptions::default()));
+
+ let options = FileOptions::default().compression_method(zip::CompressionMethod::Stored).unix_permissions(0o755);
+ try!(zip.start_file("test/☃.txt", options));
+ try!(zip.write_all(b"Hello, World!\n"));
+
+ try!(zip.start_file("test/lorem_ipsum.txt", FileOptions::default()));
+ try!(zip.write_all(LOREM_IPSUM));
+
+ try!(zip.finish());
+ Ok(())
+}
+
+const LOREM_IPSUM : &'static [u8] = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tellus elit, tristique vitae mattis egestas, ultricies vitae risus. Quisque sit amet quam ut urna aliquet
+molestie. Proin blandit ornare dui, a tempor nisl accumsan in. Praesent a consequat felis. Morbi metus diam, auctor in auctor vel, feugiat id odio. Curabitur ex ex,
+dictum quis auctor quis, suscipit id lorem. Aliquam vestibulum dolor nec enim vehicula, porta tristique augue tincidunt. Vivamus ut gravida est. Sed pellentesque, dolor
+vitae tristique consectetur, neque lectus pulvinar dui, sed feugiat purus diam id lectus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
+inceptos himenaeos. Maecenas feugiat velit in ex ultrices scelerisque id id neque.
+
+Phasellus sed nisi in augue sodales pulvinar ut et leo. Pellentesque eget leo vitae massa bibendum sollicitudin. Curabitur erat lectus, congue quis auctor sed, aliquet
+bibendum est. Ut porta ultricies turpis at maximus. Cras non lobortis justo. Duis rutrum magna sed velit facilisis, et sagittis metus laoreet. Pellentesque quam ligula,
+dapibus vitae mauris quis, dapibus cursus leo. Sed sit amet condimentum eros. Nulla vestibulum enim sit amet lorem pharetra, eu fringilla nisl posuere. Sed tristique non
+nibh at viverra. Vivamus sed accumsan lacus, nec pretium eros. Mauris elementum arcu eu risus fermentum, tempor ullamcorper neque aliquam. Sed tempor in erat eu
+suscipit. In euismod in libero in facilisis. Donec sagittis, odio et fermentum dignissim, risus justo pretium nibh, eget vestibulum lectus metus vel lacus.
+
+Quisque feugiat, magna ac feugiat ullamcorper, augue justo consequat felis, ut fermentum arcu lorem vitae ligula. Quisque iaculis tempor maximus. In quis eros ac tellus
+aliquam placerat quis id tellus. Donec non gravida nulla. Morbi faucibus neque sed faucibus aliquam. Sed accumsan mattis nunc, non interdum justo. Cras vitae facilisis
+leo. Fusce sollicitudin ultrices sagittis. Maecenas eget massa id lorem dignissim ultrices non et ligula. Pellentesque aliquam mi ac neque tempus ornare. Morbi non enim
+vulputate quam ullamcorper finibus id non neque. Quisque malesuada commodo lorem, ut ornare velit iaculis rhoncus. Mauris vel maximus ex.
+
+Morbi eleifend blandit diam, non vulputate ante iaculis in. Donec pellentesque augue id enim suscipit, eget suscipit lacus commodo. Ut vel ex vitae elit imperdiet
+vulputate. Nunc eu mattis orci, ut pretium sem. Nam vitae purus mollis ante tempus malesuada a at magna. Integer mattis lectus non luctus lobortis. In a cursus quam,
+eget faucibus sem.
+
+Donec vitae condimentum nisi, non efficitur massa. Praesent sed mi in massa sollicitudin iaculis. Pellentesque a libero ultrices, sodales lacus eu, ornare dui. In
+laoreet est nec dolor aliquam consectetur. Integer iaculis felis venenatis libero pulvinar, ut pretium odio interdum. Donec in nisi eu dolor varius vestibulum eget vel
+nunc. Morbi a venenatis quam, in vehicula justo. Nam risus dui, auctor eu accumsan at, sagittis ac lectus. Mauris iaculis dignissim interdum. Cras cursus dapibus auctor.
+Donec sagittis massa vitae tortor viverra vehicula. Mauris fringilla nunc eu lorem ultrices placerat. Maecenas posuere porta quam at semper. Praesent eu bibendum eros.
+Nunc congue sollicitudin ante, sollicitudin lacinia magna cursus vitae.
+";