1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
#![doc(html_root_url = "https://docs.rs/simrs/0.2.0")]
#![warn(
missing_docs,
trivial_casts,
trivial_numeric_casts,
unused_import_braces,
unused_qualifications
)]
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::module_name_repetitions, clippy::default_trait_access)]
//! General purpose simulation library that provides the mechanisms such as: scheduler, state,
//! queues, etc.
//!
//! **NOTE**: This is all experimental right now.
//!
//! The key public types are [`State`], [`Scheduler`], [`Components`], and [`Simulation`].
//! These, along with user-defined simulation components (structs implementing the [`Component`] trait),
//! are the simulation building blocks.
//! Let's first explain each of the above, and then look at examples.
//!
//! # State
//!
//! A simulation must have the ability to mutate its state.
//! This functionality is fully delegated to the [`State`] struct.
//! It can store, remove, and modify values of arbitrary types `T: 'static`.
//! It also allows us to create queues that can be used to move data between components.
//!
//! ## Value Store
//!
//! [`State`] exposes several simple functions to insert, access, modify, and remove values.
//! Existing values are manipulated using special type-safe keys that are generated and
//! returned when inserting the values.
//!
//! ```
//! # use simrs::State;
//! let mut state = State::default();
//! let key = state.insert(7);
//! assert_eq!(state.remove(key), Some(7));
//! ```
//!
//! Note that the following will fail to compile because of incompatible types:
//!
//! ```compile_fail
//! # use simrs::State;
//! let mut state = State::default();
//! let int_key = state.insert(7);
//! let str_key = state.insert("str");
//! let v: i32 = state.get(str_key);
//! ```
//!
//! ## Queues
//!
//! Queues work very similar to storing values but have a different user-facing interface.
//! The access is also done through a key type. However, a different type [`QueueId`] is
//! used for clarity.
//!
//! ```
//! # use simrs::{State, Fifo, Queue};
//! let mut state = State::default();
//! let queue_id = state.add_queue(Fifo::default());
//! state.send(queue_id, 1);
//! assert_eq!(state.len(queue_id), 1);
//! assert_eq!(state.recv(queue_id), Some(1));
//! assert_eq!(state.recv(queue_id), None);
//! ```
//!
//! Additionally, a bounded queue is available, which will return an error if the size reached
//! the capacity.
//!
//! ```
//! # use simrs::{State, Fifo, Queue};
//! let mut state = State::default();
//! let queue_capacity = 1;
//! let queue_id = state.add_queue(Fifo::bounded(queue_capacity));
//! assert!(state.send(queue_id, 1).is_ok());
//! assert_eq!(state.len(queue_id), 1);
//! assert!(!state.send(queue_id, 2).is_ok());
//! assert_eq!(state.len(queue_id), 1);
//! ```
//!
//! # Components
//!
//! The [`Components`] structure is a container for all registered components.
//! Similarly to values and queues in the state, components are identified by [`ComponentId`].
//!
//! ```
//! # use simrs::{Components, Component, State, Scheduler, ComponentId};
//! struct SomeComponent {
//! // ...
//! }
//! #[derive(Debug)]
//! enum SomeEvent {
//! A,
//! B,
//! C,
//! }
//! # impl SomeComponent {
//! # fn new() -> Self {
//! # SomeComponent {}
//! # }
//! # }
//! impl Component for SomeComponent {
//! type Event = SomeEvent;
//! fn process_event(
//! &self,
//! self_id: ComponentId<Self::Event>,
//! event: &Self::Event,
//! scheduler: &mut Scheduler,
//! state: &mut State,
//! ) {
//! // Do some work...
//! }
//! }
//!
//! # fn main() {
//! let mut components = Components::default();
//! let component_id = components.add_component(SomeComponent::new());
//! # }
//! ```
//!
//! # Scheduler
//!
//! The scheduler's main functionality is to keep track of the simulation time and
//! the future events. Events are scheduled to run on a specific component at a specified
//! time interval. Because the events are type-erased, it's up to the component to
//! downcast the event. To make it easy, each component gets a blanket implementation
//! of an internal trait that does that automatically. It is all encapsulated in the
//! `Components` container, as shown in the below example:
//!
//! ```
//! # use simrs::{Components, Component, State, Scheduler, ComponentId};
//! # use std::time::Duration;
//! # struct SomeComponent {
//! # // ...
//! # }
//! # #[derive(Debug)]
//! # enum SomeEvent {
//! # A,
//! # B,
//! # C,
//! # }
//! # impl SomeComponent {
//! # fn new() -> Self {
//! # SomeComponent {}
//! # }
//! # }
//! # impl Component for SomeComponent {
//! # type Event = SomeEvent;
//! # fn process_event(
//! # &self,
//! # self_id: ComponentId<Self::Event>,
//! # event: &Self::Event,
//! # scheduler: &mut Scheduler,
//! # state: &mut State,
//! # ) {
//! # // Do some work...
//! # }
//! # }
//! # fn main() {
//! let mut components = Components::default();
//! let mut scheduler = Scheduler::default();
//! let mut state = State::default();
//! let component_id = components.add_component(SomeComponent::new());
//! scheduler.schedule(
//! Duration::from_secs(1), // schedule 1 second from now
//! component_id,
//! SomeEvent::A,
//! );
//! let event_entry = scheduler.pop().unwrap();
//! components.process_event_entry(event_entry, &mut scheduler, &mut state);
//! # }
//! ```
//!
//! # Simulation
//!
//! [`Simulation`] takes aggregates everything under one structure and provides some additional functions.
//! See the example below.
//!
//! # Example
//!
//! ```
//! # use simrs::{Simulation, State, Scheduler, Components, ComponentId, Component, QueueId, Key, Fifo, Executor};
//! # use std::time::Duration;
//!
//! #[derive(Debug)]
//! struct Product;
//!
//! struct Producer {
//! outgoing: QueueId<Fifo<Product>>,
//! consumer: ComponentId<ConsumerEvent>,
//! produced_count: Key<usize>,
//! }
//!
//! struct Consumer {
//! incoming: QueueId<Fifo<Product>>,
//! working_on: Key<Option<Product>>,
//! }
//!
//! #[derive(Debug)]
//! struct ProducerEvent;
//!
//! #[derive(Debug)]
//! enum ConsumerEvent {
//! Received,
//! Finished,
//! }
//!
//! impl Producer {
//! fn produce(&self) -> Product {
//! Product
//! }
//! fn interval(&self) -> Duration {
//! Duration::from_secs(1)
//! }
//! }
//!
//! impl Consumer {
//! fn interval(&self) -> Duration {
//! Duration::from_secs(1)
//! }
//! fn log(&self, product: Product) {
//! println!("{:?}", product)
//! }
//! }
//!
//! impl Component for Producer {
//! type Event = ProducerEvent;
//!
//! fn process_event(
//! &self,
//! self_id: ComponentId<ProducerEvent>,
//! _event: &ProducerEvent,
//! scheduler: &mut Scheduler,
//! state: &mut State,
//! ) {
//! let count = *state.get(self.produced_count).unwrap();
//! if count < 10 {
//! let _ = state.send(self.outgoing, self.produce());
//! scheduler.schedule(self.interval(), self_id, ProducerEvent);
//! scheduler.schedule(Duration::default(), self.consumer, ConsumerEvent::Received);
//! *state.get_mut(self.produced_count).unwrap() = count + 1;
//! }
//! }
//! }
//!
//! impl Component for Consumer {
//! type Event = ConsumerEvent;
//!
//! fn process_event(
//! &self,
//! self_id: ComponentId<ConsumerEvent>,
//! event: &ConsumerEvent,
//! scheduler: &mut Scheduler,
//! state: &mut State,
//! ) {
//! let busy = state.get(self.working_on).is_some();
//! match event {
//! ConsumerEvent::Received => {
//! if busy {
//! if let Some(product) = state.recv(self.incoming) {
//! state.get_mut(self.working_on).map(|w| *w = Some(product));
//! scheduler.schedule(self.interval(), self_id, ConsumerEvent::Finished);
//! }
//! }
//! }
//! ConsumerEvent::Finished => {
//! let product = state.get_mut(self.working_on).unwrap().take().unwrap();
//! self.log(product);
//! if state.len(self.incoming) > 0 {
//! scheduler.schedule(Duration::default(), self_id, ConsumerEvent::Received);
//! }
//! }
//! }
//! }
//! }
//!
//! fn main() {
//! let mut simulation = Simulation::default();
//! let queue = simulation.add_queue(Fifo::default());
//! let working_on = simulation.state.insert::<Option<Product>>(None);
//! let consumer = simulation.add_component(Consumer {
//! incoming: queue,
//! working_on,
//! });
//! let produced_count = simulation.state.insert(0_usize);
//! let producer = simulation.add_component(Producer {
//! outgoing: queue,
//! consumer,
//! produced_count,
//! });
//! simulation.schedule(Duration::new(0, 0), producer, ProducerEvent);
//! // simulation.schedule(Duration::new(0, 0), consumer, ProducerEvent);
//! // The above would fail with: ^^^^^^^^^^^^^ expected enum `ConsumerEvent`, found struct `ProducerEvent`
//! simulation.execute(Executor::unbound().side_effect(|sim| {
//! println!("{:?}", sim.scheduler.time());
//! }));
//! }
//! ```
use std::cell::Cell;
use std::marker::PhantomData;
use std::rc::Rc;
use std::time::Duration;
type Clock = Rc<Cell<Duration>>;
pub use component::{Component, Components};
pub use scheduler::{ClockRef, EventEntry, Scheduler};
pub use state::State;
pub use queue::{Fifo, PriorityQueue, PushError, Queue};
mod component;
mod execute;
mod queue;
mod scheduler;
mod state;
pub use execute::{Execute, Executor};
static ID_COUNTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn generate_next_id() -> usize {
ID_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
}
/// Simulation struct that puts different parts of the simulation together.
///
/// See the [crate-level documentation](index.html) for more information.
#[derive(Default)]
pub struct Simulation {
/// Simulation state.
pub state: State,
/// Event scheduler.
pub scheduler: Scheduler,
/// Component container.
pub components: Components,
}
impl Simulation {
/// Performs one step of the simulation. Returns `true` if there was in fact an event
/// available to process, and `false` otherwise, which signifies that the simulation
/// ended.
pub fn step(&mut self) -> bool {
self.scheduler.pop().map_or(false, |event| {
self.components
.process_event_entry(event, &mut self.scheduler, &mut self.state);
true
})
}
/// Runs the entire simulation from start to end.
/// This function might not terminate if the end condition is not satisfied.
#[deprecated(
since = "0.2.0",
note = "Handling this in Simulation is susceptible to API breaks and/or making it messy. \
Use execute instead, which delegates the logic to an external executor."
)]
pub fn run<F: Fn(&Simulation)>(&mut self, step_function: F) {
while self.step() {
step_function(self);
}
}
/// Runs the entire simulation.
///
/// The stopping condition and other execution details depend on the executor used.
/// See [`Execute`] and [`Executor`] for more details.
pub fn execute<E: Execute>(&mut self, executor: E) {
executor.execute(self);
}
/// Adds a new component.
#[must_use]
pub fn add_component<E: std::fmt::Debug + 'static, C: Component<Event = E> + 'static>(
&mut self,
component: C,
) -> ComponentId<E> {
self.components.add_component(component)
}
/// Adds a new unbounded queue.
#[must_use]
pub fn add_queue<Q: Queue + 'static>(&mut self, queue: Q) -> QueueId<Q> {
self.state.add_queue(queue)
}
/// Schedules a new event to be executed at time `time` in component `component`.
pub fn schedule<E: std::fmt::Debug + 'static>(
&mut self,
time: Duration,
component: ComponentId<E>,
event: E,
) {
self.scheduler.schedule(time, component, event);
}
}
/// Defines a strongly typed key type.
macro_rules! key_type {
($name:ident, $inner:ty, $doc:literal) => {
#[doc = $doc]
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct $name<V> {
pub(crate) id: $inner,
_marker: PhantomData<V>,
}
impl<T> $name<T> {
pub(crate) fn new(id: $inner) -> Self {
$name {
id,
_marker: PhantomData,
}
}
}
impl<T> Clone for $name<T> {
fn clone(&self) -> Self {
Self::new(self.id)
}
}
impl<T> Copy for $name<T> {}
};
}
key_type!(
ComponentId,
usize,
"A type-safe identifier of a component. This is an analogue of [`Key`] used specifically for components."
);
key_type!(
Key,
usize,
r#"A type-safe key used to fetch values from the value store.
# Construction
A key can be constructed only by calling [`State::insert`].
The state assigns a new numerical ID to the inserted value, which is unique throughout
the running of the program.
This ensures type safety, as explained below.
# Type Safety
These keys are type-safe in a sense that a key used to insert a value of type `T` cannot be
used to access a value of another type `U`. An attempt to do so will result in a compile error.
It is achieved by having the key generic over `T`. However, `T` is just a marker, and no
values of type `T` are stored internally.
```compile_fail
# use simulation::{Key, State};
let mut state = State::default();
let id = state.insert(String::from("1"));
let _: Option<i32> = state.remove(id); // Error!
let _ = state.remove::<i32>(id); // Error!
```
"#
);
key_type!(
QueueId,
usize,
r#"A type-safe identifier of a queue. This is an analogue of [`Key`] used specifically for queues."#
);