#proc-macro #cfg #block #const

cfg_block

Simple crate to allow using #[cfg(...)] and other macros on blocks

3 unstable releases

0.2.0 Jan 24, 2024
0.1.1 Jul 24, 2022
0.1.0 Jul 24, 2022

#698 in Development tools

Download history 2252/week @ 2024-06-23 2090/week @ 2024-06-30 2019/week @ 2024-07-07 1330/week @ 2024-07-14 1627/week @ 2024-07-21 1031/week @ 2024-07-28 689/week @ 2024-08-04 635/week @ 2024-08-11 613/week @ 2024-08-18 761/week @ 2024-08-25 913/week @ 2024-09-01 1009/week @ 2024-09-08 1559/week @ 2024-09-15 945/week @ 2024-09-22 1100/week @ 2024-09-29 704/week @ 2024-10-06

4,748 downloads per month
Used in diesel-connection

Custom license

11KB
86 lines

cfg_block

A simple library for applying procedural macros to a block, for easier const values and more readable code. Grab the docs here https://docs.rs/cfg_block.

Here's a simple example for defining variables based on platform:

use cfg_block::cfg_block;

cfg_block!{
    #[cfg(target_family = "unix")] {
        const PLATFORM: &str = "posix !";
        const MY_NUMBER: u8 = 5;
    }
    #[cfg(target_family = "windows")] {
        const PLATFORM: &str = "window !";
        const MY_NUMBER: u16 = 20;
    }
    #[cfg(target_family = "wasm")] {
        const PLATFORM: &str = "web !";
        const MY_NUMBER: i32 = -5;
    }
}

// Assuming this test runs on linux/macos...
assert_eq!(PLATFORM, "posix !");
assert_eq!(MY_NUMBER, 5);

The above example demonstrates using #[cfg()], but it should work for any procedural macro. Behind the scenes, it just inserts the macro attribute before every item in the block, and removes the block wrapper.

This macro also supports a simple if/else configuration:

cfg_block!{
    if #[cfg(mips)] {
        const STR_A: &str = "where did you get this processor";
        const STR_B: &str = "mips just makes a good passing doctest";
    } else {
        const STR_A: &str = "good!";
        const STR_B: &str = "better!";
    }
}

assert_eq(STR_A, "good!");
assert_eq(STR_B, "better!");

Please note that unlike the general syntax, this if/else syntax only works with #[cfg(something)] (it just replaces it with #[cfg(not(something))]).

Link to crates.io page: https://crates.io/crates/cfg_block

Get the docs here: https://docs.rs/cfg_block

Source repository: https://github.com/pluots/cfg_block

If you have any improvements or ideas, feel free to bring them up on the Github page!

No runtime deps