Skip to main content

trellis_runner/state/
view.rs

1use super::{ConvergenceState, RuntimeState, State, UserState};
2
3use num_traits::float::FloatCore;
4use std::time::Duration;
5
6/// Read-only view into engine state at a single point in time.
7///
8/// This type is used by:
9/// - observers
10/// - logging systems
11/// - extensions
12/// - external monitoring hooks
13///
14/// It provides **safe immutable access** without exposing ownership
15/// of the underlying `State<S>`.
16pub struct StateView<'a, S: UserState> {
17    state: &'a State<S>,
18}
19
20impl<'a, S: UserState> Copy for StateView<'a, S> {}
21
22impl<'a, S: UserState> Clone for StateView<'a, S> {
23    fn clone(&self) -> Self {
24        *self
25    }
26}
27
28impl<'a, S: UserState> StateView<'a, S> {
29    pub(crate) fn new(state: &'a State<S>) -> Self {
30        Self { state }
31    }
32}
33
34impl<'a, S> StateView<'a, S>
35where
36    S: UserState,
37    <S as UserState>::Float: FloatCore,
38{
39    /// Current iteration number of the engine.
40    pub fn iteration(&self) -> usize {
41        self.state.runtime.iteration()
42    }
43
44    /// Total elapsed execution duration.
45    pub fn duration(&self) -> Duration {
46        self.state.runtime.duration()
47    }
48
49    /// Best convergence value observed so far.
50    pub fn best_measure(&self) -> S::Float {
51        self.state.convergence.best()
52    }
53
54    /// Current convergence value.
55    pub fn current_measure(&self) -> S::Float {
56        self.state.convergence.current()
57    }
58
59    /// Number of iterations since the last improvement.
60    pub fn iterations_since_best(&self) -> usize {
61        self.state
62            .convergence
63            .iterations_since_best(self.state.runtime.iteration())
64    }
65
66    /// Access to user-defined state (read-only).
67    pub fn user<'b>(&'b self) -> &'a S {
68        &self.state.user
69    }
70
71    /// Access to runtime state (read-only).
72    pub(crate) fn runtime<'b>(&'b self) -> &'a RuntimeState {
73        &self.state.runtime
74    }
75
76    /// Access to convergence state (read-only).
77    pub(crate) fn convergence<'b>(&'b self) -> &'a ConvergenceState<S::Float> {
78        &self.state.convergence
79    }
80}