-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathlib.rs
More file actions
56 lines (48 loc) · 1.47 KB
/
Copy pathlib.rs
File metadata and controls
56 lines (48 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
pub mod config;
pub mod error;
use std::cell::RefCell;
use std::sync::OnceLock;
use bevy::app::App;
use tracing::debug;
static IS_INIT: OnceLock<()> = OnceLock::new();
thread_local! {
static APP: RefCell<Option<App>> = const { RefCell::new(None) };
}
pub fn app_mut<T>(cb: impl FnOnce(&mut App) -> error::Result<T>) -> error::Result<T> {
// `try_with` so a `Drop` running after the TLS is destroyed sees an
// `AppAccess` error rather than panicking
let res = APP.try_with(|app_cell| {
let mut app_borrow = app_cell
.try_borrow_mut()
.map_err(|_| error::ProcessingError::AppAccess)?;
let app = app_borrow
.as_mut()
.ok_or(error::ProcessingError::AppAccess)?;
cb(app)
});
match res {
Ok(inner) => inner,
Err(_) => Err(error::ProcessingError::AppAccess),
}
}
pub fn is_already_init() -> error::Result<bool> {
let is_init = IS_INIT.get().is_some();
let thread_has_app = APP.with(|app_cell| app_cell.borrow().is_some());
if is_init && !thread_has_app {
return Err(error::ProcessingError::AppAccess);
}
if is_init && thread_has_app {
debug!("App already initialized");
return Ok(true);
}
Ok(false)
}
pub fn set_app(app: App) {
APP.with(|app_cell| {
IS_INIT.get_or_init(|| ());
*app_cell.borrow_mut() = Some(app);
});
}
pub fn take_app() -> Option<App> {
APP.with(|app_cell| app_cell.borrow_mut().take())
}