scientific_workflow/state/state.rs
1//! Fixed-layout, heterogeneous values at one state time.
2//!
3//! [`SystemState`] is the public typed access boundary over the private
4//! [`StateValue`] erasure layer. Every state owns its
5//! payloads, while all states derived from one [`SystemStateSchema`] share immutable
6//! field metadata and name lookup tables.
7//!
8//! # Layout invariant
9//!
10//! The slot vector always has exactly one entry per field declared by the
11//! specification. A slot may be empty, but fields cannot be added, removed, or
12//! reordered after template loading. The first successful initialization binds a
13//! slot to that payload's concrete Rust type. Taking or clearing the payload
14//! retains this type contract, and [`StateMaintenance::clone_structure_without_payloads`] carries all contracts
15//! into the derived blank state without cloning payloads.
16//!
17//! # Ownership and cloning
18//!
19//! `set` consumes a payload without cloning it. Initial insertion returns
20//! `None`, replacement returns ownership of the previous same-typed payload,
21//! and rejection returns ownership of the unchanged incoming payload through
22//! [`PayloadInsertError`]. `take` moves a stored payload back to the caller. These
23//! operations preserve the backing allocations of ordinary scientific owners
24//! such as `Vec<T>` and tensor containers.
25//!
26//! Explicitly cloning a `SystemState` is different: it shares the immutable
27//! specification but deep-clones every populated payload. Persistence should
28//! borrow a live state during synchronous serialization rather than invoke
29//! this expensive clone.
30//!
31//! # Mutation
32//!
33//! The owning simulation can replace, borrow mutably, extract, or clear every
34//! payload. [`SystemState::borrow_payloads`] and [`SystemState::borrow_payloads_mut`] grant
35//! coordinated access to distinct heterogeneous fields through type and name
36//! tuples, allowing one validated borrow to surround an entire scientific
37//! kernel. It can advance time transactionally through
38//! [`SystemState::advance_time`]; advanced lifecycle code can replace a complete
39//! coordinate through [`StateMaintenance::replace_time`].
40//!
41//! # Type safety
42//!
43//! Typed access uses Rust's exact runtime [`TypeId`]. A type
44//! mismatch reports both type names. `take` validates the retained slot type
45//! before removing its owner, so an incorrect request cannot temporarily empty
46//! or discard scientific data.
47//!
48//! # Serialization capability
49//!
50//! New payloads must implement Serde [`Serialize`]. A crate-private accessor
51//! exposes that existing implementation as a borrowed erased trait object for
52//! the storage encoder. `SystemState` itself does not select JSON, frame
53//! records, or perform IO.
54
55use std::any::{Any, TypeId, type_name};
56use std::fmt;
57
58use serde::Serialize;
59
60use super::error::{PayloadInsertError, StateError};
61use super::schema::{StateSchemaAccess, SystemStateSchema};
62use super::time::StateTime;
63use super::value::StateValue;
64
65/// A heterogeneous collection of payloads describing one system time point.
66///
67/// Fields are declared by a JSON-derived [`SystemStateSchema`]. Values are addressed
68/// by those field names but stored in compact optional slots. The type-erased
69/// representation remains private; callers always insert, borrow, mutate, and
70/// extract concrete Rust types.
71pub struct SystemState {
72 spec: SystemStateSchema,
73 time: StateTime,
74 slots: Vec<StateSlot>,
75}
76
77/// One fixed state field's retained type contract and optional payload.
78///
79/// A JSON template creates an unbound slot. The first accepted payload records
80/// its exact runtime type independently from the optional owner, allowing an
81/// emptied slot and every state derived from it to reject accidental retyping.
82/// This structure is private because callers interact only with concrete types
83/// through [`SystemState`].
84#[derive(Clone)]
85struct StateSlot {
86 definition: Option<ValueType>,
87 value: Option<StateValue>,
88}
89
90impl StateSlot {
91 /// Creates a payload-empty slot without a concrete type contract.
92 const fn unbound() -> Self {
93 Self {
94 definition: None,
95 value: None,
96 }
97 }
98
99 /// Creates a payload-empty slot retaining this slot's type contract.
100 const fn empty_like(&self) -> Self {
101 Self {
102 definition: self.definition,
103 value: None,
104 }
105 }
106}
107
108/// Copyable runtime identity retained after a slot's payload is removed.
109#[derive(Clone, Copy)]
110struct ValueType {
111 id: TypeId,
112 name: &'static str,
113}
114
115impl ValueType {
116 /// Captures the exact runtime identity and diagnostic name of `T`.
117 fn of<T>() -> Self
118 where
119 T: Any,
120 {
121 Self {
122 id: TypeId::of::<T>(),
123 name: type_name::<T>(),
124 }
125 }
126
127 /// Reports whether this definition names the exact concrete type `T`.
128 fn is<T>(self) -> bool
129 where
130 T: Any,
131 {
132 self.id == TypeId::of::<T>()
133 }
134}
135
136impl SystemState {
137 /// Creates an empty state from a validated specification.
138 ///
139 /// This constructor is crate-private so an external caller cannot create a
140 /// state without first loading a template. [`SystemStateSchema::create_empty_state`] is the
141 /// public initial construction path.
142 pub(crate) fn new(spec: SystemStateSchema, time: StateTime) -> Self {
143 let slots = (0..spec.len()).map(|_| StateSlot::unbound()).collect();
144 Self { spec, time, slots }
145 }
146
147 /// Returns this state's temporal coordinate.
148 pub const fn time(&self) -> StateTime {
149 self.time
150 }
151
152 /// Advances the iteration by one after one completed model step.
153 ///
154 /// Passing `None` increments only the authoritative iteration and
155 /// preserves the current optional physical coordinate. Passing
156 /// `Some(delta)` additionally requires an existing physical coordinate,
157 /// a finite `delta`, and a finite sum. Negative and zero finite deltas are
158 /// valid because iteration—not physical time—defines record ordering.
159 ///
160 /// On success, the new [`StateTime`] is stored and returned. All validation
161 /// occurs before assignment, so every error leaves the original time point
162 /// unchanged.
163 ///
164 /// # Errors
165 ///
166 /// Returns:
167 ///
168 /// - [`StateError::IterationOverflow`] when the current iteration is
169 /// `u64::MAX`;
170 /// - [`StateError::MissingPhysicalTime`] when a delta is supplied but the
171 /// current state has no physical coordinate;
172 /// - [`StateError::InvalidPhysicalAdvance`] when the delta or resulting
173 /// coordinate is not finite.
174 pub fn advance_time(
175 &mut self,
176 physical_time_increment: Option<f64>,
177 ) -> Result<StateTime, StateError> {
178 let next = self.time.checked_advance(physical_time_increment)?;
179 self.time = next;
180 Ok(next)
181 }
182
183 /// Returns the shared immutable field specification.
184 pub const fn schema(&self) -> &SystemStateSchema {
185 &self.spec
186 }
187
188 /// Reports whether a declared field currently contains a payload.
189 ///
190 /// # Errors
191 ///
192 /// Returns [`StateError::UnknownField`] when `key` was not declared by the
193 /// JSON template.
194 pub fn contains_payload(&self, key: &str) -> Result<bool, StateError> {
195 let index = self.spec.index_of(key)?;
196 Ok(self.slots[index].value.is_some())
197 }
198
199 /// Initializes one declared field and establishes its concrete Rust type.
200 ///
201 /// This is the assembly-oriented operation: it succeeds exactly once per
202 /// field and never silently replaces a value. Every failure preserves the
203 /// unchanged incoming payload in [`PayloadInsertError`].
204 pub fn initialize_payload<T>(
205 &mut self,
206 key: &str,
207 payload: T,
208 ) -> Result<(), PayloadInsertError<T>>
209 where
210 T: Serialize + Clone + Send + 'static,
211 {
212 let index = match self.spec.index_of(key) {
213 Ok(index) => index,
214 Err(error) => return Err(PayloadInsertError::new(error, payload)),
215 };
216 let slot = &mut self.slots[index];
217 if slot.definition.is_some() {
218 return Err(PayloadInsertError::new(
219 StateError::PayloadAlreadyInitialized {
220 field: key.to_owned(),
221 },
222 payload,
223 ));
224 }
225 slot.definition = Some(ValueType::of::<T>());
226 slot.value = Some(StateValue::new(payload));
227 Ok(())
228 }
229
230 /// Sets or replaces a payload while preserving ownership on every outcome.
231 ///
232 /// `payload` moves into this operation and is never cloned:
233 ///
234 /// - a never-populated declared slot binds itself to `T`, receives the
235 /// payload, and returns `Ok(None)`;
236 /// - a slot bound to exactly `T` receives it and returns the displaced
237 /// payload as `Ok(Some(previous))`, or `Ok(None)` when currently empty;
238 /// - an undeclared key returns `Err(PayloadInsertError<T>)` containing the unchanged
239 /// incoming payload;
240 /// - a slot bound to another concrete type remains unchanged and returns
241 /// the incoming payload in `PayloadInsertError<T>`, even when its payload is empty.
242 ///
243 /// Returning a previous payload is deliberate assignment behavior. A
244 /// caller that does not need that owner should discard it explicitly:
245 ///
246 /// ```no_run
247 /// # use scientific_workflow::state::basic::{SystemStateSchema, StateTime};
248 /// # fn example(spec: &SystemStateSchema) -> Result<(), Box<dyn std::error::Error>> {
249 /// let mut state = spec.create_empty_state(StateTime::from_iteration(0));
250 /// drop(state.insert_payload("population", vec![1_u64, 2, 3])?);
251 /// # Ok(())
252 /// # }
253 /// ```
254 ///
255 /// Type-contract validation occurs before the slot is changed.
256 /// Consequently, rejection cannot discard or temporarily remove an
257 /// existing scientific value, and `take` or `clear` cannot reopen a field
258 /// for a different type.
259 ///
260 /// # Errors
261 ///
262 /// Returns [`PayloadInsertError`] containing:
263 ///
264 /// - [`StateError::UnknownField`] when `key` is undeclared;
265 /// - [`StateError::TypeMismatch`] when the slot is bound to a different
266 /// concrete Rust type.
267 ///
268 /// In both cases [`PayloadInsertError::into_parts`] recovers the unchanged incoming
269 /// `T` without cloning it.
270 pub fn insert_payload<T>(
271 &mut self,
272 key: &str,
273 payload: T,
274 ) -> Result<Option<T>, PayloadInsertError<T>>
275 where
276 T: Serialize + Clone + Send + 'static,
277 {
278 let index = match self.spec.index_of(key) {
279 Ok(index) => index,
280 Err(error) => return Err(PayloadInsertError::new(error, payload)),
281 };
282
283 let slot = &mut self.slots[index];
284 match slot.definition {
285 Some(definition) if !definition.is::<T>() => {
286 return Err(PayloadInsertError::new(
287 StateError::TypeMismatch {
288 field: key.to_owned(),
289 expected: type_name::<T>(),
290 actual: definition.name,
291 },
292 payload,
293 ));
294 }
295 Some(_) => {}
296 None => slot.definition = Some(ValueType::of::<T>()),
297 }
298
299 let previous = slot.value.replace(StateValue::new(payload));
300 match previous {
301 None => Ok(None),
302 Some(previous) => match previous.downcast::<T>() {
303 Ok(previous) => Ok(Some(previous)),
304 Err(_) => unreachable!("a type-bound StateValue failed its consuming downcast"),
305 },
306 }
307 }
308
309 /// Borrows a populated field as the exact Rust type `T`.
310 ///
311 /// # Errors
312 ///
313 /// Returns [`StateError::UnknownField`] for an undeclared key,
314 /// [`StateError::MissingPayload`] for an empty slot, or
315 /// [`StateError::TypeMismatch`] when the stored concrete type differs from
316 /// `T`.
317 pub fn payload<T>(&self, key: &str) -> Result<&T, StateError>
318 where
319 T: Any,
320 {
321 let index = self.spec.index_of(key)?;
322 self.validate_slot::<T>(index, key)?;
323 Ok(self.slots[index]
324 .value
325 .as_ref()
326 .and_then(StateValue::downcast_ref::<T>)
327 .expect("a validated state slot must contain its bound concrete type"))
328 }
329
330 /// Mutably borrows a populated field as the exact Rust type `T`.
331 ///
332 /// Mutation occurs in place and does not clone the payload.
333 ///
334 /// # Errors
335 ///
336 /// Returns [`StateError::UnknownField`] for an undeclared key,
337 /// [`StateError::MissingPayload`] for an empty slot, or
338 /// [`StateError::TypeMismatch`] when the stored concrete type differs from
339 /// `T`.
340 pub fn payload_mut<T>(&mut self, key: &str) -> Result<&mut T, StateError>
341 where
342 T: Any,
343 {
344 let index = self.spec.index_of(key)?;
345 self.validate_slot::<T>(index, key)?;
346 Ok(self.slots[index]
347 .value
348 .as_mut()
349 .and_then(StateValue::downcast_mut::<T>)
350 .expect("a validated state slot must contain its bound concrete type"))
351 }
352
353 /// Borrows several distinct populated fields as concrete immutable types.
354 ///
355 /// `Q` is a tuple of expected payload types, while `keys` is the equally
356 /// sized tuple of field names. Tuple positions correspond exactly. The
357 /// supported arities are two through eight; single-field callers should use
358 /// [`SystemState::payload`]. The sealed tuple implementation is internal and
359 /// requires no user-defined selector, query object, or macro invocation.
360 ///
361 /// # Errors
362 ///
363 /// Validation proceeds from left to right and completes before references
364 /// are returned. The method reports an unknown field, repeated field,
365 /// retained type mismatch, or missing payload through [`StateError`]. An
366 /// error leaves every slot unchanged.
367 pub fn borrow_payloads<'state, Q>(
368 &'state self,
369 keys: Q::Keys<'_>,
370 ) -> Result<Q::Refs<'state>, StateError>
371 where
372 Q: PayloadTuple,
373 {
374 Q::borrow(self, keys)
375 }
376
377 /// Borrows several distinct populated fields as concrete mutable types.
378 ///
379 /// `Q` is a tuple of expected payload types, while `keys` is the equally
380 /// sized tuple of field names. All names, duplicate indices, retained type
381 /// contracts, and payload presence are validated before any mutable
382 /// reference is produced. Payloads remain owned by this state and are not
383 /// cloned, moved, serialized, locked, or temporarily removed.
384 ///
385 /// One call should normally surround a complete coupled kernel or sweep so
386 /// name lookup and dynamic type validation occur once outside its inner
387 /// loop. Supported arities are two through eight; single-field callers
388 /// should use [`SystemState::payload_mut`].
389 ///
390 /// # Errors
391 ///
392 /// Returns the same deterministic validation errors as
393 /// [`SystemState::borrow_payloads`]. A failure leaves the state unchanged and grants
394 /// no partial borrow.
395 pub fn borrow_payloads_mut<'state, Q>(
396 &'state mut self,
397 keys: Q::Keys<'_>,
398 ) -> Result<Q::RefsMut<'state>, StateError>
399 where
400 Q: PayloadTuple,
401 {
402 Q::borrow_mut(self, keys)
403 }
404
405 /// Removes and returns the payload from a declared field.
406 ///
407 /// A successful call moves the original concrete `T` out of its internal
408 /// box and leaves the field slot empty while retaining its type contract.
409 /// It does not invoke `Clone`. Type and presence validation occurs before
410 /// the payload owner is removed.
411 ///
412 /// # Errors
413 ///
414 /// Returns [`StateError::UnknownField`] for an undeclared key,
415 /// [`StateError::MissingPayload`] for an empty slot, or
416 /// [`StateError::TypeMismatch`] when the stored concrete type differs from
417 /// `T`.
418 pub fn take_payload<T>(&mut self, key: &str) -> Result<T, StateError>
419 where
420 T: Any + Send,
421 {
422 let index = self.spec.index_of(key)?;
423 self.validate_slot::<T>(index, key)?;
424 let value = self.slots[index]
425 .value
426 .take()
427 .expect("a validated state slot must contain a payload");
428 match value.downcast::<T>() {
429 Ok(payload) => Ok(payload),
430 Err(_) => unreachable!("a type-bound StateValue failed its consuming downcast"),
431 }
432 }
433
434 /// Returns a populated erased value for a typed immutable accessor.
435 fn value(&self, key: &str) -> Result<&StateValue, StateError> {
436 let index = self.spec.index_of(key)?;
437 self.slots[index]
438 .value
439 .as_ref()
440 .ok_or_else(|| StateError::MissingPayload {
441 field: key.to_owned(),
442 })
443 }
444
445 /// Validates one resolved slot against an expected concrete type and value.
446 fn validate_slot<T>(&self, index: usize, key: &str) -> Result<(), StateError>
447 where
448 T: Any,
449 {
450 let slot = &self.slots[index];
451 if let Some(definition) = slot.definition
452 && !definition.is::<T>()
453 {
454 return Err(StateError::TypeMismatch {
455 field: key.to_owned(),
456 expected: type_name::<T>(),
457 actual: definition.name,
458 });
459 }
460
461 if slot.value.is_none() {
462 return Err(StateError::MissingPayload {
463 field: key.to_owned(),
464 });
465 }
466 Ok(())
467 }
468
469 /// Resolves and validates a fixed-size tuple of distinct field names.
470 fn resolve_distinct<const N: usize>(&self, keys: [&str; N]) -> Result<[usize; N], StateError> {
471 let mut indices = [0; N];
472 for (position, key) in keys.iter().enumerate() {
473 let index = self.spec.index_of(key)?;
474 if indices[..position].contains(&index) {
475 return Err(StateError::RepeatedPayloadBorrow {
476 field: (*key).to_owned(),
477 });
478 }
479 indices[position] = index;
480 }
481 Ok(indices)
482 }
483
484 /// Safely separates already validated distinct slot indices.
485 fn disjoint_slots_mut<const N: usize>(&mut self, indices: [usize; N]) -> [&mut StateSlot; N] {
486 let mut positions: [(usize, usize); N] =
487 std::array::from_fn(|position| (position, indices[position]));
488 positions.sort_unstable_by_key(|(_, index)| *index);
489
490 let mut remaining = self.slots.as_mut_slice();
491 let mut base = 0;
492 let mut selected: [Option<&mut StateSlot>; N] = std::array::from_fn(|_| None);
493 for (original_position, index) in positions {
494 let relative = index - base;
495 let (_, at_index) = remaining.split_at_mut(relative);
496 let (slot, tail) = at_index
497 .split_first_mut()
498 .expect("resolved state slot index must be in bounds");
499 selected[original_position] = Some(slot);
500 remaining = tail;
501 base = index + 1;
502 }
503
504 selected
505 .map(|slot| slot.expect("one disjoint slot must be returned for every requested index"))
506 }
507
508 /// Borrows one populated payload through erased Serde serialization.
509 ///
510 /// This crate-private method is the complete format-agnostic boundary used
511 /// by the storage encoder. It performs the same declared-field and
512 /// populated-slot validation as [`SystemState::payload`], but it neither
513 /// downcasts nor exposes the private [`StateValue`] wrapper.
514 ///
515 /// The returned object refers directly to the stored concrete payload. No
516 /// clone, allocation, encoding, or ownership transfer occurs here.
517 pub(crate) fn serializable(
518 &self,
519 key: &str,
520 ) -> Result<&dyn erased_serde::Serialize, StateError> {
521 Ok(self.value(key)?.serializable())
522 }
523}
524
525/// Advanced structural and lifecycle operations for an assembled state.
526pub trait StateMaintenance {
527 /// Creates an empty state sharing schema and retained payload type contracts.
528 fn clone_structure_without_payloads(&self, time: StateTime) -> SystemState;
529
530 /// Replaces the complete temporal coordinate and returns the previous one.
531 fn replace_time(&mut self, time: StateTime) -> StateTime;
532
533 /// Returns the number of fields that currently contain payloads.
534 fn populated_field_count(&self) -> usize;
535
536 /// Reports whether a populated field contains exactly `T`.
537 fn payload_has_type<T: Any>(&self, key: &str) -> Result<bool, StateError>;
538
539 /// Drops one payload while retaining its field type contract.
540 fn clear_payload(&mut self, key: &str) -> Result<bool, StateError>;
541
542 /// Drops all payloads while retaining schema, time, and type contracts.
543 fn clear_all_payloads(&mut self);
544}
545
546impl StateMaintenance for SystemState {
547 fn clone_structure_without_payloads(&self, time: StateTime) -> SystemState {
548 SystemState {
549 spec: self.spec.clone(),
550 time,
551 slots: self.slots.iter().map(StateSlot::empty_like).collect(),
552 }
553 }
554
555 fn replace_time(&mut self, time: StateTime) -> StateTime {
556 std::mem::replace(&mut self.time, time)
557 }
558
559 fn populated_field_count(&self) -> usize {
560 self.slots
561 .iter()
562 .filter(|slot| slot.value.is_some())
563 .count()
564 }
565
566 fn payload_has_type<T: Any>(&self, key: &str) -> Result<bool, StateError> {
567 let index = self.spec.index_of(key)?;
568 Ok(self.slots[index]
569 .value
570 .as_ref()
571 .is_some_and(StateValue::is::<T>))
572 }
573
574 fn clear_payload(&mut self, key: &str) -> Result<bool, StateError> {
575 let index = self.spec.index_of(key)?;
576 Ok(self.slots[index].value.take().is_some())
577 }
578
579 fn clear_all_payloads(&mut self) {
580 self.slots.iter_mut().for_each(|slot| slot.value = None);
581 }
582}
583
584/// Sealing boundary for the internally generated tuple implementations.
585mod tuple_sealed {
586 /// Prevents downstream crates from implementing the hidden tuple contract.
587 pub trait Sealed {}
588}
589
590/// Internal type-level mapping used by [`SystemState::borrow_payloads`] and
591/// [`SystemState::borrow_payloads_mut`].
592///
593/// This trait must be public because it appears in those generic methods'
594/// signatures, but it is sealed and hidden from generated documentation.
595/// Applications select an implementation simply by
596/// writing a supported tuple type such as `(Position, Velocity)`.
597#[doc(hidden)]
598pub trait PayloadTuple: tuple_sealed::Sealed {
599 /// Equally sized tuple of borrowed field names.
600 type Keys<'key>;
601
602 /// Equally sized tuple of immutable concrete payload references.
603 type Refs<'state>
604 where
605 Self: 'state;
606
607 /// Equally sized tuple of mutable concrete payload references.
608 type RefsMut<'state>
609 where
610 Self: 'state;
611
612 /// Resolves and immutably borrows one supported field tuple.
613 #[doc(hidden)]
614 fn borrow<'state, 'key>(
615 state: &'state SystemState,
616 keys: Self::Keys<'key>,
617 ) -> Result<Self::Refs<'state>, StateError>;
618
619 /// Resolves and mutably borrows one supported field tuple.
620 #[doc(hidden)]
621 fn borrow_mut<'state, 'key>(
622 state: &'state mut SystemState,
623 keys: Self::Keys<'key>,
624 ) -> Result<Self::RefsMut<'state>, StateError>;
625}
626
627/// Substitutes one repeated generic identifier with a common tuple element.
628macro_rules! substitute_type {
629 ($_generic:ident => $replacement:ty) => {
630 $replacement
631 };
632}
633
634/// Generates the sealed heterogeneous borrow contract for one tuple arity.
635///
636/// Public callers see only `SystemState::borrow_payloads[_mut]`; this macro centralizes
637/// validation order, exact downcasts, and tuple construction so every supported
638/// arity has identical semantics.
639macro_rules! impl_state_tuple {
640 ($(($type:ident, $key:ident, $slot:ident, $index:tt)),+ $(,)?) => {
641 impl<$($type),+> tuple_sealed::Sealed for ($($type,)+)
642 where
643 $($type: Any,)+
644 {
645 }
646
647 impl<$($type),+> PayloadTuple for ($($type,)+)
648 where
649 $($type: Any,)+
650 {
651 type Keys<'key> = ($(substitute_type!($type => &'key str),)+);
652 type Refs<'state> = ($(&'state $type,)+) where Self: 'state;
653 type RefsMut<'state> = ($(&'state mut $type,)+) where Self: 'state;
654
655 fn borrow<'state, 'key>(
656 state: &'state SystemState,
657 keys: Self::Keys<'key>,
658 ) -> Result<Self::Refs<'state>, StateError> {
659 let ($($key,)+) = keys;
660 let indices = state.resolve_distinct([$($key,)+])?;
661 $(state.validate_slot::<$type>(indices[$index], $key)?;)+
662
663 Ok(($(
664 state.slots[indices[$index]]
665 .value
666 .as_ref()
667 .and_then(StateValue::downcast_ref::<$type>)
668 .expect("a preflighted state slot must contain its bound concrete type"),
669 )+))
670 }
671
672 fn borrow_mut<'state, 'key>(
673 state: &'state mut SystemState,
674 keys: Self::Keys<'key>,
675 ) -> Result<Self::RefsMut<'state>, StateError> {
676 let ($($key,)+) = keys;
677 let indices = state.resolve_distinct([$($key,)+])?;
678 $(state.validate_slot::<$type>(indices[$index], $key)?;)+
679 let [$($slot,)+] = state.disjoint_slots_mut(indices);
680
681 Ok(($(
682 $slot
683 .value
684 .as_mut()
685 .and_then(StateValue::downcast_mut::<$type>)
686 .expect("a preflighted state slot must contain its bound concrete type"),
687 )+))
688 }
689 }
690 };
691}
692
693impl_state_tuple!((A, key_a, slot_a, 0), (B, key_b, slot_b, 1));
694impl_state_tuple!(
695 (A, key_a, slot_a, 0),
696 (B, key_b, slot_b, 1),
697 (C, key_c, slot_c, 2),
698);
699impl_state_tuple!(
700 (A, key_a, slot_a, 0),
701 (B, key_b, slot_b, 1),
702 (C, key_c, slot_c, 2),
703 (D, key_d, slot_d, 3),
704);
705impl_state_tuple!(
706 (A, key_a, slot_a, 0),
707 (B, key_b, slot_b, 1),
708 (C, key_c, slot_c, 2),
709 (D, key_d, slot_d, 3),
710 (E, key_e, slot_e, 4),
711);
712impl_state_tuple!(
713 (A, key_a, slot_a, 0),
714 (B, key_b, slot_b, 1),
715 (C, key_c, slot_c, 2),
716 (D, key_d, slot_d, 3),
717 (E, key_e, slot_e, 4),
718 (F, key_f, slot_f, 5),
719);
720impl_state_tuple!(
721 (A, key_a, slot_a, 0),
722 (B, key_b, slot_b, 1),
723 (C, key_c, slot_c, 2),
724 (D, key_d, slot_d, 3),
725 (E, key_e, slot_e, 4),
726 (F, key_f, slot_f, 5),
727 (G, key_g, slot_g, 6),
728);
729impl_state_tuple!(
730 (A, key_a, slot_a, 0),
731 (B, key_b, slot_b, 1),
732 (C, key_c, slot_c, 2),
733 (D, key_d, slot_d, 3),
734 (E, key_e, slot_e, 4),
735 (F, key_f, slot_f, 5),
736 (G, key_g, slot_g, 6),
737 (H, key_h, slot_h, 7),
738);
739
740impl Clone for SystemState {
741 /// Shares the immutable specification and deep-clones populated payloads.
742 fn clone(&self) -> Self {
743 Self {
744 spec: self.spec.clone(),
745 time: self.time,
746 slots: self.slots.clone(),
747 }
748 }
749}
750
751impl fmt::Debug for SystemState {
752 /// Formats structural metadata without formatting scientific payloads.
753 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
754 formatter
755 .debug_struct("SystemState")
756 .field("time", &self.time)
757 .field("source", &self.spec.template_path())
758 .field("fields", &self.slots.len())
759 .field(
760 "loaded",
761 &self
762 .slots
763 .iter()
764 .filter(|slot| slot.value.is_some())
765 .count(),
766 )
767 .finish_non_exhaustive()
768 }
769}