use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use std::any::Any;
use std::cell::RefCell;
use std::collections::HashMap;
use super::Archivable;
pub(crate) struct Record {
pub id: u32,
pub tag: &'static str,
pub payload: Vec<u8>,
}
enum Slot {
Reserved(&'static str),
Written(Record),
}
#[derive(Default)]
struct WriteScope {
seen: HashMap<usize, u32>,
slots: Vec<Slot>,
order: Vec<u32>,
}
#[derive(Default)]
struct ReadScope {
objects: HashMap<u32, (String, Box<dyn Any + Send + Sync>)>,
}
thread_local! {
static WRITING: RefCell<Option<WriteScope>> = const { RefCell::new(None) };
static READING: RefCell<Option<ReadScope>> = const { RefCell::new(None) };
}
fn no_scope() -> PyrucastError {
PyrucastError::Message(
"a Handle can only be serialized inside an archive: its value is an \
address, which means nothing outside this process. Use \
archive::save / archive::load."
.into(),
)
}
pub(crate) fn with_write<R>(f: impl FnOnce() -> Result<R>) -> Result<(R, Vec<Record>)> {
WRITING.with(|w| *w.borrow_mut() = Some(WriteScope::default()));
let out = f();
let scope = WRITING.with(|w| w.borrow_mut().take());
let value = out?;
let mut scope = scope.expect("the write scope is installed just above");
let mut records = Vec::with_capacity(scope.order.len());
for id in std::mem::take(&mut scope.order) {
match std::mem::replace(&mut scope.slots[id as usize], Slot::Reserved("taken")) {
Slot::Written(r) => records.push(r),
Slot::Reserved(tag) => unreachable!("record for {tag} was never deposited"),
}
}
Ok((value, records))
}
pub(crate) fn intern_handle<T: Archivable>(h: &Handle<T>) -> Result<u32> {
let key = h.id();
let known = WRITING.with(|w| -> Result<Option<u32>> {
let mut b = w.borrow_mut();
let scope = b.as_mut().ok_or_else(no_scope)?;
Ok(scope.seen.get(&key).copied())
})?;
if let Some(id) = known {
let complete = WRITING.with(|w| {
matches!(
w.borrow().as_ref().map(|s| &s.slots[id as usize]),
Some(Slot::Written(_))
)
});
if !complete {
return Err(PyrucastError::Message(format!(
"the object graph has a cycle: {h} refers back to itself \
through its own contents. Only recomputable caches may point \
backwards, and caches are not written."
)));
}
return Ok(id);
}
let id = WRITING.with(|w| -> Result<u32> {
let mut b = w.borrow_mut();
let scope = b.as_mut().ok_or_else(no_scope)?;
let id = u32::try_from(scope.slots.len()).map_err(|_| {
PyrucastError::Message("more than 4 billion objects in one archive".into())
})?;
scope.seen.insert(key, id);
scope.slots.push(Slot::Reserved(T::TAG));
Ok(id)
})?;
let payload = h.read().to_bytes()?;
WRITING.with(|w| {
if let Some(scope) = w.borrow_mut().as_mut() {
scope.slots[id as usize] = Slot::Written(Record {
id,
tag: T::TAG,
payload,
});
scope.order.push(id);
}
});
Ok(id)
}
pub(crate) fn with_read<R>(f: impl FnOnce() -> Result<R>) -> Result<R> {
READING.with(|r| *r.borrow_mut() = Some(ReadScope::default()));
let out = f();
READING.with(|r| *r.borrow_mut() = None);
out
}
pub(crate) fn publish(id: u32, tag: String, object: Box<dyn Any + Send + Sync>) -> Result<()> {
READING.with(|r| {
let mut b = r.borrow_mut();
let scope = b.as_mut().ok_or_else(no_scope)?;
scope.objects.insert(id, (tag, object));
Ok(())
})
}
pub(crate) fn tag_of(id: u32) -> Result<String> {
READING.with(|r| {
let b = r.borrow();
let scope = b.as_ref().ok_or_else(no_scope)?;
scope
.objects
.get(&id)
.map(|(tag, _)| tag.clone())
.ok_or_else(|| {
PyrucastError::Message(format!("archive: root points at unknown object #{id}"))
})
})
}
pub(crate) fn resolve<T: Archivable>(id: u32) -> Result<Handle<T>> {
READING.with(|r| {
let b = r.borrow();
let scope = b.as_ref().ok_or_else(no_scope)?;
let (_, any) = scope.objects.get(&id).ok_or_else(|| {
PyrucastError::Message(format!(
"archive: object #{id} is referenced before it is defined — \
the file is damaged or was written by another tool"
))
})?;
any.downcast_ref::<Handle<T>>().cloned().ok_or_else(|| {
PyrucastError::Message(format!(
"archive: object #{id} is not a {} — the file is damaged",
T::TAG
))
})
})
}
pub(crate) fn with_object<R>(id: u32, f: impl FnOnce(&(dyn Any + Send + Sync)) -> R) -> Result<R> {
READING.with(|r| {
let b = r.borrow();
let scope = b.as_ref().ok_or_else(no_scope)?;
let (_, any) = scope.objects.get(&id).ok_or_else(|| {
PyrucastError::Message(format!("archive: root points at unknown object #{id}"))
})?;
Ok(f(any.as_ref()))
})
}
impl<T: Archivable> serde::Serialize for Handle<T> {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::Error;
let id = intern_handle(self).map_err(S::Error::custom)?;
s.serialize_u32(id)
}
}
impl<'de, T: Archivable> serde::Deserialize<'de> for Handle<T> {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
use serde::de::Error;
let id = u32::deserialize(d)?;
resolve::<T>(id).map_err(D::Error::custom)
}
}