Line data Source code
1 : use std::sync::Arc;
2 :
3 : use rand::Rng;
4 :
5 : use super::chan::Chan;
6 : use super::network::TCP;
7 : use super::world::{Node, NodeId, World};
8 : use crate::proto::NodeEvent;
9 :
10 : /// Abstraction with all functions (aka syscalls) available to the node.
11 : #[derive(Clone)]
12 : pub struct NodeOs {
13 : world: Arc<World>,
14 : internal: Arc<Node>,
15 : }
16 :
17 : impl NodeOs {
18 18921 : pub fn new(world: Arc<World>, internal: Arc<Node>) -> NodeOs {
19 18921 : NodeOs { world, internal }
20 18921 : }
21 :
22 : /// Get the node id.
23 9793 : pub fn id(&self) -> NodeId {
24 9793 : self.internal.id
25 9793 : }
26 :
27 : /// Opens a bidirectional connection with the other node. Always successful.
28 35335 : pub fn open_tcp(&self, dst: NodeId) -> TCP {
29 35335 : self.world.open_tcp(dst)
30 35335 : }
31 :
32 : /// Returns a channel to receive node events (socket Accept and internal messages).
33 19471 : pub fn node_events(&self) -> Chan<NodeEvent> {
34 19471 : self.internal.node_events()
35 19471 : }
36 :
37 : /// Get current time.
38 327115 : pub fn now(&self) -> u64 {
39 327115 : self.world.now()
40 327115 : }
41 :
42 : /// Generate a random number in range [0, max).
43 34119 : pub fn random(&self, max: u64) -> u64 {
44 34119 : self.internal.rng.lock().gen_range(0..max)
45 34119 : }
46 :
47 : /// Append a new event to the world event log.
48 27220 : pub fn log_event(&self, data: String) {
49 27220 : self.internal.log_event(data)
50 27220 : }
51 : }
|