ratman_configure/
lib.rs

1//! Ratman configuration toolkit
2//!
3//! Creating networks via Ratman is pretty easy but can involve a fair
4//! amount of boilerplate.  To make the network initialisation easier
5//! and less repetitive, this library is meant to handle network
6//! module state and initialisation, at runtime, either via a
7//! configuration language parser, or via the pure code API.
8
9mod parser;
10pub use parser::parse_json;
11
12pub mod config;
13
14use config::{Endpoint, Id, Network, Params};
15use std::{collections::BTreeMap, net::SocketAddr};
16
17/// A rust API builder equivalent of the json parser
18///
19/// You can easily construct ratman router configurations with this
20/// type, either to connect to other routers across the world, or
21/// locally in memory to test changes made to the router code itself.
22pub struct NetBuilder {
23    id_ctr: Id,
24    endpoints: BTreeMap<Id, Endpoint>,
25}
26
27impl NetBuilder {
28    pub fn new() -> Self {
29        Self {
30            id_ctr: 0,
31            endpoints: BTreeMap::new(),
32        }
33    }
34
35    pub fn endpoint(mut self, epb: EpBuilder) -> Self {
36        let (id, ep) = epb.build(&mut self.id_ctr);
37        self.endpoints.insert(id, ep);
38        self
39    }
40
41    pub fn build(self) -> Network {
42        Network {
43            endpoints: self.endpoints,
44            patches: Default::default(),
45        }
46    }
47}
48
49pub struct EpBuilder {
50    p: Params,
51}
52
53impl EpBuilder {
54    pub fn virt() -> Self {
55        Self { p: Params::Virtual }
56    }
57
58    pub fn tcp(addr: String, port: u16, dynamic: bool) -> Self {
59        Self {
60            p: Params::Tcp {
61                addr,
62                port,
63                peers: vec![],
64                dynamic,
65            },
66        }
67    }
68
69    pub fn local_udp(addr: String) -> Self {
70        Self {
71            p: Params::LocalUpd { addr },
72        }
73    }
74
75    #[cfg(feature = "android")]
76    pub fn wifi_direct() -> Self {
77        Self {
78            p: Params::WifiDirect,
79        }
80    }
81
82    fn build(self, id: &mut Id) -> (Id, Endpoint) {
83        let this = *id;
84        *id += 1;
85        (
86            this,
87            Endpoint {
88                id: this,
89                params: self.p,
90            },
91        )
92    }
93}