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