odem-rs-core 0.1.0

Core components of the ODEM-rs simulation framework
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
466
467
468
469
470
471
472
//! Provides type-erased and object-safe traits that can be used to dynamically
//! dispatch over [`Simulators`], regardless of their [configuration].
//!
//! [`Simulators`]: crate::simulator::Simulator
//! [configuration]: Config

pub use crate::continuation::erased::State;

use core::{any::Any, fmt, marker::PhantomData, ptr::NonNull, task::RawWaker};

use crate::{
	config::Config,
	continuation,
	ptr::{IntrusivelyCounted, Irc},
	simulator::{Prec, SimBox},
};

/// Type-erased trait for [Simulation contexts](crate::simulator::Sim).
pub trait Sim: Any + IntrusivelyCounted<Inner = SimBox> {
	/// Returns the currently active and config-erased version of a [`Puck`].
	///
	/// [`Puck`]: crate::Puck
	fn active(&self) -> Option<ContPuck>;

	/// Returns the current time as a displayable object.
	fn now(&self) -> &dyn fmt::Display;

	/// Returns the global (shared) data of the simulator.
	fn global(&self) -> &dyn Any;

	/// Constructs a [`RawWaker`] for the currently active process.
	fn waker(&self) -> RawWaker;

	/// Defers the currently active process.
	fn defer(&self);
}

/// Type-erased trait for [continuations](continuation::Continuation).
pub trait Continuation:
	Any + IntrusivelyCounted<Inner = continuation::ContBox> + fmt::Debug
{
	/// Returns a type-erased reference to the shared agent data.
	fn subject(&self) -> &dyn Any;

	/// Returns the continuation's [`Label`](continuation::Label).
	fn label(&self) -> continuation::Label;

	/// Returns the continuation's [precedence](Prec).
	fn prec(&self) -> Prec;

	/// Returns the continuation's [`State`].
	fn state(&self) -> State;
}

/// [`Config`]-erased type for [pucks](continuation::Puck).
#[derive(Clone)]
pub struct ContPuck(Irc<dyn Continuation>);

impl ContPuck {
	/// Converts a [`Config`]-erased [`ContPuck`] into a `Config`-dependent
	/// [Puck](continuation::Puck) or returns the original object if the
	/// configuration didn't agree with the actual type.
	pub fn downcast<C: Config>(self) -> Result<continuation::Puck<C>, Self> {
		match self.0.downcast::<continuation::Continuation<'static, C>>() {
			Ok(task) => Ok(continuation::Puck::checked(task).unwrap()),
			Err(old) => Err(ContPuck(old)),
		}
	}

	/// Returns a reference to the instance shared among all the [jobs]
	/// associated with the same agent as this one.
	///
	/// [jobs]: crate::job::Job
	pub fn shared(&self) -> &dyn Any {
		self.0.subject()
	}

	/// Returns the name of the underlying [`Agent`](crate::agent::Agent).
	pub fn label(&self) -> continuation::Label {
		self.0.label()
	}

	/// Returns the current [precedence] of the underlying [Job].
	///
	/// [precedence]: Prec
	/// [Job]: crate::job::Job
	pub fn prec(&self) -> Prec {
		self.0.prec()
	}

	/// Returns a copy of this continuation's [`State`].
	pub fn state(&self) -> State {
		self.0.state()
	}
}

impl<C: Config> From<continuation::Puck<C>> for ContPuck {
	fn from(task: continuation::Puck<C>) -> Self {
		let coerced = Irc::into_raw(task.into_inner()) as NonNull<dyn Continuation>;
		ContPuck(unsafe { Irc::from_raw(coerced) })
	}
}

impl fmt::Debug for ContPuck {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.fmt(f)
	}
}

/// Currently active thread-local and type-erased [simulation context].
///
/// [simulation context]: Sim
use shared::SIMULATOR;

/// Sets the passed [simulation context](crate::simulator::Sim)-reference as the
/// new active simulator, returning a [Guard] that resets the active simulator
/// on drop.
#[must_use = "dropping this guard restores the previous thread-local simulator"]
pub(crate) fn hook(sim: Irc<impl Sim>) -> impl Drop {
	Guard::new(sim)
}

/// Executes a closure receiving a type-erased [simulation context].
/// Returns `None` if no simulator is currently active.
///
/// [simulation context]: crate::simulator::Sim
pub fn with<R>(f: impl FnOnce(&dyn Sim) -> R) -> Option<R> {
	SIMULATOR.with(|inner| {
		let sim = inner.take()?;
		let res = f(&*sim);
		inner.set(Some(sim));
		Some(res)
	})
}

/// Returns a [`ContPuck`] for the currently active continuation, if this thread
/// is currently running a simulation.
pub fn active() -> Option<ContPuck> {
	SIMULATOR.with(|inner| {
		let sim = inner.take()?;
		let res = sim.active();
		inner.set(Some(sim));
		res
	})
}

/// Guards the currently active [`Simulator`] in this thread, restoring the
/// previous state when this guard is dropped.
///
/// Guard-instances form an implicit chain over the stack, allowing nested
/// simulation runs within the same thread.
///
/// [`Simulator`]: crate::simulator::Simulator
struct Guard {
	/// The previous type-erased simulator.
	prev: Option<Irc<dyn Sim>>,
}

impl Guard {
	/// Creates a new Guard, pushing it on top of the implicit simulator-stack.
	fn new(sim: Irc<impl Sim>) -> Self {
		Guard {
			prev: SIMULATOR.replace(Some(Irc::map(sim, |inner| -> &dyn Sim { inner }))),
		}
	}
}

impl Drop for Guard {
	fn drop(&mut self) {
		SIMULATOR.replace(self.prev.take());
	}
}

/* *************************************************************** Model Time */

/// Helper that allows displaying the model time of the currently active
/// simulator in human-readable format.
pub struct ModelTime<W>(pub W)
where
	W: Fn(&mut dyn fmt::Write, &dyn Sim) -> fmt::Result;

impl<W> fmt::Display for ModelTime<W>
where
	W: Fn(&mut dyn fmt::Write, &dyn Sim) -> fmt::Result,
{
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		with(move |sim| self.0(f, sim)).unwrap_or(Ok(()))
	}
}

/// Constructs a constant [`ModelTime`] instance that may be used to return the
/// model time of the currently active simulator for this thread.
///
/// The macro accepts a format string and optional, additional arguments as
/// specified for the [format_args]-macro. The format string may reference the
/// `time`-variable.
///
/// This is really meant in combination with the `tracing`-crate, but it is
/// possible to be used independently through the [`Display`]-trait.
///
/// # Example
/// ```
/// # use odem_rs_core::{simulator::{Sim, simulation}, model_time};
/// # async fn sim_main(sim: &Sim) {}
/// fn main() {
///     tracing_subscriber::fmt()
///         .with_timer(model_time!("[{time:#}]"))
///         .init();
///
///     simulation(sim_main).unwrap();
///}
/// ```
///
/// [`Display`]: fmt::Display
#[macro_export]
macro_rules! model_time {
	() => { $crate::model_time!("[{time}]") };

	($($arg:tt)*) => {
		$crate::erased::ModelTime(
			move |w,s| ::core::fmt::write(w, ::core::format_args!($($arg)*, time = s.now()))
		)
	};
}

// make ModelTime compatible to the FormatTime-trait from tracing-subscriber
#[cfg(feature = "tracing")]
impl<W> tracing_subscriber::fmt::time::FormatTime for ModelTime<W>
where
	W: Fn(&mut dyn fmt::Write, &dyn Sim) -> fmt::Result,
{
	fn format_time(&self, w: &mut tracing_subscriber::fmt::format::Writer<'_>) -> fmt::Result {
		with(move |sim| self.0(w, sim)).unwrap_or(Ok(()))
	}
}

/* **************************************************** Normalized Model Time */

/// Helper for displaying normalized model-time in digital-clock-format.
#[derive(Copy, Clone)]
pub struct ClockTime<U> {
	/// The value-part of the time.
	value: isize,
	/// Indicator of the unit of time.
	_unit: PhantomData<U>,
}

impl ClockTime<()> {
	/// Constructs a [displayable](fmt::Display) clock time in seconds.
	pub const fn seconds(value: isize) -> impl fmt::Display {
		ClockTime::<Seconds> {
			value,
			_unit: PhantomData,
		}
	}

	/// Constructs a [displayable](fmt::Display) clock time in minutes.
	pub const fn minutes(value: isize) -> impl fmt::Display {
		ClockTime::<Minutes> {
			value,
			_unit: PhantomData,
		}
	}

	/// Constructs a [displayable](fmt::Display) clock time in hours.
	pub const fn hours(value: isize) -> impl fmt::Display {
		ClockTime::<Hours> {
			value,
			_unit: PhantomData,
		}
	}

	/// Constructs a [displayable](fmt::Display) clock time in days.
	pub const fn days(value: isize) -> impl fmt::Display {
		ClockTime::<Days> {
			value,
			_unit: PhantomData,
		}
	}

	/// Constructs a [displayable](fmt::Display) clock time in weeks.
	pub const fn years(value: isize) -> impl fmt::Display {
		ClockTime::<Years> {
			value,
			_unit: PhantomData,
		}
	}
}

impl<U> ClockTime<U> {
	/// Private method that prints the time's sign.
	fn write_sign(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		if self.value < 0 {
			write!(f, "-")
		} else if f.sign_plus() {
			write!(f, "+")
		} else {
			Ok(())
		}
	}
}

impl fmt::Display for ClockTime<Years> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.write_sign(f)?;
		Years(self.value.unsigned_abs()).fmt(f)
	}
}

impl fmt::Display for ClockTime<Days> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.write_sign(f)?;
		Days(self.value.unsigned_abs()).fmt(f)
	}
}

impl fmt::Display for ClockTime<Hours> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.write_sign(f)?;
		Hours(self.value.unsigned_abs()).fmt(f)
	}
}

impl fmt::Display for ClockTime<Minutes> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.write_sign(f)?;
		Minutes(self.value.unsigned_abs()).fmt(f)
	}
}

impl fmt::Display for ClockTime<Seconds> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.write_sign(f)?;
		Seconds(self.value.unsigned_abs()).fmt(f)
	}
}

/// Marks the inner quantity as 'in seconds'.
struct Seconds(usize);
/// Marks the inner quantity as 'in minutes'.
struct Minutes(usize);
/// Marks the inner quantity as 'in hours'.
struct Hours(usize);
/// Marks the inner quantity as 'in days'.
struct Days(usize);
/// Marks the inner quantity as 'in years'.
struct Years(usize);

impl fmt::Display for Years {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.fmt(f).and_then(|_| f.write_str("a"))
	}
}

impl fmt::Display for Days {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut quantity = self.0;

		if quantity >= 365 || f.precision().map(|w| w > 4).unwrap_or(false) {
			Years(quantity / 365).fmt(f)?;
			quantity %= 365;
			f.write_str(" ")?;
		}

		write!(f, "{quantity}d")
	}
}

impl fmt::Display for Hours {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut quantity = self.0;

		if quantity >= 24 || f.precision().map(|w| w > 3).unwrap_or(false) {
			Days(quantity / 24).fmt(f)?;
			quantity %= 24;
			f.write_str(" ")?;
		}

		write!(f, "{quantity:02}h")
	}
}

impl fmt::Display for Minutes {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut quantity = self.0;

		if quantity >= 60 || f.precision().map(|w| w > 2).unwrap_or(false) {
			Hours(quantity / 60).fmt(f)?;
			quantity %= 60;
			f.write_str(" ")?;
		}

		write!(f, "{quantity:02}m")
	}
}

impl fmt::Display for Seconds {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let mut quantity = self.0;

		if quantity >= 60 || f.precision().map(|w| w > 1).unwrap_or(false) {
			Minutes(quantity / 60).fmt(f)?;
			quantity %= 60;
			f.write_str(" ")?;
		}

		write!(f, "{quantity:02}s")
	}
}

/* ****************************************** Shared Simulator Helper Modules */

#[cfg(feature = "std")]
mod shared {
	use super::{Irc, Sim};
	use std::cell::Cell;

	thread_local! {
		pub static SIMULATOR: Cell<Option<Irc<dyn Sim>>> = const { Cell::new(None) };
	}
}

#[cfg(not(feature = "std"))]
mod shared {
	use super::{Irc, Sim};
	use core::{
		cell::Cell,
		sync::atomic::{AtomicBool, Ordering},
	};

	pub static SIMULATOR: LocalKey = LocalKey::new();

	pub struct LocalKey {
		sim: Cell<Option<Irc<dyn Sim>>>,
		lock: AtomicBool,
	}

	impl LocalKey {
		const fn new() -> Self {
			Self {
				sim: Cell::new(None),
				lock: AtomicBool::new(true),
			}
		}

		pub fn with<R>(&self, f: impl FnOnce(&Cell<Option<Irc<dyn Sim>>>) -> R) -> R {
			assert!(
				self.lock.swap(false, Ordering::SeqCst),
				"detected multiple threads running simulators"
			);

			let res = f(&self.sim);

			self.lock.store(true, Ordering::SeqCst);
			res
		}

		pub fn replace(&self, sim: Option<Irc<dyn Sim>>) -> Option<Irc<dyn Sim>> {
			assert!(
				self.lock.swap(false, Ordering::SeqCst),
				"detected multiple threads running simulators"
			);

			let res = self.sim.replace(sim);

			self.lock.store(true, Ordering::SeqCst);
			res
		}
	}

	unsafe impl Sync for LocalKey {}
}