Expand description
Provides helpful configuration macros, allowing features to be introspected across crates at compile time.
The two main features that power this crate are switch and alias.
§switch
switch provides a match-like syntax to make complex compile-time configuration
more ergonomic.
// Without `crossfig`:
#[cfg(feature = "fastest")]
// Use the fastest algorithm!
#[cfg(all(not(feature = "fastest"), feature = "fast"))]
// Use the fast algorithm
#[cfg(all(not(feature = "fastest"), not(feature = "fast")))]
// Use the slow algorithm// With `crossfig`:
crossfig::switch! {
#[cfg(feature = "fastest")] => {
// Use the fastest algorithm!
}
#[cfg(feature = "fast")] => {
// Use the fast algorithm
}
_ => {
// Use the slow algorithm
}
}§alias
alias instead allows for creating a short-hand for common configurations.
// Define an alias
alias! {
std: { #[cfg(feature = "std")] }
}
// Use it for conditional compilation
std! {
// This code is only compiled with feature = "std"
}§Combined
Individually, both are useful tools for reducing repetition in conditional compilation. But where they really shine is when combined:
alias! {
std: { #[cfg(feature = "std")] },
log: { #[cfg(feature = "log")] },
}
switch! {
log => {
// Use the log crate
}
std => {
// Use println! for logging
}
_ => {
// Don't bother logging
}
}§Cross-Crate Configuration Introspection
One last trick; aliases created with alias can be exported in
your public API.
// In the `foo` crate:
crossfig::alias! {
pub multi_threading: { #[cfg(feature = "multi_threading")] }
}
// In a consumer's crate:
foo::multi_threading! {
// This code will be compiled if and only if foo/multi_threading
// is enabled.
}This can be extremely powerful, as it allows consuming crates to introspect on the enabled features of their dependencies.
§macro_rules_attribute
As a quality of life improvement, you can also use macro_rules_attribute.
This provides an attribute proc-macro apply, which can be used to apply aliases
to items as an attribute.
#![no_std]
use macro_rules_attribute::apply;
alias! {
std: { #[cfg(feature = "std")] }
}
#[apply(std)]
extern crate std;Macros§
- alias
- Defines an alias for a particular configuration.
This has two advantages over directly using
#[cfg(...)]: - disabled
- Examples
- enabled
- Examples
- switch
- Provides a
match-like expression similar tocfg_ifand based on the experimentalcfg_match. The nameswitchis used to avoid conflict with thematchkeyword. Arms are evaluated top to bottom, and an optional wildcard arm can be provided if no match can be made.