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