23
23
//! ```
24
24
#![ allow( clippy:: bool_to_int_with_if) ]
25
25
26
- use std:: cell:: UnsafeCell ;
27
26
use std:: env;
28
- use std:: sync:: Once ;
27
+ use std:: sync:: OnceLock ;
29
28
30
29
/// possible stream sources
31
30
#[ derive( Clone , Copy , Debug ) ]
@@ -159,16 +158,6 @@ pub fn on(stream: Stream) -> Option<ColorLevel> {
159
158
translate_level ( supports_color ( stream) )
160
159
}
161
160
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
-
172
161
macro_rules! assert_stream_in_bounds {
173
162
( $( $variant: ident) * ) => {
174
163
$(
@@ -187,12 +176,10 @@ be returned from then on.
187
176
If you expect your environment to change between calls, use [`on`]
188
177
*/
189
178
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 ( ) ] ;
194
180
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) ) )
196
183
}
197
184
198
185
/**
@@ -254,6 +241,22 @@ mod tests {
254
241
assert_eq ! ( on( Stream :: Stdout ) , None ) ;
255
242
}
256
243
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
+
257
260
#[ test]
258
261
#[ cfg_attr( miri, ignore) ]
259
262
fn test_clicolor_force_ansi ( ) {
0 commit comments