Skip to main content

sparse_ir_core/
debug.rs

1//! Opt-in debug diagnostics, controlled by the `SPARSEIR_DEBUG` environment
2//! variable.
3
4use std::ffi::OsStr;
5
6/// Environment variable that enables debug diagnostics.
7const DEBUG_ENV_VAR: &str = "SPARSEIR_DEBUG";
8
9/// Values of [`DEBUG_ENV_VAR`] that enable debug diagnostics, compared ASCII
10/// case-insensitively. pylibsparseir accepts the same values.
11const ENABLED_VALUES: [&str; 4] = ["1", "true", "yes", "on"];
12
13/// Returns `true` if the `SPARSEIR_DEBUG` environment variable enables debug
14/// diagnostics.
15///
16/// Debug diagnostics are enabled only when `SPARSEIR_DEBUG` is `1`, `true`,
17/// `yes` or `on`, in any letter case, the same values pylibsparseir accepts.
18/// Any other value, including `0`, `false`, an empty string, or an accepted
19/// value with surrounding whitespace, leaves them disabled, as does an unset
20/// variable.
21///
22/// The variable is read on every call. [`debug_warn!`](crate::debug_warn!)
23/// and the debug macros of `sparse-ir-capi` all use this function.
24pub fn is_debug_enabled() -> bool {
25    enables_debug(std::env::var_os(DEBUG_ENV_VAR).as_deref())
26}
27
28/// Whether a value of `SPARSEIR_DEBUG` (`None` if the variable is unset)
29/// enables debug diagnostics.
30fn enables_debug(value: Option<&OsStr>) -> bool {
31    // A value that is not valid Unicode cannot equal an accepted value.
32    value.and_then(OsStr::to_str).is_some_and(|value| {
33        ENABLED_VALUES
34            .iter()
35            .any(|enabled| value.eq_ignore_ascii_case(enabled))
36    })
37}
38
39#[cfg(test)]
40#[path = "debug_tests.rs"]
41mod debug_tests;