Skip to main content

labstream_net/
config.rs

1//! The configuration file.
2//!
3//! liblsl reads one file at the first call that needs it, keeps the result for
4//! the life of the process, and never reads another
5//! (`src/api_config.cpp:326-337`). Every port, every multicast group, and
6//! every tuning value below comes from that file or from a default.
7//!
8//! A site that changes `lsl_api.cfg` changes the wire. Two libraries that read
9//! the file differently cannot see each other, and no test of the protocol
10//! finds that, because both sides are correct on their own defaults.
11
12use std::collections::HashMap;
13use std::sync::{Mutex, OnceLock};
14
15/// A file in the format that liblsl reads.
16///
17/// The rules come from `src/util/inireader.cpp`:
18///
19/// * A line that starts with `;` is a comment. **A `#` is not.**
20/// * A blank line is skipped.
21/// * `[section]` opens a section. The key is then `section.Key`.
22/// * A line with no `=` is an error, and one error throws the whole file away.
23/// * A repeated key is an error.
24/// * The key and the value lose the space around them.
25#[derive(Debug, Default, Clone)]
26pub struct Ini {
27    values: HashMap<String, String>,
28}
29
30impl Ini {
31    /// Read a file. An error names the line.
32    pub fn parse(text: &str) -> Result<Ini, String> {
33        let mut values: HashMap<String, String> = HashMap::new();
34        let mut section = String::new();
35        for (k, raw) in text.lines().enumerate() {
36            let line = raw.trim_end_matches('\r');
37            let number = k + 1;
38            if line.starts_with(';') || line.trim().is_empty() {
39                continue;
40            }
41            if line.starts_with('[') {
42                let close = line
43                    .find(']')
44                    .ok_or_else(|| format!("No closing bracket ] found in line {number}"))?;
45                section = format!("{}.", &line[1..close]);
46                continue;
47            }
48            let eq = line
49                .find('=')
50                .ok_or_else(|| format!("No Key-Value pair in line {number}"))?;
51            let key = line[..eq].trim();
52            let value = line[eq + 1..].trim();
53            if key.is_empty() {
54                return Err(format!("Empty key in line {number}"));
55            }
56            if value.is_empty() {
57                return Err(format!("Empty value in line {number}"));
58            }
59            let full = format!("{section}{key}");
60            if values.contains_key(&full) {
61                return Err(format!("Duplicate key {full}"));
62            }
63            values.insert(full, value.to_string());
64        }
65        Ok(Ini { values })
66    }
67
68    /// True when the file explicitly set `key`.
69    pub fn contains_key(&self, key: &str) -> bool {
70        self.values.contains_key(key)
71    }
72
73    /// The text of a key, or a default.
74    pub fn text(&self, key: &str, default: &str) -> String {
75        self.values
76            .get(key)
77            .cloned()
78            .unwrap_or_else(|| default.to_string())
79    }
80
81    /// A whole number, read the way `std::istream` reads one.
82    pub fn int(&self, key: &str, default: i64) -> i64 {
83        match self.values.get(key) {
84            Some(v) => leading_number(v).unwrap_or(0.0) as i64,
85            None => default,
86        }
87    }
88
89    /// A number with a fraction.
90    pub fn float(&self, key: &str, default: f64) -> f64 {
91        match self.values.get(key) {
92            Some(v) => leading_number(v).unwrap_or(0.0),
93            None => default,
94        }
95    }
96
97    /// A yes or no value.
98    ///
99    /// **Only the text `1` means yes.** `src/util/inireader.hpp` reads a
100    /// boolean with `from_string<bool>`, and `src/util/cast.hpp:10` defines
101    /// that as `str == "1"`. A file that says `true` therefore means no.
102    pub fn flag(&self, key: &str, default: bool) -> bool {
103        match self.values.get(key) {
104            Some(v) => v == "1",
105            None => default,
106        }
107    }
108
109    /// A set of the form `{a, b, c}`.
110    ///
111    /// Anything that does not start with `{` and end with `}` is an empty set
112    /// (`src/api_config.cpp:40-46`).
113    pub fn set(&self, key: &str, default: &str) -> Vec<String> {
114        let text = self.text(key, default);
115        let t = text.trim();
116        if t.len() <= 2 || !t.starts_with('{') || !t.ends_with('}') {
117            return Vec::new();
118        }
119        t[1..t.len() - 1]
120            .split(',')
121            .map(|s| s.trim().to_string())
122            .filter(|s| !s.is_empty())
123            .collect()
124    }
125}
126
127/// Read the longest leading run that looks like a number.
128fn leading_number(text: &str) -> Option<f64> {
129    let t = text.trim();
130    let mut end = 0;
131    for (i, c) in t.char_indices() {
132        let keep = c.is_ascii_digit()
133            || (i == 0 && (c == '-' || c == '+'))
134            || c == '.'
135            || c == 'e'
136            || c == 'E';
137        if !keep {
138            break;
139        }
140        end = i + c.len_utf8();
141    }
142    t[..end].parse().ok()
143}
144
145/// When fallback discovery runs after multicast finds no stream.
146/// `labstream.FallbackDiscovery`. `docs/discovery.md`.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub enum FallbackDiscovery {
149    /// Run fallback paths only after wave 1 finds no stream.
150    Auto,
151    /// Run classic LSL discovery only (multicast, `255.255.255.255`, `KnownPeers` UDP).
152    Off,
153    /// Run fallback paths on every wave, including wave 1.
154    Subnet,
155}
156
157impl FallbackDiscovery {
158    /// Lowercase name for display and JSON output.
159    pub fn as_str(self) -> &'static str {
160        match self {
161            FallbackDiscovery::Auto => "auto",
162            FallbackDiscovery::Off => "off",
163            FallbackDiscovery::Subnet => "subnet",
164        }
165    }
166
167    fn parse(text: &str) -> FallbackDiscovery {
168        match text.trim().to_ascii_lowercase().as_str() {
169            "off" | "0" | "false" | "none" => FallbackDiscovery::Off,
170            "subnet" | "always" | "on" => FallbackDiscovery::Subnet,
171            _ => FallbackDiscovery::Auto,
172        }
173    }
174}
175
176/// Every value that changes what travels on the wire.
177///
178/// The names follow `src/api_config.cpp:168-322`. A value that this
179/// implementation does not act on yet is left out rather than read and
180/// ignored.
181#[derive(Debug, Clone)]
182pub struct Config {
183    /// The port for a multicast or broadcast query. `ports.MulticastPort`.
184    pub multicast_port: u16,
185    /// The first port of the unicast range. `ports.BasePort`.
186    pub base_port: u16,
187    /// How many ports the range holds. `ports.PortRange`.
188    pub port_range: u16,
189    /// The session that a stream belongs to. `lab.SessionID`.
190    pub session_id: String,
191    /// Addresses that a resolver always sends to. `lab.KnownPeers`.
192    pub known_peers: Vec<String>,
193    /// The groups that a query goes to, for the chosen scope.
194    pub multicast_addresses: Vec<String>,
195    /// The hop count for a multicast query.
196    pub multicast_ttl: u32,
197    /// How long a quiet source stays connected. `tuning.WatchdogTimeThreshold`.
198    pub watchdog_time_threshold: f64,
199    /// How often the clock is measured. `tuning.TimeUpdateInterval`.
200    pub time_update_interval: f64,
201    /// How many probes an estimate needs. `tuning.TimeUpdateMinProbes`.
202    pub time_update_min_probes: u32,
203    /// How many probes one burst sends. `tuning.TimeProbeCount`.
204    pub time_probe_count: u32,
205    /// The gap between two probes. `tuning.TimeProbeInterval`.
206    pub time_probe_interval: f64,
207    /// How long a burst waits for answers. `tuning.TimeProbeMaxRTT`.
208    pub time_probe_max_rtt: f64,
209    /// The half-time of the smoothing filter. `tuning.SmoothingHalftime`.
210    pub smoothing_halftime: f32,
211    /// When true, every pushed timestamp is replaced by the current clock.
212    /// `tuning.ForceDefaultTimestamps`.
213    pub force_default_timestamps: bool,
214    /// The gap between two waves of a background resolver.
215    /// `tuning.ContinuousResolveInterval`.
216    pub continuous_resolve_interval: f64,
217    /// The shortest time a multicast wave waits. `tuning.MulticastMinRTT`.
218    pub multicast_min_rtt: f64,
219    /// The shortest time a unicast wave waits. `tuning.UnicastMinRTT`.
220    pub unicast_min_rtt: f64,
221    /// The protocol version that an outlet writes. `tuning.UseProtocolVersion`.
222    pub use_protocol_version: i32,
223    /// True when an outlet binds an IPv4 stack. `ports.IPv6`.
224    pub allow_ipv4: bool,
225    /// True when an outlet binds an IPv6 stack. `ports.IPv6`.
226    pub allow_ipv6: bool,
227    /// The labstream features that this process can use, for example `seq`.
228    /// `labstream.Features`. liblsl does not read this key. The value `{}`
229    /// turns every feature off. `docs/extensions.md`.
230    pub features: Vec<String>,
231    /// The time limit of the `resume` history, in seconds.
232    /// `labstream.ResumeSeconds`, 30 s by default. The value 0 turns the
233    /// history off.
234    /// `docs/extensions.md`, section `resume`.
235    pub resume_seconds: f64,
236    /// The memory limit of the `resume` history, in MiB.
237    /// `labstream.ResumeMemory`.
238    pub resume_memory_mib: f64,
239    /// The disk spool limit of the `resume` history, in MiB.
240    /// `labstream.ResumeDisk`, 0 by default (memory only).
241    /// `docs/roadmap.md`, step 3.
242    pub resume_disk_mib: f64,
243    /// Optional directory for disk spool files (`labstream.ResumeDiskPath`).
244    /// `None` uses the system temporary directory.
245    pub resume_disk_path: Option<String>,
246    /// When fallback discovery runs. `labstream.FallbackDiscovery`.
247    /// `docs/discovery.md`.
248    pub fallback_discovery: FallbackDiscovery,
249    /// When true, refuse any feed connection that does not negotiate `enc/1`
250    /// (`labstream.RequireEncryption`, off by default, `docs/roadmap.md`, step 14).
251    pub require_encryption: bool,
252    /// Optional pre-shared key mixed into the `enc/1` key derivation for mutual
253    /// peer authentication (`labstream.EncryptionKey`, empty by default).
254    pub encryption_key: Option<String>,
255    /// Where the values came from, for a report.
256    pub source: String,
257}
258
259impl Default for Config {
260    fn default() -> Config {
261        Config::from_ini(&Ini::default(), "the defaults")
262    }
263}
264
265impl Config {
266    /// The limits of the `resume` history from `labstream.ResumeSeconds`,
267    /// `labstream.ResumeMemory`, `labstream.ResumeDisk`, and
268    /// `labstream.ResumeDiskPath`.
269    pub fn history_limits(&self) -> crate::history::HistoryLimits {
270        let bytes = self.resume_memory_mib * (1u64 << 20) as f64;
271        let disk_bytes = self.resume_disk_mib * (1u64 << 20) as f64;
272        crate::history::HistoryLimits {
273            seconds: self.resume_seconds,
274            bytes: if bytes >= usize::MAX as f64 {
275                usize::MAX
276            } else {
277                bytes as usize
278            },
279            disk_bytes: if disk_bytes >= u64::MAX as f64 {
280                u64::MAX
281            } else {
282                disk_bytes as u64
283            },
284            disk_dir: self.resume_disk_path.as_ref().map(std::path::PathBuf::from),
285        }
286    }
287
288    /// Read a configuration out of a file that was already parsed.
289    pub fn from_ini(ini: &Ini, source: &str) -> Config {
290        // The scope decides which groups a query reaches, and the hop count.
291        // `src/api_config.cpp:211-247`.
292        let scope = ini.text("multicast.ResolveScope", "site");
293        let rank = |s: &str| match s {
294            "machine" => 0,
295            "link" => 1,
296            "site" => 2,
297            "organization" => 3,
298            "global" => 4,
299            // liblsl throws here, which throws the whole file away.
300            _ => 2,
301        };
302        let level = rank(&scope);
303        // Each scope adds an IPv6 group as well, built from one suffix and the
304        // prefix of that scope (`src/api_config.cpp:191-247`).
305        let v6 = ini.text(
306            "multicast.IPv6MulticastGroup",
307            "113D:6FDD:2C17:A643:FFE2:1BD1:3CD2",
308        );
309        let mut addresses = ini.set("multicast.MachineAddresses", "{127.0.0.1}");
310        let mut ttl = 0;
311        if level >= 1 {
312            addresses.extend(ini.set(
313                "multicast.LinkAddresses",
314                "{255.255.255.255, 224.0.0.1, 224.0.0.183}",
315            ));
316            addresses.push(format!("FF02:{v6}"));
317            ttl = 1;
318        }
319        if level >= 2 {
320            addresses.extend(ini.set("multicast.SiteAddresses", "{239.255.172.215}"));
321            addresses.push(format!("FF05:{v6}"));
322            ttl = 24;
323        }
324        if level >= 3 {
325            addresses.extend(ini.set("multicast.OrganizationAddresses", "{}"));
326            addresses.push(format!("FF08:{v6}"));
327            ttl = 32;
328        }
329        if level >= 4 {
330            addresses.extend(ini.set("multicast.GlobalAddresses", "{}"));
331            addresses.push(format!("FF0E:{v6}"));
332            ttl = 255;
333        }
334        let ttl_override = ini.int("multicast.TTLOverride", -1);
335        if ttl_override >= 0 {
336            ttl = ttl_override as u32;
337        }
338        let address_override = ini.set("multicast.AddressesOverride", "{}");
339        if !address_override.is_empty() {
340            addresses = address_override;
341        }
342        // `ports.IPv6` names which stacks an outlet binds
343        // (`src/api_config.cpp:172-185`). A word outside the list makes liblsl
344        // throw, which throws the whole file away, so the defaults apply.
345        let (allow_ipv4, allow_ipv6) = match ini.text("ports.IPv6", "allow").as_str() {
346            "disabled" | "disable" => (true, false),
347            "forced" | "force" => (false, true),
348            _ => (true, true),
349        };
350        addresses.retain(|a| match a.parse::<std::net::IpAddr>() {
351            Ok(std::net::IpAddr::V4(_)) => allow_ipv4,
352            Ok(std::net::IpAddr::V6(_)) => allow_ipv6,
353            Err(_) => false,
354        });
355
356        let resume_disk_mib = ini.float("labstream.ResumeDisk", 0.0).max(0.0);
357        let resume_disk_path_raw = ini.text("labstream.ResumeDiskPath", "");
358        let resume_disk_path = if resume_disk_path_raw.is_empty() {
359            None
360        } else {
361            Some(resume_disk_path_raw)
362        };
363        // When disk spooling is enabled and `ResumeSeconds` is not explicitly
364        // set, let `ResumeDisk` bound retention instead of cutting off at the
365        // 30 s RAM default.
366        let resume_seconds =
367            if resume_disk_mib > 0.0 && !ini.contains_key("labstream.ResumeSeconds") {
368                f64::INFINITY
369            } else {
370                ini.float("labstream.ResumeSeconds", 30.0).max(0.0)
371            };
372
373        let encryption_key_raw = ini.text("labstream.EncryptionKey", "");
374        let encryption_key = if encryption_key_raw.is_empty() {
375            None
376        } else {
377            Some(encryption_key_raw)
378        };
379        let require_encryption = ini.flag("labstream.RequireEncryption", false);
380
381        Config {
382            multicast_port: ini.int("ports.MulticastPort", 16571) as u16,
383            base_port: ini.int("ports.BasePort", 16572) as u16,
384            port_range: ini.int("ports.PortRange", 32) as u16,
385            session_id: ini.text("lab.SessionID", "default"),
386            known_peers: ini.set("lab.KnownPeers", "{}"),
387            features: ini.set(
388                "labstream.Features",
389                "{seq, resume, dgram, select, shm, comp, meta}",
390            ),
391            resume_seconds,
392            resume_memory_mib: ini.float("labstream.ResumeMemory", 64.0).max(0.0),
393            resume_disk_mib,
394            resume_disk_path,
395            fallback_discovery: FallbackDiscovery::parse(
396                &ini.text("labstream.FallbackDiscovery", "auto"),
397            ),
398            require_encryption,
399            encryption_key,
400            multicast_addresses: addresses,
401            multicast_ttl: ttl,
402            watchdog_time_threshold: ini.float("tuning.WatchdogTimeThreshold", 15.0),
403            time_update_interval: ini.float("tuning.TimeUpdateInterval", 2.0),
404            time_update_min_probes: ini.int("tuning.TimeUpdateMinProbes", 6) as u32,
405            time_probe_count: ini.int("tuning.TimeProbeCount", 8) as u32,
406            time_probe_interval: ini.float("tuning.TimeProbeInterval", 0.064),
407            time_probe_max_rtt: ini.float("tuning.TimeProbeMaxRTT", 0.128),
408            smoothing_halftime: ini.float("tuning.SmoothingHalftime", 90.0) as f32,
409            force_default_timestamps: ini.flag("tuning.ForceDefaultTimestamps", false),
410            continuous_resolve_interval: ini.float("tuning.ContinuousResolveInterval", 0.5),
411            multicast_min_rtt: ini.float("tuning.MulticastMinRTT", 0.5),
412            unicast_min_rtt: ini.float("tuning.UnicastMinRTT", 0.75),
413            use_protocol_version: (ini.int("tuning.UseProtocolVersion", 110) as i32).min(110),
414            allow_ipv4,
415            allow_ipv6,
416            source: source.to_string(),
417        }
418    }
419}
420
421/// A file name that an application set before the first use.
422static FILENAME: Mutex<Option<String>> = Mutex::new(None);
423/// Text that an application set before the first use.
424static CONTENT: Mutex<Option<String>> = Mutex::new(None);
425static LOADED: OnceLock<Config> = OnceLock::new();
426
427/// Name the file to read. Call this before anything else.
428///
429/// `lsl_set_config_filename`. A call after the configuration is read has no
430/// effect, on either implementation.
431pub fn set_filename(path: &str) {
432    *FILENAME.lock().unwrap() = Some(path.to_string());
433}
434
435/// Give the configuration as text. Call this before anything else.
436///
437/// `lsl_set_config_content`. liblsl uses the text once and then drops it
438/// (`src/api_config.cpp:57-70`).
439pub fn set_content(text: &str) {
440    *CONTENT.lock().unwrap() = Some(text.to_string());
441}
442
443/// The configuration of this process.
444///
445/// The file is read once. Every later call returns the same values, which is
446/// what liblsl does with `std::call_once` (`src/api_config.cpp:326`).
447pub fn get() -> &'static Config {
448    LOADED.get_or_init(load)
449}
450
451/// Where liblsl looks, in order. `src/api_config.cpp:70-110`.
452fn candidates() -> Vec<String> {
453    let mut out: Vec<String> = Vec::new();
454    if let Some(name) = FILENAME.lock().unwrap().clone() {
455        if std::fs::File::open(&name).is_ok() {
456            out.push(name);
457        }
458    }
459    // The environment takes precedence over the name that an application set.
460    if let Ok(env) = std::env::var("LSLAPICFG") {
461        if std::fs::File::open(&env).is_ok() {
462            out.insert(0, env);
463        }
464    }
465    out.push("lsl_api.cfg".to_string());
466    if let Ok(home) = std::env::var("HOME") {
467        out.push(format!("{home}/lsl_api/lsl_api.cfg"));
468    }
469    out.push("/etc/lsl_api/lsl_api.cfg".to_string());
470    out
471}
472
473fn load() -> Config {
474    if let Some(text) = CONTENT.lock().unwrap().take() {
475        match Ini::parse(&text) {
476            Ok(ini) => return Config::from_ini(&ini, "the text that the application gave"),
477            // A file that does not parse leaves the defaults in place.
478            Err(_) => return Config::default(),
479        }
480    }
481    for name in candidates() {
482        if let Ok(text) = std::fs::read_to_string(&name) {
483            return match Ini::parse(&text) {
484                Ok(ini) => Config::from_ini(&ini, &name),
485                Err(_) => Config::default(),
486            };
487        }
488    }
489    Config::default()
490}
491
492#[cfg(test)]
493mod tests {
494    use super::*;
495
496    #[test]
497    fn a_section_becomes_part_of_the_key() {
498        let ini = Ini::parse("[ports]\nBasePort = 17000\n").expect("a file");
499        assert_eq!(ini.int("ports.BasePort", 16572), 17000);
500        assert_eq!(ini.int("BasePort", 16572), 16572);
501    }
502
503    #[test]
504    fn only_a_semicolon_starts_a_comment() {
505        // `src/util/inireader.cpp:13` tests for `;` and nothing else. A `#`
506        // makes the line a key with no `=`, which throws the file away.
507        assert!(Ini::parse("; a note\n[lab]\nSessionID = x\n").is_ok());
508        assert!(Ini::parse("# a note\n[lab]\nSessionID = x\n").is_err());
509    }
510
511    #[test]
512    fn only_the_digit_one_means_yes() {
513        // `src/util/cast.hpp:10` defines this as `str == "1"`.
514        let ini = Ini::parse("[tuning]\nA = 1\nB = true\nC = 0\n").expect("a file");
515        assert!(ini.flag("tuning.A", false));
516        assert!(!ini.flag("tuning.B", false));
517        assert!(!ini.flag("tuning.C", true));
518        assert!(ini.flag("tuning.Missing", true));
519    }
520
521    #[test]
522    fn a_repeated_key_throws_the_file_away() {
523        assert!(Ini::parse("[lab]\nSessionID = a\nSessionID = b\n").is_err());
524    }
525
526    #[test]
527    fn a_line_with_no_equals_sign_throws_the_file_away() {
528        assert!(Ini::parse("[lab]\nSessionID\n").is_err());
529    }
530
531    #[test]
532    fn a_set_needs_both_braces() {
533        let ini = Ini::parse("[lab]\nA = {x, y}\nB = x, y\nC = {}\n").expect("a file");
534        assert_eq!(ini.set("lab.A", "{}"), vec!["x", "y"]);
535        assert!(ini.set("lab.B", "{}").is_empty());
536        assert!(ini.set("lab.C", "{}").is_empty());
537    }
538
539    #[test]
540    fn the_space_around_a_key_and_a_value_is_dropped() {
541        let ini = Ini::parse("[lab]\n   SessionID   =   my lab   \n").expect("a file");
542        assert_eq!(ini.text("lab.SessionID", ""), "my lab");
543    }
544
545    #[test]
546    fn the_defaults_match_the_values_in_the_source() {
547        let c = Config::default();
548        assert_eq!(c.multicast_port, 16571);
549        assert_eq!(c.base_port, 16572);
550        assert_eq!(c.port_range, 32);
551        assert_eq!(c.session_id, "default");
552        assert_eq!(c.watchdog_time_threshold, 15.0);
553        assert_eq!(c.time_update_interval, 2.0);
554        assert_eq!(c.time_update_min_probes, 6);
555        assert_eq!(c.time_probe_count, 8);
556        assert_eq!(c.time_probe_interval, 0.064);
557        assert_eq!(c.time_probe_max_rtt, 0.128);
558        assert_eq!(c.smoothing_halftime, 90.0);
559        assert!(!c.force_default_timestamps);
560        assert_eq!(c.use_protocol_version, 110);
561    }
562
563    #[test]
564    fn the_resume_limits_have_defaults_and_a_file_sets_them() {
565        let c = Config::from_ini(&Ini::default(), "test");
566        assert_eq!(c.history_limits(), crate::history::HistoryLimits::DEFAULT);
567        let set =
568            Ini::parse("[labstream]\nResumeSeconds = 2.5\nResumeMemory = 1\n").expect("a file");
569        let limits = Config::from_ini(&set, "test").history_limits();
570        assert_eq!(limits.seconds, 2.5);
571        assert_eq!(limits.bytes, 1 << 20);
572        let off = Ini::parse("[labstream]\nResumeSeconds = 0\n").expect("a file");
573        assert!(!Config::from_ini(&off, "test")
574            .history_limits()
575            .allow_history());
576        let negative = Ini::parse("[labstream]\nResumeMemory = -5\n").expect("a file");
577        assert!(!Config::from_ini(&negative, "test")
578            .history_limits()
579            .allow_history());
580        let disk = Ini::parse("[labstream]\nResumeDisk = 512\nResumeDiskPath = /tmp/spool\n")
581            .expect("a file");
582        let dlimits = Config::from_ini(&disk, "test").history_limits();
583        assert_eq!(dlimits.disk_bytes, 512 << 20);
584        assert_eq!(
585            dlimits.disk_dir.as_deref(),
586            Some(std::path::Path::new("/tmp/spool"))
587        );
588        assert!(dlimits.seconds.is_infinite());
589    }
590
591    #[test]
592    fn the_labstream_features_are_on_by_default_and_a_file_turns_them_off() {
593        let c = Config::from_ini(&Ini::default(), "test");
594        assert_eq!(
595            c.features,
596            vec![
597                "seq".to_string(),
598                "resume".to_string(),
599                "dgram".to_string(),
600                "select".to_string(),
601                "shm".to_string(),
602                "comp".to_string(),
603                "meta".to_string()
604            ]
605        );
606        let off = Ini::parse("[labstream]\nFeatures = {}\n").expect("a file");
607        assert!(Config::from_ini(&off, "test").features.is_empty());
608    }
609
610    #[test]
611    fn the_scope_decides_the_groups_and_the_hop_count() {
612        let of = |scope: &str| {
613            let ini =
614                Ini::parse(&format!("[multicast]\nResolveScope = {scope}\n")).expect("a file");
615            Config::from_ini(&ini, "test")
616        };
617        let machine = of("machine");
618        assert_eq!(machine.multicast_addresses, vec!["127.0.0.1"]);
619        assert_eq!(machine.multicast_ttl, 0);
620
621        let link = of("link");
622        assert!(link
623            .multicast_addresses
624            .contains(&"224.0.0.183".to_string()));
625        assert!(!link
626            .multicast_addresses
627            .contains(&"239.255.172.215".to_string()));
628        assert_eq!(link.multicast_ttl, 1);
629
630        let site = of("site");
631        assert!(site
632            .multicast_addresses
633            .contains(&"239.255.172.215".to_string()));
634        assert_eq!(site.multicast_ttl, 24);
635    }
636
637    #[test]
638    fn an_address_override_replaces_the_whole_list() {
639        let ini =
640            Ini::parse("[multicast]\nAddressesOverride = {10.0.0.1, 10.0.0.2}\n").expect("a file");
641        let c = Config::from_ini(&ini, "test");
642        assert_eq!(c.multicast_addresses, vec!["10.0.0.1", "10.0.0.2"]);
643    }
644
645    #[test]
646    fn a_hop_count_override_wins() {
647        let ini = Ini::parse("[multicast]\nTTLOverride = 7\n").expect("a file");
648        assert_eq!(Config::from_ini(&ini, "test").multicast_ttl, 7);
649    }
650
651    #[test]
652    fn the_protocol_version_never_rises_above_the_one_this_library_speaks() {
653        let ini = Ini::parse("[tuning]\nUseProtocolVersion = 200\n").expect("a file");
654        assert_eq!(Config::from_ini(&ini, "test").use_protocol_version, 110);
655        let ini = Ini::parse("[tuning]\nUseProtocolVersion = 100\n").expect("a file");
656        assert_eq!(Config::from_ini(&ini, "test").use_protocol_version, 100);
657    }
658
659    #[test]
660    fn fallback_discovery_defaults_to_auto_and_parses_modes() {
661        let def = Config::default();
662        assert_eq!(def.fallback_discovery, FallbackDiscovery::Auto);
663        let off = Ini::parse("[labstream]\nFallbackDiscovery = off\n").expect("a file");
664        assert_eq!(
665            Config::from_ini(&off, "test").fallback_discovery,
666            FallbackDiscovery::Off
667        );
668        let sub = Ini::parse("[labstream]\nFallbackDiscovery = subnet\n").expect("a file");
669        assert_eq!(
670            Config::from_ini(&sub, "test").fallback_discovery,
671            FallbackDiscovery::Subnet
672        );
673    }
674}