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 19965 : pub fn new(world: Arc<World>, internal: Arc<Node>) -> NodeOs {
19 19965 : NodeOs { world, internal }
20 19965 : }
21 :
22 : /// Get the node id.
23 10397 : pub fn id(&self) -> NodeId {
24 10397 : self.internal.id
25 10397 : }
26 :
27 : /// Opens a bidirectional connection with the other node. Always successful.
28 36862 : pub fn open_tcp(&self, dst: NodeId) -> TCP {
29 36862 : self.world.open_tcp(dst)
30 36862 : }
31 :
32 : /// Returns a channel to receive node events (socket Accept and internal messages).
33 20410 : pub fn node_events(&self) -> Chan<NodeEvent> {
34 20410 : self.internal.node_events()
35 20410 : }
36 :
37 : /// Get current time.
38 334831 : pub fn now(&self) -> u64 {
39 334831 : self.world.now()
40 334831 : }
41 :
42 : /// Generate a random number in range [0, max).
43 35694 : pub fn random(&self, max: u64) -> u64 {
44 35694 : self.internal.rng.lock().gen_range(0..max)
45 35694 : }
46 :
47 : /// Append a new event to the world event log.
48 28825 : pub fn log_event(&self, data: String) {
49 28825 : self.internal.log_event(data)
50 28825 : }
51 : }
|