rustsim_core/model.rs
1//! Abstract model trait - the interface shared by all model types.
2//!
3//! Both [`StandardModel`] and [`EventQueueModel`] implement this trait,
4//! which provides uniform access to time, RNG, space, properties, and agents.
5//!
6//! [`StandardModel`]: crate::standard::StandardModel
7//! [`EventQueueModel`]: crate::event_queue::EventQueueModel
8
9use rand::RngCore;
10use std::ops::{Deref, DerefMut};
11
12use crate::{
13 agent::Agent,
14 space::Space,
15 types::{AgentId, Time},
16};
17
18/// The abstract model interface.
19///
20/// Provides read access to the simulation state (time, space, properties, agents)
21/// and mutable access to the RNG. Concrete model types add stepping methods.
22///
23/// # Generic Associated Types
24///
25/// `AgentRef` and `AgentRefMut` are GATs that allow models using interior
26/// mutability (e.g. `RefCell`) to return borrowed references without
27/// requiring `&mut self` for agent access.
28pub trait Model {
29 /// The agent type stored in this model.
30 type Agent: Agent;
31 /// The space type used by this model.
32 type Space: Space;
33 /// User-defined model properties (can be `()` if unused).
34 type Properties;
35 /// The random number generator type.
36 type Rng: RngCore;
37
38 /// Borrowed reference to an agent (may be `Ref<'a, A>` for `RefCell`-based stores).
39 type AgentRef<'a>: Deref<Target = Self::Agent>
40 where
41 Self: 'a;
42 /// Mutably borrowed reference to an agent (may be `RefMut<'a, A>`).
43 type AgentRefMut<'a>: DerefMut<Target = Self::Agent>
44 where
45 Self: 'a;
46
47 /// Current simulation time.
48 fn time(&self) -> Time;
49
50 /// Mutable access to the model's RNG.
51 ///
52 /// Takes `&self` (not `&mut self`) because the RNG is stored behind interior
53 /// mutability, allowing agent step functions to use it without borrowing
54 /// the entire model exclusively.
55 fn rng_mut(&self) -> impl DerefMut<Target = Self::Rng> + '_;
56
57 /// Immutable reference to the simulation space.
58 fn space(&self) -> &Self::Space;
59
60 /// Immutable reference to user-defined properties.
61 fn properties(&self) -> &Self::Properties;
62
63 /// Mutable reference to user-defined properties.
64 fn properties_mut(&mut self) -> &mut Self::Properties;
65
66 /// Look up an agent by ID, returning a borrowed reference.
67 fn agent(&self, id: AgentId) -> Option<Self::AgentRef<'_>>;
68
69 /// Look up an agent by ID, returning a mutably borrowed reference.
70 fn agent_mut(&self, id: AgentId) -> Option<Self::AgentRefMut<'_>>;
71
72 /// Check whether an agent with the given ID exists.
73 fn has_id(&self, id: AgentId) -> bool {
74 self.agent(id).is_some()
75 }
76}