use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::any::{Any, TypeId};
use core::fmt;
use core::marker::PhantomData;
use hashbrown::HashMap;
use crate::engine::{DescentGuard, StdDescentGuard, StdDescentGuardInit};
use super::super::error::{DeserializeError, RegistrationError, SerializeError};
use super::super::object::SerializableLang;
use super::super::value::{SerialEntry, SerialIndex, SerialValue, TableId};
use super::super::wire::{FromSerialValue, ToSerialValue};
use super::context::{DeserializeContext, SerializeContext};
use super::driver::{ObjectSerdeDriver, TableHandle};
use super::segment::{check_entry_nesting, Segment, SegmentMeta, SegmentTable, WireEntry};
pub struct SerdeSession<L: SerializableLang> {
tables: Vec<TableState<L>>,
user_data: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
profile: Option<String>,
descent_guard_init: StdDescentGuardInit,
write_stack: Vec<(usize, usize)>,
memo_journal: Vec<(usize, String)>,
lang: PhantomData<fn() -> L>,
}
pub(super) struct TableState<L: SerializableLang> {
name: &'static str,
homogeneous: Option<&'static str>,
driver: Arc<dyn Any + Send + Sync>,
driver_type: TypeId,
materialize: MaterializeFn<L>,
slots: Vec<Slot>,
by_pointer: HashMap<usize, u32>,
outbox: Vec<SerialValue>,
pub(super) registry: Option<Box<dyn TableRegistry>>,
}
pub(crate) trait TableRegistry: Any + Send + Sync {
fn as_any_mut(&mut self) -> &mut (dyn Any + Send + Sync);
fn forget_memo(&mut self, identifier: &str);
}
enum Slot {
Pending(SerialValue),
InProgress,
Materialized(Box<dyn Any + Send + Sync>),
}
impl Slot {
fn is_materialized(&self) -> bool {
matches!(self, Slot::Materialized(_))
}
}
type MaterializeFn<L> = fn(
&mut SerdeSession<L>,
&mut StdDescentGuard,
usize,
u32,
Option<(usize, u32)>,
) -> Result<(), DeserializeError>;
fn address<T: ?Sized>(object: &Arc<T>) -> usize {
Arc::as_ptr(object) as *const () as usize
}
impl<L: SerializableLang> SerdeSession<L> {
pub fn empty() -> SerdeSession<L> {
SerdeSession {
tables: Vec::new(),
user_data: HashMap::new(),
profile: None,
descent_guard_init: StdDescentGuardInit::default(),
write_stack: Vec::new(),
memo_journal: Vec::new(),
lang: PhantomData,
}
}
pub fn with_descent_guard_init(mut self, init: StdDescentGuardInit) -> SerdeSession<L> {
self.descent_guard_init = init;
self
}
pub fn set_profile(&mut self, profile: impl Into<String>) {
self.profile = Some(profile.into());
}
pub fn profile(&self) -> Option<&str> {
self.profile.as_deref()
}
pub fn register_table<D: ObjectSerdeDriver<L>>(
&mut self,
driver: D,
) -> Result<TableHandle<D>, RegistrationError> {
let name = driver.table_name();
if self.tables.iter().any(|table| table.name == name) {
return Err(RegistrationError::DuplicateTableName { name });
}
if driver.homogeneous_identifier() == Some("") {
return Err(RegistrationError::EmptyHomogeneousIdentifier { table: name });
}
let ordinal = u32::try_from(self.tables.len()).map_err(|_| RegistrationError::TooManyTables)?;
if ordinal == u32::MAX {
return Err(RegistrationError::TooManyTables);
}
self.tables.push(TableState {
name,
homogeneous: driver.homogeneous_identifier(),
driver: Arc::new(driver),
driver_type: TypeId::of::<D>(),
materialize: materialize_erased::<L, D>,
slots: Vec::new(),
by_pointer: HashMap::new(),
outbox: Vec::new(),
registry: None,
});
Ok(TableHandle::new(TableId::new(ordinal)))
}
pub fn table_handle<D: ObjectSerdeDriver<L>>(&self, name: &str) -> Option<TableHandle<D>> {
let ordinal = self.table_ordinal_by_name(name)?;
let table = self.tables.get(ordinal)?;
(table.driver_type == TypeId::of::<D>()).then(|| TableHandle::new(TableId::new(ordinal as u32)))
}
pub(crate) fn table_index<D: 'static>(&self, handle: TableHandle<D>) -> Result<usize, TableId> {
let ordinal = usize::try_from(handle.id().ordinal()).map_err(|_| handle.id())?;
match self.tables.get(ordinal) {
Some(table) if table.driver_type == handle.driver_type_id() => Ok(ordinal),
_ => Err(handle.id()),
}
}
pub(crate) fn table_name(&self, ordinal: usize) -> &'static str {
self.tables.get(ordinal).map_or("?", |table| table.name)
}
pub(crate) fn table_ordinal_by_name(&self, name: &str) -> Option<usize> {
self.tables.iter().position(|table| table.name == name)
}
pub(crate) fn registry_mut<R: TableRegistry + Default>(&mut self, ordinal: usize) -> Option<&mut R> {
let table = self.tables.get_mut(ordinal)?;
table
.registry
.get_or_insert_with(|| Box::new(R::default()) as Box<dyn TableRegistry>)
.as_any_mut()
.downcast_mut::<R>()
}
pub(super) fn record_memo(&mut self, ordinal: usize, identifier: &str) {
self.memo_journal.push((ordinal, String::from(identifier)));
}
pub fn set_user_data<T: Any + Send + Sync>(&mut self, data: T) {
self.user_data.insert(TypeId::of::<T>(), Box::new(data));
}
pub fn user_data<T: Any>(&self) -> Option<&T> {
self.user_data.get(&TypeId::of::<T>())?.downcast_ref::<T>()
}
pub fn intern<D: ObjectSerdeDriver<L>>(
&mut self,
table: TableHandle<D>,
object: &Arc<D::Object>,
) -> Result<D::Index, SerializeError> {
let mut guard = StdDescentGuard::init(&self.descent_guard_init);
self.intern_with_guard(&mut guard, table, object)
}
pub(super) fn intern_with_guard<D: ObjectSerdeDriver<L>>(
&mut self,
guard: &mut StdDescentGuard,
table: TableHandle<D>,
object: &Arc<D::Object>,
) -> Result<D::Index, SerializeError> {
let ordinal = self.table_index(table).map_err(|table| SerializeError::UnknownTable { table })?;
let table_id = TableId::new(ordinal as u32);
let name = self.tables[ordinal].name;
let pointer = address(object);
if let Some(&position) = self.tables[ordinal].by_pointer.get(&pointer) {
return Ok(D::Index::from_parts(table_id, position));
}
if self.write_stack.iter().any(|&(t, p)| t == ordinal && p == pointer) {
let referrer = self.write_stack.last().map_or(name, |&(t, _)| self.tables[t].name);
return Err(SerializeError::ReferenceCycle { table: name, referrer });
}
if let Err(refusal) = guard.try_enter() {
return Err(SerializeError::DescentLimitExceeded { detail: refusal.detail });
}
self.write_stack.push((ordinal, pointer));
let result = match self.driver::<D>(ordinal) {
Some(driver) => {
let mut cx = SerializeContext::new(self, guard);
driver.serialize_object(object, &mut cx)
}
None => Err(SerializeError::UnknownTable { table: table_id }),
};
self.write_stack.pop();
guard.exit();
let entry = result.map_err(|error| error.in_table(name))?;
let state = &mut self.tables[ordinal];
let wire = match state.homogeneous {
Some(expected) => {
if entry.identifier != expected {
return Err(SerializeError::UnexpectedIdentifier {
table: name,
expected,
found: String::from(&*entry.identifier),
});
}
entry.data
}
None => WireEntry { identifier: entry.identifier, data: entry.data }.to_serial_value()?,
};
check_entry_nesting(&wire).map_err(|error| SerializeError::from(error).in_table(name))?;
let position = u32::try_from(state.slots.len()).map_err(|_| SerializeError::TableFull { table: name })?;
if position == u32::MAX {
return Err(SerializeError::TableFull { table: name });
}
state.slots.push(Slot::Materialized(Box::new(object.clone())));
state.by_pointer.insert(pointer, position);
state.outbox.push(wire);
Ok(D::Index::from_parts(table_id, position))
}
fn driver<D: ObjectSerdeDriver<L>>(&self, ordinal: usize) -> Option<Arc<D>> {
Arc::clone(&self.tables.get(ordinal)?.driver).downcast::<D>().ok()
}
pub fn take_segment(&mut self) -> Segment {
self.emit_segment(None)
}
pub fn take_segment_with_main(&mut self, main: impl SerialIndex) -> Result<Segment, SerializeError> {
let table = self
.tables
.get(main.table().ordinal() as usize)
.ok_or(SerializeError::UnknownTable { table: main.table() })?;
let len = table.slots.len() as u32;
if main.index() >= len {
return Err(SerializeError::IndexOutOfRange { table: table.name, index: main.index(), len });
}
Ok(self.emit_segment(Some((main.table(), main.index()))))
}
fn emit_segment(&mut self, main: Option<(TableId, u32)>) -> Segment {
let tables = self
.tables
.iter_mut()
.enumerate()
.map(|(ordinal, table)| {
let entries = core::mem::take(&mut table.outbox);
debug_assert!(entries.len() <= table.slots.len(), "the outbox is the tail of the slots");
let start = table.slots.len().saturating_sub(entries.len()) as u32;
SegmentTable::new(String::from(table.name), TableId::new(ordinal as u32), start, entries)
})
.collect();
Segment::new(Segment::VERSION, SegmentMeta::new(self.profile.clone()), tables, main)
}
pub fn push_segment(&mut self, segment: Segment) -> Result<Option<(TableId, u32)>, DeserializeError> {
let (version, meta, tables, main) = segment.into_parts();
if version != Segment::VERSION {
return Err(DeserializeError::UnsupportedVersion { found: version, expected: Segment::VERSION });
}
if let Some(expected) = &self.profile {
if meta.profile() != Some(expected.as_str()) {
return Err(DeserializeError::ProfileMismatch {
expected: expected.clone(),
found: meta.profile().map(String::from),
});
}
}
if let Some(table) = self.tables.iter().find(|table| !table.outbox.is_empty()) {
return Err(DeserializeError::UnemittedEntries { table: table.name });
}
let mut writer_to_reader: HashMap<u32, usize> = HashMap::new();
let mut planned: Vec<(usize, Vec<SerialValue>)> = Vec::with_capacity(tables.len());
for segment_table in tables {
let (name, id, start, entries) = segment_table.into_parts();
let ordinal = self
.tables
.iter()
.position(|table| table.name == name)
.ok_or_else(|| DeserializeError::UnknownTableName { name: name.clone() })?;
if planned.iter().any(|(t, _)| *t == ordinal) {
return Err(DeserializeError::DuplicateSegmentTable { name });
}
if writer_to_reader.insert(id.ordinal(), ordinal).is_some() {
return Err(DeserializeError::DuplicateSegmentTable { name });
}
let table = &self.tables[ordinal];
let len = table.slots.len() as u32;
if start != len {
return Err(DeserializeError::SegmentOutOfOrder { table: table.name, expected: len, found: start });
}
let fits = u32::try_from(entries.len()).ok().and_then(|n| len.checked_add(n));
match fits {
Some(end) if end < u32::MAX => {}
_ => return Err(DeserializeError::TableFull { table: table.name }),
}
for (offset, entry) in entries.iter().enumerate() {
if let Err(error) = check_entry_nesting(entry) {
let position = len.saturating_add(u32::try_from(offset).unwrap_or(u32::MAX));
return Err(DeserializeError::from(error).in_entry(table.name, position, None));
}
}
planned.push((ordinal, entries));
}
for (_, entries) in &mut planned {
for entry in entries.iter_mut() {
translate_indices(entry, &writer_to_reader)?;
}
}
let main = match main {
None => None,
Some((table, index)) => {
let ordinal = *writer_to_reader
.get(&table.ordinal())
.ok_or(DeserializeError::UnknownWriterTable { table })?;
let appended = planned.iter().find(|(t, _)| *t == ordinal).map_or(0, |(_, entries)| entries.len());
let len = (self.tables[ordinal].slots.len() + appended) as u32;
if index >= len {
return Err(DeserializeError::IndexOutOfRange { table: self.tables[ordinal].name, index, len });
}
Some((TableId::new(ordinal as u32), index))
}
};
let old_lens: Vec<usize> = self.tables.iter().map(|table| table.slots.len()).collect();
for (ordinal, entries) in planned {
self.tables[ordinal].slots.extend(entries.into_iter().map(Slot::Pending));
}
self.memo_journal.clear();
let mut guard = StdDescentGuard::init(&self.descent_guard_init);
let result = self.materialize_new_entries(&mut guard, &old_lens);
let memoized = core::mem::take(&mut self.memo_journal);
if result.is_err() {
for (table, &old_len) in self.tables.iter_mut().zip(&old_lens) {
table.slots.truncate(old_len);
let old_len = old_len as u32;
table.by_pointer.retain(|_, position| *position < old_len);
}
for (ordinal, identifier) in memoized {
if let Some(registry) = self.tables.get_mut(ordinal).and_then(|table| table.registry.as_mut()) {
registry.forget_memo(&identifier);
}
}
}
result.map(|()| main)
}
fn materialize_new_entries(
&mut self,
guard: &mut StdDescentGuard,
old_lens: &[usize],
) -> Result<(), DeserializeError> {
for (ordinal, &old_len) in old_lens.iter().enumerate() {
let mut position = old_len;
while position < self.tables[ordinal].slots.len() {
if let Slot::Pending(_) = self.tables[ordinal].slots[position] {
let materialize = self.tables[ordinal].materialize;
materialize(self, guard, ordinal, position as u32, None)?;
}
position += 1;
}
}
for (ordinal, &old_len) in old_lens.iter().enumerate() {
let table = &self.tables[ordinal];
if let Some(offset) = table.slots[old_len..].iter().position(|slot| !slot.is_materialized()) {
return Err(DeserializeError::Internal {
detail: alloc::format!(
"entry #{} of table `{}` was left unrebuilt after the segment's entries were processed",
old_len.saturating_add(offset),
table.name
),
});
}
}
Ok(())
}
pub fn object<D: ObjectSerdeDriver<L>>(
&mut self,
table: TableHandle<D>,
index: D::Index,
) -> Result<Arc<D::Object>, DeserializeError> {
let mut guard = StdDescentGuard::init(&self.descent_guard_init);
self.object_with_guard(&mut guard, table, index, None)
}
pub(super) fn object_with_guard<D: ObjectSerdeDriver<L>>(
&mut self,
guard: &mut StdDescentGuard,
table: TableHandle<D>,
index: D::Index,
referrer: Option<(usize, u32)>,
) -> Result<Arc<D::Object>, DeserializeError> {
let ordinal = self.table_index(table).map_err(|table| DeserializeError::UnknownTable { table })?;
let name = self.tables[ordinal].name;
if index.table() != table.id() {
return Err(DeserializeError::WrongTable { expected: name, found: index.table() });
}
let position = index.index();
let len = self.tables[ordinal].slots.len() as u32;
if position >= len {
return Err(DeserializeError::IndexOutOfRange { table: name, index: position, len });
}
materialize::<L, D>(self, guard, ordinal, position, referrer)
}
#[cfg(test)]
pub(super) fn table_len(&self, ordinal: usize) -> usize {
self.tables[ordinal].slots.len()
}
}
fn materialize<L: SerializableLang, D: ObjectSerdeDriver<L>>(
session: &mut SerdeSession<L>,
guard: &mut StdDescentGuard,
ordinal: usize,
position: u32,
referrer: Option<(usize, u32)>,
) -> Result<Arc<D::Object>, DeserializeError> {
let name = session.tables[ordinal].name;
let table_id = TableId::new(ordinal as u32);
match session.tables[ordinal].slots.get(position as usize) {
Some(Slot::Materialized(object)) => {
return object
.downcast_ref::<Arc<D::Object>>()
.cloned()
.ok_or(DeserializeError::UnknownTable { table: table_id });
}
Some(Slot::InProgress) => {
let (referrer_table, referrer_index) = referrer.unwrap_or((ordinal, position));
return Err(DeserializeError::ReferenceCycle {
table: name,
index: position,
referrer_table: session.table_name(referrer_table),
referrer_index,
});
}
Some(Slot::Pending(_)) => {}
None => {
let len = session.tables[ordinal].slots.len() as u32;
return Err(DeserializeError::IndexOutOfRange { table: name, index: position, len });
}
}
if let Err(refusal) = guard.try_enter() {
return Err(DeserializeError::DescentLimitExceeded { detail: refusal.detail });
}
let result = materialize_entered::<L, D>(session, guard, ordinal, position);
guard.exit();
result
}
fn materialize_entered<L: SerializableLang, D: ObjectSerdeDriver<L>>(
session: &mut SerdeSession<L>,
guard: &mut StdDescentGuard,
ordinal: usize,
position: u32,
) -> Result<Arc<D::Object>, DeserializeError> {
let name = session.tables[ordinal].name;
let table_id = TableId::new(ordinal as u32);
let slot = &mut session.tables[ordinal].slots[position as usize];
let value = match core::mem::replace(slot, Slot::InProgress) {
Slot::Pending(value) => value,
other => {
*slot = other;
return Err(DeserializeError::IndexOutOfRange { table: name, index: position, len: 0 });
}
};
let (entry, stored) = match session.tables[ordinal].homogeneous {
Some(identifier) => (SerialEntry { identifier: Cow::Borrowed(identifier), data: value }, None),
None => match WireEntry::from_serial_value(&value) {
Ok(wire) => (SerialEntry { identifier: wire.identifier, data: wire.data }, Some(value)),
Err(error) => {
session.tables[ordinal].slots[position as usize] = Slot::Pending(value);
return Err(DeserializeError::from(error).in_entry(name, position, None));
}
},
};
let Some(driver) = session.driver::<D>(ordinal) else {
let SerialEntry { data, .. } = entry;
session.tables[ordinal].slots[position as usize] = Slot::Pending(stored.unwrap_or(data));
return Err(DeserializeError::UnknownTable { table: table_id });
};
let result = {
let mut cx = DeserializeContext::new(session, guard, Some((ordinal, position)));
driver.deserialize_object(&entry, &mut cx)
};
match result {
Ok(object) => {
let table = &mut session.tables[ordinal];
table.slots[position as usize] = Slot::Materialized(Box::new(object.clone()));
table.by_pointer.entry(address(&object)).or_insert(position);
Ok(object)
}
Err(error) => {
let SerialEntry { identifier, data } = entry;
session.tables[ordinal].slots[position as usize] = Slot::Pending(stored.unwrap_or(data));
Err(error.in_entry(name, position, Some(identifier)))
}
}
}
fn materialize_erased<L: SerializableLang, D: ObjectSerdeDriver<L>>(
session: &mut SerdeSession<L>,
guard: &mut StdDescentGuard,
ordinal: usize,
position: u32,
referrer: Option<(usize, u32)>,
) -> Result<(), DeserializeError> {
materialize::<L, D>(session, guard, ordinal, position, referrer).map(|_| ())
}
fn translate_indices(
value: &mut SerialValue,
writer_to_reader: &HashMap<u32, usize>,
) -> Result<(), DeserializeError> {
let mut pending: Vec<&mut SerialValue> = Vec::from([value]);
while let Some(value) = pending.pop() {
match value {
SerialValue::Index { table, .. } => {
let reader = writer_to_reader
.get(&table.ordinal())
.ok_or(DeserializeError::UnknownWriterTable { table: *table })?;
*table = TableId::new(*reader as u32);
}
SerialValue::List(items) => pending.extend(items.iter_mut()),
SerialValue::Map(entries) => pending.extend(entries.iter_mut().map(|(_, value)| value)),
SerialValue::Null
| SerialValue::Bool(_)
| SerialValue::Int(_)
| SerialValue::Str(_)
| SerialValue::Bytes(_) => {}
}
}
Ok(())
}
impl<L: SerializableLang> fmt::Debug for SerdeSession<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct Tables<'a, L: SerializableLang>(&'a [TableState<L>]);
impl<L: SerializableLang> fmt::Debug for Tables<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut list = f.debug_list();
for table in self.0 {
list.entry(&format_args!(
"{}: {} entries ({} pending emission)",
table.name,
table.slots.len(),
table.outbox.len()
));
}
list.finish()
}
}
f.debug_struct("SerdeSession")
.field("tables", &Tables(&self.tables))
.field("user_data", &format_args!("{} value(s)", self.user_data.len()))
.field("descent_guard_init", &self.descent_guard_init)
.finish()
}
}