switch.rs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //! The `VICTORY_*` on/off switches (`VICTORY_D3D12_DEBUG=1` and its siblings).
  2. use std::ffi::OsStr;
  3. /// Whether a switch's value turns it on: it is set, and is not `0`.
  4. ///
  5. /// A switch used to be on whenever its variable existed, so `VICTORY_D3D12_WARP=0` (typed to switch it off, or left
  6. /// over from comparing two runs) still selected the software adapter. Any other value keeps the old meaning.
  7. fn value_is_on(value: Option<&OsStr>) -> bool {
  8. value.is_some_and(|v| v != "0")
  9. }
  10. /// Whether the environment variable `name` switches something on.
  11. pub(crate) fn on(name: &str) -> bool {
  12. value_is_on(std::env::var_os(name).as_deref())
  13. }
  14. /// A switch that is on unless its variable is `0`, read once; with
  15. /// `VICTORY_AB` naming it (diagnostics builds, `crate::ab`), on and off while
  16. /// the title runs.
  17. #[cfg(windows)]
  18. #[macro_export]
  19. #[doc(hidden)]
  20. macro_rules! toggled {
  21. ($name:literal) => {{
  22. #[cfg(feature = "diagnostics")]
  23. {
  24. static BIT: std::sync::OnceLock<Result<bool, u32>> = std::sync::OnceLock::new();
  25. match BIT.get_or_init(|| match $crate::ab::bit($name) {
  26. Some(bit) => Err(bit),
  27. None => Ok(std::env::var_os($name).is_none_or(|v| v != "0")),
  28. }) {
  29. Ok(on) => *on,
  30. Err(bit) => $crate::ab::on(*bit),
  31. }
  32. }
  33. #[cfg(not(feature = "diagnostics"))]
  34. {
  35. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  36. *ON.get_or_init(|| std::env::var_os($name).is_none_or(|v| v != "0"))
  37. }
  38. }};
  39. }
  40. #[cfg(test)]
  41. mod tests {
  42. use super::value_is_on;
  43. use std::ffi::OsStr;
  44. #[test]
  45. fn unset_is_off() {
  46. assert!(!value_is_on(None));
  47. }
  48. #[test]
  49. fn zero_is_off() {
  50. assert!(!value_is_on(Some(OsStr::new("0"))));
  51. }
  52. #[test]
  53. fn one_is_on() {
  54. assert!(value_is_on(Some(OsStr::new("1"))));
  55. }
  56. #[test]
  57. fn other_values_keep_their_old_meaning() {
  58. // Documented as `=1`; anything else that was on before stays on: only `0` is new.
  59. for value in ["", "true", "yes", "2", "00", " 0", "0 "] {
  60. assert!(value_is_on(Some(OsStr::new(value))), "{value:?}");
  61. }
  62. }
  63. }