#proc-macro #block #cfg #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

#252 in Development tools

Download history 2544/week @ 2023-12-04 2815/week @ 2023-12-11 2637/week @ 2023-12-18 1089/week @ 2023-12-25 1846/week @ 2024-01-01 2361/week @ 2024-01-08 2436/week @ 2024-01-15 2816/week @ 2024-01-22 2276/week @ 2024-01-29 2253/week @ 2024-02-05 2453/week @ 2024-02-12 2829/week @ 2024-02-19 2616/week @ 2024-02-26 2067/week @ 2024-03-04 2263/week @ 2024-03-11 1805/week @ 2024-03-18

8,932 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