devela::code::util

Macro cfg_if

Source
macro_rules! cfg_if {
    ( $( if #[cfg( $i_meta:meta )] { $( $i_tokens:tt )* } ) else+
      else { $( $e_tokens:tt )* }
    ) => { ... };
    ( $( if #[cfg( $i_meta:meta )] { $( $i_tokens:tt )* } ) else+
      else { $( $e_tokens:tt )* }
      if $($extra_conditions:tt)+
    ) => { ... };
    ( if #[cfg( $i_meta:meta )] { $( $i_tokens:tt )* }
      $( else if #[cfg( $e_meta:meta )] { $( $e_tokens:tt )* } )*
    ) => { ... };
    ( if #[cfg( $i_meta:meta )] { $( $i_tokens:tt )* }
      $( else if #[cfg( $e_meta:meta )] { $( $e_tokens:tt )* } )*
      if $($extra_conditions:tt)+
    ) => { ... };
    (@__items ( $( $_:meta , )* ) ; ) => { ... };
    ( @__items ( $( $no:meta , )* ) ;
      (( $( $yes:meta )? ) ( $( $tokens:tt )* )) ,
      $( $rest:tt , )*
    ) => { ... };
    (@__identity $( $tokens:tt )* ) => { ... };
}
Expand description

A macro for defining #[cfg] if-else statements.

Allows definition of a cascade of #[cfg] cases, emitting the implementation which matches first.

ยงExample

cfg_if! {
    if #[cfg(unix)] {
        fn foo() { /* unix specific functionality */ }
    } else if #[cfg(target_pointer_width = "32")] {
        fn foo() { /* non-unix, 32-bit functionality */ }
    } else {
        fn foo() { /* fallback implementation */ }
    }

    // there can be multiple conditions
    if #[cfg(feature = "bar")] {
        fn bar() {}
    }
}