use std::cell::{Cell, RefCell};
use std::rc::{Rc, Weak};
use crate::{Container, ContainerError, Sharing};
struct Cached<P: ?Sized> {
epoch: u64,
port: Rc<P>,
}
pub struct PortCell<P: ?Sized + 'static> {
container: Weak<Container>,
epoch: Rc<Cell<u64>>,
key: &'static str,
cache: RefCell<Option<Cached<P>>>,
}
impl<P: ?Sized + 'static> PortCell<P> {
pub fn new(container: &Rc<Container>, key: &'static str) -> PortCell<P> {
PortCell {
container: Rc::downgrade(container),
epoch: container.epoch_cell(),
key,
cache: RefCell::new(None),
}
}
pub fn key(&self) -> &'static str {
self.key
}
pub fn get(&self) -> Rc<P> {
if self.container.strong_count() == 0 {
panic!("port {}: the container was dropped", self.key);
}
match self.try_get() {
Ok(port) => port,
Err(err) => panic!("port {}: {err}", self.key),
}
}
pub fn with<R>(&self, f: impl FnOnce(&P) -> R) -> R {
{
let cache = self.cache.borrow();
if let Some(hit) = cache.as_ref()
&& hit.epoch == self.epoch.get()
{
return f(&hit.port);
}
}
let port = self.get();
f(&port)
}
pub fn try_get(&self) -> Result<Rc<P>, ContainerError> {
let Some(container) = self.container.upgrade() else {
return Err(ContainerError::Unresolvable(
self.key.to_string(),
"the container was dropped".to_string(),
));
};
let epoch = self.epoch.get();
if let Some(hit) = self.cache.borrow().as_ref()
&& hit.epoch == epoch
{
return Ok(hit.port.clone());
}
let port = container.make_port::<P>(self.key)?;
let cached = if container.is_foreign(self.key) {
None
} else {
match container.sharing(self.key) {
Some(Sharing::Transient) | None => None,
Some(_) => Some(Cached {
epoch,
port: port.clone(),
}),
}
};
if let Ok(mut cache) = self.cache.try_borrow_mut() {
*cache = cached;
}
Ok(port)
}
}