use async_channel::Sender;
use std::{cell::RefCell, sync::atomic::AtomicUsize, sync::atomic::Ordering};
use super::arbiter::{Arbiter, SystemCommand};
use super::builder::{Builder, SystemRunner};
static SYSTEM_COUNT: AtomicUsize = AtomicUsize::new(0);
#[derive(Clone, Debug)]
pub struct System {
id: usize,
sys: Sender<SystemCommand>,
arbiter: Arbiter,
stop_on_panic: bool,
}
thread_local!(
static CURRENT: RefCell<Option<System>> = const { RefCell::new(None) };
);
impl System {
pub(super) fn construct(
sys: Sender<SystemCommand>,
arbiter: Arbiter,
stop_on_panic: bool,
) -> Self {
let sys = System {
sys,
arbiter,
stop_on_panic,
id: SYSTEM_COUNT.fetch_add(1, Ordering::SeqCst),
};
System::set_current(sys.clone());
sys
}
pub fn build() -> Builder {
Builder::new()
}
#[allow(clippy::new_ret_no_self)]
pub fn new(name: &str) -> SystemRunner {
Self::build().name(name).finish()
}
pub fn current() -> System {
CURRENT.with(|cell| match *cell.borrow() {
Some(ref sys) => sys.clone(),
None => panic!("System is not running"),
})
}
#[doc(hidden)]
pub fn set_current(sys: System) {
CURRENT.with(|s| {
*s.borrow_mut() = Some(sys);
})
}
pub fn id(&self) -> usize {
self.id
}
pub fn stop(&self) {
self.stop_with_code(0)
}
pub fn stop_with_code(&self, code: i32) {
let _ = self.sys.try_send(SystemCommand::Exit(code));
}
pub(super) fn sys(&self) -> &Sender<SystemCommand> {
&self.sys
}
pub fn stop_on_panic(&self) -> bool {
self.stop_on_panic
}
pub fn arbiter(&self) -> &Arbiter {
&self.arbiter
}
}