Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 30 additions & 38 deletions examples/write_dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use anyhow::Context;
use clap::{Parser, ValueEnum};
use std::io::prelude::*;
use zip::{result::ZipError, write::SimpleFileOptions};
use zip::{cfg_if_expr, result::ZipError, write::SimpleFileOptions};

use std::fs::File;
use std::path::{Path, PathBuf};
Expand All @@ -30,59 +30,51 @@ enum CompressionMethod {
Zstd,
}

fn main() {
std::process::exit(real_main());
}

fn real_main() -> i32 {
fn main() -> ! {
let args = Args::parse();
let src_dir = &args.source;
let dst_file = &args.destination;
let method = match args.compression_method {
CompressionMethod::Stored => zip::CompressionMethod::Stored,
CompressionMethod::Deflated => {
#[cfg(not(feature = "deflate-flate2"))]
{
CompressionMethod::Deflated => cfg_if_expr! {
#[cfg(feature = "deflate-flate2")] => zip::CompressionMethod::Deflated,
_ => {
println!("The `deflate-flate2` feature is not enabled");
return 1;
std::process::exit(1)
}
#[cfg(feature = "deflate-flate2")]
zip::CompressionMethod::Deflated
}
CompressionMethod::Bzip2 => {
#[cfg(not(feature = "bzip2"))]
{
},
CompressionMethod::Bzip2 => cfg_if_expr! {
#[cfg(feature = "bzip2")] => zip::CompressionMethod::Bzip2,
_ => {
println!("The `bzip2` feature is not enabled");
return 1;
std::process::exit(1)
}
#[cfg(feature = "bzip2")]
zip::CompressionMethod::Bzip2
}
CompressionMethod::Xz => {
#[cfg(not(feature = "xz"))]
{
},
CompressionMethod::Xz => cfg_if_expr! {
#[cfg(feature = "xz")] => zip::CompressionMethod::Xz,
_ => {
println!("The `xz` feature is not enabled");
return 1;
std::process::exit(1)
}
#[cfg(feature = "xz")]
zip::CompressionMethod::Xz
}
CompressionMethod::Zstd => {
#[cfg(not(feature = "zstd"))]
{
},
CompressionMethod::Zstd => cfg_if_expr! {
#[cfg(feature = "zstd")] => zip::CompressionMethod::Zstd,
_ => {
println!("The `zstd` feature is not enabled");
return 1;
std::process::exit(1)
}
#[cfg(feature = "zstd")]
zip::CompressionMethod::Zstd
}
},
};
match doit(src_dir, dst_file, method) {
Ok(_) => println!("done: {src_dir:?} written to {dst_file:?}"),
Err(e) => eprintln!("Error: {e:?}"),
Ok(_) => {
println!("done: {src_dir:?} written to {dst_file:?}");
std::process::exit(0);
}
Err(e) => {
eprintln!("Error: {e:?}");
std::process::abort();
}
}

0
}

fn zip_dir<T>(
Expand Down
11 changes: 6 additions & 5 deletions src/compression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

use std::{fmt, io};

use crate::cfg_if_expr;

#[allow(deprecated)]
/// Identifies the storage format used to compress a file within a ZIP archive.
///
Expand Down Expand Up @@ -228,11 +230,10 @@ impl CompressionMethod {

impl Default for CompressionMethod {
fn default() -> Self {
#[cfg(feature = "_deflate-any")]
return CompressionMethod::Deflated;

#[cfg(not(feature = "_deflate-any"))]
return CompressionMethod::Stored;
cfg_if_expr! {
#[cfg(feature = "_deflate-any")] => CompressionMethod::Deflated,
_ => CompressionMethod::Stored
}
}
}

Expand Down
5 changes: 4 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
//!
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![warn(missing_docs)]
#![allow(unexpected_cfgs)] // Needed for cfg(fuzzing) on nightly as of 2024-05-06
#![allow(unexpected_cfgs)] // Needed for cfg(fuzzing)
pub use crate::compression::{CompressionMethod, SUPPORTED_COMPRESSION_METHODS};
pub use crate::read::HasZipMetadata;
pub use crate::read::ZipArchive;
Expand Down Expand Up @@ -71,3 +71,6 @@ zip = \"="]
#[doc = "\"\n\
```"]
pub mod unstable;

#[doc(hidden)]
pub mod macros;
162 changes: 162 additions & 0 deletions src/macros.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
//! Macros used internally.
//!
//! These may technically be exported, but that's only to make them available to internal
//! project dependencies. The `#[doc(hidden)]` mark indicates that these are not stable or supported
//! APIs, and should not be relied upon by external dependees.
/// The single macro export of the [`cfg-if`](https://docs.rs/cfg-if) crate.
///
/// It is packaged here to avoid pulling in another dependency. The stdlib does the same[^1].
///
/// [^1]: https://github.com/rust-lang/rust/blob/a2db9280539229a3b8a084a09886670a57bc7e9c/library/compiler-builtins/libm/src/math/support/macros.rs#L1
#[doc(hidden)]
#[macro_export]
macro_rules! cfg_if {
// match if/else chains with a final `else`
(
$(
if #[cfg( $i_meta:meta )] { $( $i_tokens:tt )* }
) else+
else { $( $e_tokens:tt )* }
) => {
$crate::cfg_if! {
@__items () ;
$(
(( $i_meta ) ( $( $i_tokens )* )) ,
)+
(() ( $( $e_tokens )* )) ,
};
};

// match if/else chains lacking a final `else`
(
if #[cfg( $i_meta:meta )] { $( $i_tokens:tt )* }
$(
else if #[cfg( $e_meta:meta )] { $( $e_tokens:tt )* }
)*
) => {
$crate::cfg_if! {
@__items () ;
(( $i_meta ) ( $( $i_tokens )* )) ,
$(
(( $e_meta ) ( $( $e_tokens )* )) ,
)*
};
};

// Internal and recursive macro to emit all the items
//
// Collects all the previous cfgs in a list at the beginning, so they can be
// negated. After the semicolon are all the remaining items.
(@__items ( $( $_:meta , )* ) ; ) => {};
(
@__items ( $( $no:meta , )* ) ;
(( $( $yes:meta )? ) ( $( $tokens:tt )* )) ,
$( $rest:tt , )*
) => {
// Emit all items within one block, applying an appropriate #[cfg]. The
// #[cfg] will require all `$yes` matchers specified and must also negate
// all previous matchers.
#[cfg(all(
$( $yes , )?
not(any( $( $no ),* ))
))]
$crate::cfg_if! { @__identity $( $tokens )* }

// Recurse to emit all other items in `$rest`, and when we do so add all
// our `$yes` matchers to the list of `$no` matchers as future emissions
// will have to negate everything we just matched as well.
$crate::cfg_if! {
@__items ( $( $no , )* $( $yes , )? ) ;
$( $rest , )*
};
};

// Internal macro to make __apply work out right for different match types,
// because of how macros match/expand stuff.
(@__identity $( $tokens:tt )* ) => {
$( $tokens )*
};
}

/// Similar to [`cfg_if`](cfg_if), but accepts a list of expressions, and generates an internal
/// closure to return each value.
///
/// The main reason this is necessary is because attaching `#[cfg(...)]` annotations to certain
/// types of statements requires a nightly feature, or `cfg_if` would be enough on its own. This
/// macro's restricted interface allows it to generate a closure as a circumlocution that is legal
/// on stable rust.
///
/// Note that any `return` operation within the expressions provided to this macro will apply to the
/// generated closure, not the enclosing scope--it cannot be used to interfere with external
/// control flow.
Copy link
Member

@Pr0methean Pr0methean Oct 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this gotcha be checked at build-time, by raising an error when a branch expression starts with return, break or continue and a warning when those keywords occur later in the expression?

///
/// The generated closure is non-[`const`](const@keyword), so cannot be used inside `const` methods.
#[doc(hidden)]
#[macro_export]
macro_rules! cfg_if_expr {
// Match =>, chains, maybe with a final _ => catchall clause.
(
$( $ret_ty:ty : )?
$(
#[cfg( $i_meta:meta )] => $i_val:expr
),+ ,
_ => $rem_val:expr $(,)?
) => {
(|| $( -> $ret_ty )? {
$crate::cfg_if_expr! {
@__items ();
$(
(( $i_meta ) (
#[allow(unreachable_code)]
return $i_val ;
)) ,
)+
(() (
#[allow(unreachable_code)]
return $rem_val ;
)) ,
}
})()
};
// Match =>, chains *without* any _ => clause.
(
$( $ret_ty:ty : )?
$(
#[cfg( $i_meta:meta )] => $i_val:expr
),+ $(,)?
) => {
(|| $( -> $ret_ty )? {
$crate::cfg_if_expr! {
@__items ();
$(
(( $i_meta ) (
#[allow(unreachable_code)]
return $i_val ;
)) ,
)+
}
})()
};

(@__items ( $( $_:meta , )* ) ; ) => {};
(
@__items ( $( $no:meta , )* ) ;
(( $( $yes:meta )? ) ( $( $tokens:tt )* )) ,
$( $rest:tt , )*
) => {
#[cfg(all(
$( $yes , )?
not(any( $( $no ),* ))
))]
$crate::cfg_if_expr! { @__identity $( $tokens )* }

$crate::cfg_if_expr! {
@__items ( $( $no , )* $( $yes , )? ) ;
$( $rest , )*
};
};
(@__identity $( $tokens:tt )* ) => {
$( $tokens )*
};
}
Loading