use std::{fmt, sync::Arc};
#[derive(Clone, Debug, Default)]
pub struct Generation(Arc<()>);
impl Generation {
pub fn new() -> Self {
Self::default()
}
pub fn bind<T>(&self, value: T) -> GenerationValue<T> {
GenerationValue {
generation: self.clone(),
value,
}
}
}
pub struct GenerationValue<T> {
generation: Generation,
value: T,
}
impl<T> GenerationValue<T> {
pub fn get(&self, current: &Generation) -> Result<&T, GenerationMismatch> {
if Arc::ptr_eq(&self.generation.0, ¤t.0) {
Ok(&self.value)
} else {
Err(GenerationMismatch)
}
}
}
impl<T> fmt::Debug for GenerationValue<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("GenerationValue(<redacted>)")
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GenerationMismatch;
impl fmt::Display for GenerationMismatch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("value belongs to a different resource generation")
}
}
impl std::error::Error for GenerationMismatch {}