Skip to content

Commit

Permalink
Extract a set-exactly-once boolean value
Browse files Browse the repository at this point in the history
  • Loading branch information
shepmaster committed Oct 21, 2022
1 parent 35dcf44 commit e491da4
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 16 deletions.
26 changes: 10 additions & 16 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,9 @@ mod backtrace_shim;
))]
pub use crate::backtrace_shim::*;

#[cfg(any(feature = "std", test))]
mod once_bool;

#[cfg(feature = "backtraces-impl-backtrace-crate")]
pub use backtrace::Backtrace;

Expand Down Expand Up @@ -1216,26 +1219,17 @@ impl AsBacktrace for Option<Backtrace> {

#[cfg(any(feature = "std", test))]
fn backtrace_collection_enabled() -> bool {
use std::{
env,
sync::{
atomic::{AtomicBool, Ordering},
Once,
},
};
use crate::once_bool::OnceBool;
use std::env;

static START: Once = Once::new();
static ENABLED: AtomicBool = AtomicBool::new(false);
static ENABLED: OnceBool = OnceBool::new();

START.call_once(|| {
ENABLED.get(|| {
// TODO: What values count as "true"?
let enabled = env::var_os("RUST_LIB_BACKTRACE")
env::var_os("RUST_LIB_BACKTRACE")
.or_else(|| env::var_os("RUST_BACKTRACE"))
.map_or(false, |v| v == "1");
ENABLED.store(enabled, Ordering::SeqCst);
});

ENABLED.load(Ordering::SeqCst)
.map_or(false, |v| v == "1")
})
}

#[cfg(feature = "backtraces-impl-backtrace-crate")]
Expand Down
27 changes: 27 additions & 0 deletions src/once_bool.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use std::sync::{
atomic::{AtomicBool, Ordering},
Once,
};

pub struct OnceBool {
start: Once,
enabled: AtomicBool,
}

impl OnceBool {
pub const fn new() -> Self {
Self {
start: Once::new(),
enabled: AtomicBool::new(false),
}
}

pub fn get<F: FnOnce() -> bool>(&self, f: F) -> bool {
self.start.call_once(|| {
let enabled = f();
self.enabled.store(enabled, Ordering::SeqCst);
});

self.enabled.load(Ordering::SeqCst)
}
}

0 comments on commit e491da4

Please sign in to comment.