cargo_emit/rustc_cfg.rs
1/// Tells Cargo to enable a `$feature`.
2///
3/// This is equivalent to:
4///
5/// ```
6/// println!("cargo:rustc-cfg=$feature");
7/// ```
8///
9/// # Examples
10///
11/// Useful for conditionally enabling certain code to run.
12///
13/// ```
14/// # struct Cargo;
15/// # impl Cargo {
16/// # fn can_bench(&self) -> bool { true }
17/// # }
18/// # let cargo = Cargo;
19/// if cargo.can_bench() {
20/// cargo_emit::rustc_cfg!("bench");
21/// }
22/// ```
23///
24/// or, in case you want it to emit to a custom stream:
25///
26/// ```
27/// # struct Cargo;
28/// # impl Cargo {
29/// # fn can_bench(&self) -> bool { true }
30/// # }
31/// # let cargo = Cargo;
32/// let mut stdout = std::io::stdout();
33/// if cargo.can_bench() {
34/// cargo_emit::rustc_cfg!(
35/// to: stdout,
36/// "bench"
37/// );
38/// }
39/// ```
40///
41/// Then outside of `build.rs`:
42///
43/// ```
44/// #[cfg(bench)]
45/// mod benches {
46/// // ...
47/// }
48/// ```
49#[macro_export]
50macro_rules! rustc_cfg {
51 (to: $stream:expr, $feature:expr $(, $($args:tt)*)?) => {
52 $crate::pair!(to: $stream, "rustc-cfg", $feature $(, $($args)+)?);
53 };
54 ($feature:expr $(, $($args:tt)*)?) => {
55 $crate::rustc_cfg!(to: std::io::stdout(), $feature $(, $($args)+)?);
56 };
57}
58
59#[cfg(test)]
60mod tests {
61 #[test]
62 fn literal() {
63 insta::assert_display_snapshot!(
64 crate::capture_output(|output| {
65 crate::rustc_cfg!(
66 to: output,
67 "CFG"
68 );
69 }),
70 @"cargo:rustc-cfg=CFG\n"
71 );
72 }
73
74 #[test]
75 fn formatted() {
76 insta::assert_display_snapshot!(
77 crate::capture_output(|output| {
78 crate::rustc_cfg!(
79 to: output,
80 "{}", "CFG"
81 );
82 }),
83 @"cargo:rustc-cfg=CFG\n"
84 );
85 }
86}