Skip to main content

SimTime

Struct SimTime 

Source
pub struct SimTime(/* private fields */);
Expand description

Virtual simulation time measured in nanoseconds from the start of a run.

Implementations§

Source§

impl SimTime

Source

pub const ZERO: Self

The start of simulation time.

Source

pub const fn from_nanos(nanoseconds: u64) -> Self

Creates a time value from nanoseconds.

Examples found in repository?
examples/direct.rs (line 45)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let config = NetworkConfig {
10        devices: vec![
11            DeviceConfig {
12                id: "source".into(),
13                kind: DeviceKind::Source {
14                    egress: "link".into(),
15                },
16                mobility: Default::default(),
17                interference: vec![],
18            },
19            DeviceConfig {
20                id: "sink".into(),
21                kind: DeviceKind::Sink,
22                mobility: Default::default(),
23                interference: vec![],
24            },
25        ],
26        channels: vec![ChannelConfig {
27            id: "link".into(),
28            endpoints: [DeviceId::from("source"), DeviceId::from("sink")],
29            bit_rate_bps: 1_000_000,
30            propagation_delay_ns: 10_000_000,
31            state: ChannelState::Operational,
32            distance: None,
33            radio: None,
34        }],
35    };
36
37    let mut simulator = Simulator::new(config)?;
38    simulator.send("source", "sink", vec![0; 1_000])?;
39    let events = simulator.run()?;
40
41    let delivered_at = events.iter().find_map(|event| match event {
42        NetworkEvent::PacketDelivered { at, .. } => Some(*at),
43        _ => None,
44    });
45    assert_eq!(delivered_at, Some(SimTime::from_nanos(18_000_000)));
46    println!("1,000 bytes delivered in {}", delivered_at.unwrap());
47    Ok(())
48}
More examples
Hide additional examples
examples/moving_link.rs (line 53)
8fn main() -> Result<(), Box<dyn std::error::Error>> {
9    let network = NetworkConfig {
10        devices: vec![
11            DeviceConfig {
12                id: "aircraft".into(),
13                kind: DeviceKind::Source {
14                    egress: "radio".into(),
15                },
16                mobility: MobilityModel::Linear {
17                    position_at_epoch: Position3D::new(100_000.0, 0.0, 10_000.0),
18                    velocity_mps: Velocity3D::new(-150.0, 0.0, 0.0),
19                    epoch_ns: 0,
20                },
21                interference: vec![],
22            },
23            DeviceConfig {
24                id: "ground_station".into(),
25                kind: DeviceKind::Sink,
26                mobility: MobilityModel::Static {
27                    position: Position3D::ORIGIN,
28                },
29                interference: vec![],
30            },
31        ],
32        channels: vec![ChannelConfig {
33            id: "radio".into(),
34            endpoints: ["aircraft".into(), "ground_station".into()],
35            bit_rate_bps: 10_000_000,
36            propagation_delay_ns: 50_000,
37            state: ChannelState::Operational,
38            distance: Some(DistanceChannel {
39                propagation_speed_mps: 299_792_458.0,
40                max_range_m: 120_000.0,
41                rate_model: DistanceRateModel::Linear {
42                    full_rate_distance_m: 20_000.0,
43                    minimum_bit_rate_bps: 1_000_000,
44                },
45            }),
46            radio: None,
47        }],
48    };
49
50    let mut simulator = Simulator::new(network)?;
51    simulator.schedule_send(SimTime::ZERO, "aircraft", "ground_station", vec![0; 1_000])?;
52    simulator.schedule_send(
53        SimTime::from_nanos(300_000_000_000),
54        "aircraft",
55        "ground_station",
56        vec![0; 1_000],
57    )?;
58    simulator.schedule_send(
59        SimTime::from_nanos(1_500_000_000_000),
60        "aircraft",
61        "ground_station",
62        vec![0; 1_000],
63    )?;
64
65    simulator.run_with(|event| match event {
66        NetworkEvent::TransmissionStarted {
67            at,
68            distance_mm,
69            effective_bit_rate_bps,
70            ..
71        } => println!(
72            "{at}: distance {:.1} km, rate {:.2} Mbit/s",
73            distance_mm.unwrap_or_default() as f64 / 1_000_000.0,
74            *effective_bit_rate_bps as f64 / 1_000_000.0,
75        ),
76        NetworkEvent::PacketDropped { at, reason, .. } => {
77            println!("{at}: packet dropped: {reason:?}");
78        }
79        _ => {}
80    })?;
81    Ok(())
82}
examples/intermittent_jamming.rs (line 50)
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15    let network = NetworkConfig {
16        devices: vec![
17            DeviceConfig {
18                id: "vehicle".into(),
19                kind: DeviceKind::Source {
20                    egress: "radio".into(),
21                },
22                mobility: Default::default(),
23                interference: vec![],
24            },
25            DeviceConfig {
26                id: "operator".into(),
27                kind: DeviceKind::Sink,
28                mobility: Default::default(),
29                interference: vec![],
30            },
31        ],
32        channels: vec![ChannelConfig {
33            id: "radio".into(),
34            endpoints: ["vehicle".into(), "operator".into()],
35            bit_rate_bps: 1_000_000,
36            propagation_delay_ns: 100_000,
37            state: ChannelState::Operational,
38            distance: None,
39            radio: Some(RadioChannel {
40                band: RADIO_BAND,
41                interference_response: InterferenceResponse::default(),
42            }),
43        }],
44    };
45
46    let mut simulator = Simulator::new(network)?;
47
48    // A continuous, full-band jammer degrades the second packet to half rate.
49    simulator.schedule_receiver_interference(
50        SimTime::from_nanos(2_000_000),
51        "operator",
52        vec![interference(RADIO_BAND, 0.5)],
53    )?;
54    simulator.schedule_receiver_interference(SimTime::from_nanos(4_000_000), "operator", vec![])?;
55
56    // A short pulse begins after the third packet starts and corrupts it.
57    simulator.schedule_receiver_interference(
58        SimTime::from_nanos(5_200_000),
59        "operator",
60        vec![interference(RADIO_BAND, 0.5)],
61    )?;
62    simulator.schedule_receiver_interference(SimTime::from_nanos(5_300_000), "operator", vec![])?;
63
64    // An accidental emitter covering half the radio band contributes 0.3.
65    simulator.schedule_receiver_interference(
66        SimTime::from_nanos(8_000_000),
67        "operator",
68        vec![interference(
69            FrequencyBand::new(2_400_000_000, 2_410_000_000),
70            0.6,
71        )],
72    )?;
73
74    for at in [0, 2_000_000, 5_000_000, 8_000_000] {
75        simulator.schedule_send(SimTime::from_nanos(at), "vehicle", "operator", vec![0; 100])?;
76    }
77
78    simulator.run_with(|event| match event {
79        NetworkEvent::TransmissionStarted {
80            at,
81            packet,
82            effective_bit_rate_bps,
83            ..
84        } => println!(
85            "{at}: packet {} started at {effective_bit_rate_bps} bit/s",
86            packet.id()
87        ),
88        NetworkEvent::PacketDelivered { at, packet, .. } => {
89            println!("{at}: packet {} delivered", packet.id());
90        }
91        NetworkEvent::PacketDropped {
92            at, packet, reason, ..
93        } => println!("{at}: packet {} dropped: {reason:?}", packet.id()),
94        _ => {}
95    })?;
96    Ok(())
97}
examples/bounded_queues.rs (line 58)
9fn main() -> Result<(), Box<dyn std::error::Error>> {
10    let network = NetworkConfig {
11        devices: vec![
12            DeviceConfig {
13                id: "sender".into(),
14                kind: DeviceKind::Source {
15                    egress: "radio".into(),
16                },
17                mobility: Default::default(),
18                interference: vec![],
19            },
20            DeviceConfig {
21                id: "receiver".into(),
22                kind: DeviceKind::Sink,
23                mobility: Default::default(),
24                interference: vec![],
25            },
26        ],
27        channels: vec![ChannelConfig {
28            id: "radio".into(),
29            endpoints: ["sender".into(), "receiver".into()],
30            bit_rate_bps: 8_000,
31            propagation_delay_ns: 1_000_000,
32            state: ChannelState::Operational,
33            distance: None,
34            radio: None,
35        }],
36    };
37    let mut simulator = Simulator::new_with_options(
38        network,
39        SimulatorOptions {
40            seed: 42,
41            channels: BTreeMap::from([(
42                "radio".into(),
43                ChannelOptions {
44                    mtu_bytes: Some(128),
45                    wire_overhead_bytes: 20,
46                    queue: QueueConfig {
47                        max_packets: Some(2),
48                        max_bytes: Some(256),
49                        discipline: QueueDiscipline::StrictPriority,
50                    },
51                    ..Default::default()
52                },
53            )]),
54        },
55    )?;
56    simulator.send("sender", "receiver", vec![0; 100])?;
57    simulator.schedule_send_with_metadata(
58        SimTime::from_nanos(1),
59        "sender",
60        "receiver",
61        b"old contact".to_vec(),
62        PacketMetadata {
63            priority: 1,
64            expires_at: Some(SimTime::from_nanos(50_000_000)),
65            ..Default::default()
66        },
67    )?;
68    simulator.schedule_send_with_metadata(
69        SimTime::from_nanos(2),
70        "sender",
71        "receiver",
72        b"background".to_vec(),
73        PacketMetadata {
74            priority: 1,
75            ..Default::default()
76        },
77    )?;
78    let urgent = simulator.schedule_send_with_metadata(
79        SimTime::from_nanos(3),
80        "sender",
81        "receiver",
82        b"move".to_vec(),
83        PacketMetadata {
84            priority: 230,
85            ..Default::default()
86        },
87    )?;
88    let mut events = simulator.advance_to(SimTime::from_nanos(10_000_000))?;
89    let metrics = simulator.channel_queue_metrics("radio")?;
90    assert_eq!(metrics.packets_0_to_1, 2);
91    println!(
92        "At 10 ms: {} waiting packets, {} wire bytes",
93        metrics.packets_0_to_1, metrics.bytes_0_to_1
94    );
95    events.extend(simulator.run()?);
96    assert!(events.iter().any(|event| matches!(
97        event,
98        NetworkEvent::PacketDropped {
99            reason: DropReason::Expired,
100            ..
101        }
102    )));
103    assert!(events.iter().any(|event| matches!(event,
104        NetworkEvent::PacketDelivered { packet, .. } if packet.id() == urgent
105    )));
106    for event in events {
107        println!("{event:?}");
108    }
109    Ok(())
110}
Source

pub const fn as_nanos(self) -> u64

Returns this time in nanoseconds.

Trait Implementations§

Source§

impl Clone for SimTime

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for SimTime

Source§

impl Debug for SimTime

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for SimTime

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for SimTime

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for SimTime

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for SimTime

Source§

impl Ord for SimTime

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for SimTime

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for SimTime

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for SimTime

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for SimTime

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.