is_debug/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2
3mod core {
4    #[cfg(not(feature = "std"))]
5    pub use core::*;
6    #[cfg(feature = "std")]
7    pub use std::*;
8}
9pub use self::core::cmp::PartialEq;
10pub use self::core::prelude::*;
11pub use self::core::{cfg, fmt, fmt::Debug, matches};
12
13pub enum BuildModel {
14    Debug,
15    Release,
16}
17
18pub const fn build_channel() -> BuildModel {
19    if cfg!(debug_assertions) {
20        return BuildModel::Debug;
21    }
22    BuildModel::Release
23}
24
25impl fmt::Display for BuildModel {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            Self::Debug => f.write_str("debug"),
29            Self::Release => f.write_str("release"),
30        }
31    }
32}
33pub const fn is_debug() -> bool {
34    matches!(build_channel(), BuildModel::Debug)
35}
36
37pub const fn is_release() -> bool {
38    matches!(build_channel(), BuildModel::Release)
39}
40
41#[cfg(test)]
42mod tests {
43    use xshell::{cmd, Shell};
44
45    #[test]
46    fn test_std() {
47        let sh = Shell::new().unwrap();
48        let repo = "is_debug_test";
49        let _ = cmd!(sh, "rm -rf {repo}").run();
50        cmd!(sh, "cargo new {repo}").run().unwrap();
51        sh.change_dir(repo);
52        let cargo_content = r#"
53        [package]
54name = "is_debug_test"
55version = "0.1.0"
56edition = "2021"
57
58[dependencies]
59is_debug = {path = "../"}
60        "#;
61
62        sh.write_file("Cargo.toml", cargo_content).unwrap();
63
64        let main_debug = r#"
65fn main() {
66    assert!(is_debug::is_debug())
67}
68"#;
69
70        let main_release = r#"
71fn main() {
72    assert!(is_debug::is_release())
73}
74"#;
75        sh.write_file("src/main.rs", main_debug).unwrap();
76        cmd!(sh, "cargo run").run().unwrap();
77        sh.write_file("src/main.rs", main_release).unwrap();
78        cmd!(sh, "cargo run --release").run().unwrap();
79
80        cmd!(sh, "rm -rf ../{repo}").run().unwrap();
81    }
82}