use super::*;
#[derive(Clone)]
pub struct Cancellation(pub(super) Rc<CancellationState>);
pub(super) struct CancellationState {
cancelled: Cell<bool>,
reason: Cell<&'static str>,
send: RefCell<Option<oneshot::Sender<()>>>,
wait: Shared<LocalBoxFuture<'static, ()>>,
}
pub type ResourceSignal = Cancellation;
impl Cancellation {
pub(super) fn new(reason: &'static str) -> Self {
let (send, receive) = oneshot::channel();
Self(Rc::new(CancellationState {
cancelled: Cell::new(false),
reason: Cell::new(reason),
send: RefCell::new(Some(send)),
wait: async move {
let _ = receive.await;
}
.boxed_local()
.shared(),
}))
}
pub(super) fn cancel(&self) {
self.0.cancelled.set(true);
if let Some(send) = self.0.send.borrow_mut().take() {
let _ = send.send(());
}
}
pub(super) fn cancel_because(&self, reason: &'static str) {
if !self.0.cancelled.get() {
self.0.reason.set(reason);
}
self.0.cancelled.set(true);
if let Some(send) = self.0.send.borrow_mut().take() {
let _ = send.send(());
}
}
pub fn is_cancelled(&self) -> bool {
self.0.cancelled.get()
}
pub fn check(&self) -> Result<()> {
if self.is_cancelled() {
Err(Error::new(
core::Code::Cancelled,
self.0.reason.get(),
"operation was cancelled",
))
} else {
Ok(())
}
}
pub async fn cancelled(&self) {
self.0.wait.clone().await;
}
}
#[derive(Clone)]
pub struct ResourceKey {
pub(super) host: Host,
pub(super) id: core::Id,
pub(super) name: Rc<str>,
pub(super) version: u32,
}
pub struct Resource<T> {
pub(super) key: ResourceKey,
pub(super) marker: std::marker::PhantomData<T>,
}
impl<T: 'static> Resource<T> {
pub fn key(&self) -> ResourceKey {
self.key.clone()
}
pub fn value(&self) -> Result<Rc<T>> {
let host = &self.key.host;
let id = host.kernel().resource_value(self.key.id)?;
let value = host
.0
.values
.borrow()
.get(&id)
.map(|record| record.value.clone())
.ok_or_else(|| {
Error::new(
core::Code::Gone,
Reason::Resource,
format!("the value of the resource `{}` was released", self.key.name),
)
})?;
value.downcast().map_err(|_| {
Error::invalid(
Reason::RustType,
format!(
"the resource `{}` holds a value of another Rust type than the one it is \
read as",
self.key.name
),
)
})
}
}
impl<T> Clone for Resource<T> {
fn clone(&self) -> Self {
Self {
key: self.key.clone(),
marker: std::marker::PhantomData,
}
}
}
impl<T> Resource<T> {
pub fn version(&self) -> u32 {
self.key.version
}
}