Skip to content

Commit 1e173e5

Browse files
committed
Remove unsafe code in favor of OnceLock
This also simplifies the code a bit
1 parent 5973c20 commit 1e173e5

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

src/lib.rs

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,8 @@
2323
//! ```
2424
#![allow(clippy::bool_to_int_with_if)]
2525

26-
use std::cell::UnsafeCell;
2726
use std::env;
28-
use std::sync::Once;
27+
use std::sync::OnceLock;
2928

3029
/// possible stream sources
3130
#[derive(Clone, Copy, Debug)]
@@ -159,16 +158,6 @@ pub fn on(stream: Stream) -> Option<ColorLevel> {
159158
translate_level(supports_color(stream))
160159
}
161160

162-
struct CacheCell(UnsafeCell<Option<ColorLevel>>);
163-
164-
unsafe impl Sync for CacheCell {}
165-
166-
static INIT: [Once; 2] = [Once::new(), Once::new()];
167-
static ON_CACHE: [CacheCell; 2] = [
168-
CacheCell(UnsafeCell::new(None)),
169-
CacheCell(UnsafeCell::new(None)),
170-
];
171-
172161
macro_rules! assert_stream_in_bounds {
173162
($($variant:ident)*) => {
174163
$(
@@ -187,12 +176,10 @@ be returned from then on.
187176
If you expect your environment to change between calls, use [`on`]
188177
*/
189178
pub fn on_cached(stream: Stream) -> Option<ColorLevel> {
190-
let stream_index = stream as usize;
191-
INIT[stream_index].call_once(|| unsafe {
192-
*ON_CACHE[stream_index].0.get() = translate_level(supports_color(stream));
193-
});
179+
static CACHE: [OnceLock<Option<ColorLevel>>; 2] = [OnceLock::new(), OnceLock::new()];
194180

195-
unsafe { *ON_CACHE[stream_index].0.get() }
181+
let stream_index = stream as usize;
182+
*CACHE[stream_index].get_or_init(|| translate_level(supports_color(stream)))
196183
}
197184

198185
/**
@@ -254,6 +241,22 @@ mod tests {
254241
assert_eq!(on(Stream::Stdout), None);
255242
}
256243

244+
#[test]
245+
#[cfg_attr(miri, ignore)]
246+
fn test_on_cached() {
247+
let _test_guard = TEST_LOCK.lock().unwrap();
248+
set_up();
249+
env::set_var("IGNORE_IS_TERMINAL", "1");
250+
251+
env::set_var("CLICOLOR", "1");
252+
assert!(on(Stream::Stdout).is_some());
253+
assert!(on_cached(Stream::Stdout).is_some());
254+
255+
env::set_var("CLICOLOR", "0");
256+
assert!(on(Stream::Stdout).is_none());
257+
assert!(on_cached(Stream::Stdout).is_some());
258+
}
259+
257260
#[test]
258261
#[cfg_attr(miri, ignore)]
259262
fn test_clicolor_force_ansi() {

0 commit comments

Comments
 (0)