cat-dev 0.0.13

A library for interacting with the CAT-DEV hardware units distributed by Nintendo (i.e. a type of Wii-U DevKits).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//! MION is the Sata Device present on the CAT-DEV Bridge.
//!
//! In general MION's are pretty much the "host bridge" most of the host bridge
//! software _actually_ talks too. `hostdisplayversion` calls it the
//! "Bridge Type", but I don't think we  know of any other bridge types.
//!
//! In general if you're trying to look for things relating to the bridge as a
//! whole, you're _probably_ really actually talking to the MION.

#[cfg_attr(docsrs, doc(cfg(feature = "clients")))]
#[cfg(feature = "clients")]
pub mod cgis;
#[cfg_attr(docsrs, doc(cfg(feature = "clients")))]
#[cfg(feature = "clients")]
pub mod discovery;
pub mod errors;
pub mod firmware;
#[cfg_attr(docsrs, doc(cfg(feature = "clients")))]
#[cfg(feature = "clients")]
pub mod parameter;
/// MionBootType is used by SDIO server, and thus we allow all of these protos
/// to be used on the server side.
#[cfg_attr(docsrs, doc(cfg(any(feature = "clients", feature = "servers"))))]
#[cfg(any(feature = "clients", feature = "servers"))]
pub mod proto;

use crate::errors::FSError;
use configparser::ini::Ini;
use errors::MionAPIError;
use fnv::FnvHashMap;
use std::{
	fmt::{Display, Formatter, Result as FmtResult},
	hash::BuildHasherDefault,
	net::Ipv4Addr,
	path::PathBuf,
};

/// The environment variable name to fetch what version of [`CAFE_HARDWARE`]
/// we're using.
const HARDWARE_ENV_NAME: &str = "CAFE_HARDWARE";
/// The prefix prepended to the bridge name keys in the host env file to
/// prevent collisions.
const BRIDGE_NAME_KEY_PREFIX: &str = "BRIDGE_NAME_";
/// The section name in the ini file we store a list of the host bridges are
/// stored in.
const HOST_BRIDGES_SECTION: &str = "HOST_BRIDGES";
/// The key that contains that stores which bridge is marked as the default.
const DEFAULT_BRIDGE_KEY: &str = "BRIDGE_DEFAULT_NAME";

/// As far as I can derive from the sources available that we can cleanly read
/// (e.g. shell scripts) there are two types of CAT-DEV units. This enum
/// describes those.
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum BridgeType {
	/// "MION" is the 'standard' cat-dev unit that most people probably have (and
	/// is in fact the only one the developers have).
	///
	/// MIONs are also refered to as "v3", and "v4". If you have a tan colored
	/// box you almost assuredly have a MION.
	Mion,
	/// A toucan is the other type of cat-dev unit referenced in some of the
	/// shell scripts.
	///
	/// We don't have a ton of documentation on this particular bridge type
	/// mainly because we don't actually own any of these bridge types. They
	/// generally be refered to as "v2" bridges.
	Toucan,
}
impl BridgeType {
	/// Attempt to get the bridge type from the environment.
	///
	/// This will only return `Some()` when the environment variable
	/// `CAFE_HARDWARE` is set to a proper value. If it's not set to a value
	/// then we will always return `None`.
	///
	/// A proper way to always get a bridge type would be doing something similar
	/// to what the scripts do which is fallback to a default:
	///
	/// ```rust
	/// let ty = cat_dev::mion::BridgeType::fetch_bridge_type().unwrap_or_default();
	/// ```
	#[must_use]
	pub fn fetch_bridge_type() -> Option<Self> {
		Self::hardware_type_to_value(std::env::var(HARDWARE_ENV_NAME).as_deref().ok())
	}

	/// Convert a known hardware type to a potential Bridge Type.
	fn hardware_type_to_value(hardware_type: Option<&str>) -> Option<Self> {
		match hardware_type {
			Some("ev") => Some(Self::Toucan),
			Some("ev_x4") => Some(Self::Mion),
			Some(val) => {
				if val.chars().skip(6).collect::<String>() == *"mp" {
					Some(Self::Mion)
				} else if let Some(num) = val
					.chars()
					.nth(6)
					.and_then(|character| char::to_digit(character, 10))
				{
					if num <= 2 {
						Some(Self::Toucan)
					} else {
						Some(Self::Mion)
					}
				} else {
					None
				}
			}
			_ => None,
		}
	}
}
impl Default for BridgeType {
	/// Shell scripts default to using MION if all things are the same.
	///
	/// In general you probably want to use [`BridgeType::fetch_bridge_type`],
	/// and should only use this default when using something like
	/// `unwrap_or_default` in case the bridge type isn't in the environment.
	fn default() -> Self {
		BridgeType::Mion
	}
}
impl Display for BridgeType {
	fn fmt(&self, fmt: &mut Formatter<'_>) -> FmtResult {
		match *self {
			Self::Mion => write!(fmt, "Mion"),
			Self::Toucan => write!(fmt, "Toucan"),
		}
	}
}

/// The state of bridges that are actively known on this host.
///
/// This is effectively just a list of bridges along with one of those being
/// set as the "default" bridge. A lot of this configuration is stored within
/// a system level directory, see [`BridgeHostState::get_default_host_path`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BridgeHostState {
	/// The fully existing configuration as we know it.
	configuration: Ini,
	/// The path we originally loaded ourselves from.
	loaded_from_path: PathBuf,
}
impl BridgeHostState {
	/// Attempt to load the bridge host state from the filesystem.
	///
	/// This is commonly referred to as `bridge_env.ini`, stored normally in
	/// Windows under the `%APPDATA%\bridge_env.ini` file. This is where tools
	/// like `getbridge`/`hostdisplayversion`/`setbridge` store which bridges
	/// you actually use, and which one you've set as the default bridge.
	///
	/// ## Errors
	///
	/// - If we cannot get the default host path for your OS.
	/// - Any error case from [`BridgeHostState::load_explicit_path`].
	pub async fn load() -> Result<Self, FSError> {
		let default_host_path =
			Self::get_default_host_path().ok_or(FSError::CantFindHostEnvPath)?;
		Self::load_explicit_path(default_host_path).await
	}

	/// Attempt to load the bridge host state file from the filesystem.
	///
	/// This is commonly referred to as `bridge_env.ini`, and is a small
	/// Windows (so UTF8) ini file, separated by newlines being `\r\n`.
	///
	/// ## Errors
	///
	/// - If we cannot read from the file on the file system.
	/// - If we cannot parse the data in the file as UTF8.
	/// - If we cannot parse the data as an INI file.
	pub async fn load_explicit_path(path: PathBuf) -> Result<Self, FSError> {
		if path.exists() {
			let as_bytes = tokio::fs::read(&path).await?;
			let as_string = String::from_utf8(as_bytes)?;

			let mut ini_contents = Ini::new_cs();
			ini_contents
				.read(as_string)
				.map_err(|ini_error| FSError::InvalidDataNeedsToBeINI(format!("{ini_error:?}")))?;

			Ok(Self {
				configuration: ini_contents,
				loaded_from_path: path,
			})
		} else {
			Ok(Self {
				configuration: Ini::new_cs(),
				loaded_from_path: path,
			})
		}
	}

	/// Grab the currently configured default host bridge.
	///
	/// This returns an option (representing if any default has been configured),
	/// and then will return an option for the ip address as the name could
	/// potentially point to a name that doesn't have an ip address set, or one
	/// that doesn't have a valid IPv4 address (as bridges are required to be
	/// IPv4).
	#[must_use]
	pub fn get_default_bridge(&self) -> Option<(String, Option<Ipv4Addr>)> {
		if let Some(host_key) = self
			.configuration
			.get(HOST_BRIDGES_SECTION, DEFAULT_BRIDGE_KEY)
		{
			let host_name = host_key
				.as_str()
				.trim_start_matches(BRIDGE_NAME_KEY_PREFIX)
				.to_owned();

			Some((
				host_name,
				self.configuration
					.get(HOST_BRIDGES_SECTION, &host_key)
					.and_then(|value| value.parse::<Ipv4Addr>().ok()),
			))
		} else {
			None
		}
	}

	/// Get an actively configured bridge.
	///
	/// Returns `(BridgeIP, IsDefault)`, if a bridge is actively configured.
	#[must_use]
	pub fn get_bridge(&self, bridge_name: &str) -> Option<(Option<Ipv4Addr>, bool)> {
		let default_key = self
			.configuration
			.get(HOST_BRIDGES_SECTION, DEFAULT_BRIDGE_KEY);
		let key = format!("{BRIDGE_NAME_KEY_PREFIX}{bridge_name}");
		let is_default = default_key.as_deref() == Some(key.as_str());

		self.configuration
			.get(HOST_BRIDGES_SECTION, &key)
			.map(|value| (value.parse::<Ipv4Addr>().ok(), is_default))
	}

	/// List all the bridges that are actively configured.
	///
	/// Returns a map of `<BridgeName, (BridgeIP, IsDefault)>`. The Bridge IP
	/// will be an empty option if we could not parse the value as an IPv4
	/// Address (i.e. the value is invalid), or the key did not have a value.
	#[must_use]
	pub fn list_bridges(&self) -> FnvHashMap<String, (Option<Ipv4Addr>, bool)> {
		let ini_data = self.configuration.get_map_ref();
		let Some(host_bridge_section) = ini_data.get(HOST_BRIDGES_SECTION) else {
			return FnvHashMap::with_capacity_and_hasher(0, BuildHasherDefault::default());
		};

		let default_key = if let Some(Some(value)) = host_bridge_section.get(DEFAULT_BRIDGE_KEY) {
			Some(value)
		} else {
			None
		};

		let mut bridges = FnvHashMap::default();
		for (key, value) in host_bridge_section {
			if key.as_str() == DEFAULT_BRIDGE_KEY
				|| !key.as_str().starts_with(BRIDGE_NAME_KEY_PREFIX)
			{
				continue;
			}

			let is_default = Some(key) == default_key;
			bridges.insert(
				key.trim_start_matches(BRIDGE_NAME_KEY_PREFIX).to_owned(),
				(
					value.as_ref().and_then(|val| val.parse::<Ipv4Addr>().ok()),
					is_default,
				),
			);
		}
		bridges
	}

	/// Insert a new bridge, or update it's value.
	///
	/// *note: this will be visible in memory immediately, but in order to
	/// persist it, or have it seen in another process you need to call
	/// [`BridgeHostState::write_to_disk`].*
	///
	/// ## Errors
	///
	/// If the bridge name is not ascii.
	/// If the bridge name is empty.
	/// If the bridge name is too long.
	pub fn upsert_bridge(
		&mut self,
		bridge_name: &str,
		bridge_ip: Ipv4Addr,
	) -> Result<(), MionAPIError> {
		if !bridge_name.is_ascii() {
			return Err(MionAPIError::DeviceNameMustBeAscii);
		}
		if bridge_name.is_empty() {
			return Err(MionAPIError::DeviceNameCannotBeEmpty);
		}
		if bridge_name.len() > 255 {
			return Err(MionAPIError::DeviceNameTooLong(bridge_name.len()));
		}

		self.configuration.set(
			HOST_BRIDGES_SECTION,
			&format!("{BRIDGE_NAME_KEY_PREFIX}{bridge_name}"),
			Some(format!("{bridge_ip}")),
		);
		Ok(())
	}

	/// Remove a bridge from the configuration file.
	///
	/// *note: this will be visible in memory immediately, but in order to
	/// persist it, or have it seen in another process you need to call
	/// [`BridgeHostState::write_to_disk`].*
	pub fn remove_bridge(&mut self, bridge_name: &str) {
		self.configuration.remove_key(
			HOST_BRIDGES_SECTION,
			&format!("{BRIDGE_NAME_KEY_PREFIX}{bridge_name}"),
		);
	}

	/// Remove the default bridge key from the configuration file.
	///
	/// *note: this will be visible in memory immediately, but in order to
	/// persist it, or have it seen in another process you need to call
	/// [`BridgeHostState::write_to_disk`].*
	pub fn remove_default_bridge(&mut self) {
		self.configuration
			.remove_key(HOST_BRIDGES_SECTION, DEFAULT_BRIDGE_KEY);
	}

	/// Set the default bridge for your host.
	///
	/// ## Errors
	///
	/// If you try setting the default bridge to a bridge that does not exist.
	/// If your device name is not ascii.
	/// If your device name is empty.
	/// If your device name is too long.
	pub fn set_default_bridge(&mut self, bridge_name: &str) -> Result<(), MionAPIError> {
		if !bridge_name.is_ascii() {
			return Err(MionAPIError::DeviceNameMustBeAscii);
		}
		if bridge_name.is_empty() {
			return Err(MionAPIError::DeviceNameCannotBeEmpty);
		}
		if bridge_name.len() > 255 {
			return Err(MionAPIError::DeviceNameTooLong(bridge_name.len()));
		}

		let bridge_key = format!("{BRIDGE_NAME_KEY_PREFIX}{bridge_name}");
		if self
			.configuration
			.get(HOST_BRIDGES_SECTION, &bridge_key)
			.is_none()
		{
			return Err(MionAPIError::DefaultDeviceMustExist);
		}

		self.configuration
			.set(HOST_BRIDGES_SECTION, DEFAULT_BRIDGE_KEY, Some(bridge_key));

		Ok(())
	}

	/// Write the current configuration to disk as a Windows INI file.
	///
	/// We always write the file with carriage returns `\r\n` (windows line
	/// endings), and in UTF-8. So we can always copy-paste the file onto
	/// a windows host and have it be read by the official tools without issue.
	///
	/// ## Errors
	///
	/// If we run into a system error when writing the file to the disk.
	pub async fn write_to_disk(&self) -> Result<(), FSError> {
		let mut serialized_configuration = self.configuration.writes();
		// Multiline is disabled -- so this is safe to check if we have actual carriage returns.
		if !serialized_configuration.contains("\r\n") {
			serialized_configuration = serialized_configuration.replace('\n', "\r\n");
		}

		let parent_dir = {
			let mut path = self.loaded_from_path.clone();
			path.pop();
			path
		};
		tokio::fs::create_dir_all(&parent_dir).await?;

		tokio::fs::write(
			&self.loaded_from_path,
			serialized_configuration.into_bytes(),
		)
		.await?;

		Ok(())
	}

	/// Get the path the Bridge Host State file was being loaded from.
	#[must_use]
	pub fn get_path(&self) -> &PathBuf {
		&self.loaded_from_path
	}

	/// Get the default path that the bridge host state is supposed to be stored
	/// in.
	///
	/// NOTE: this directory is not necissarily guaranteed to exist.
	///
	/// Returns none when we can't find an appropriate path to store bridge host
	/// state in.
	#[allow(
		// We explicitly use cfg blocks to block all escape.
		//
		// However, if you're on a non explicitly mentioned OS, we still want the
		// fallback.
		unreachable_code,
	)]
	#[must_use]
	pub fn get_default_host_path() -> Option<PathBuf> {
		#[cfg(target_os = "windows")]
		{
			use std::env::var as env_var;
			if let Ok(appdata_dir) = env_var("APPDATA") {
				let mut path = PathBuf::from(appdata_dir);
				path.push("bridge_env.ini");
				return Some(path);
			}

			return None;
		}

		#[cfg(target_os = "macos")]
		{
			use std::env::var as env_var;
			if let Ok(home_dir) = env_var("HOME") {
				let mut path = PathBuf::from(home_dir);
				path.push("Library");
				path.push("Application Support");
				path.push("bridge_env.ini");
				return Some(path);
			}

			return None;
		}

		#[cfg(any(
			target_os = "linux",
			target_os = "freebsd",
			target_os = "openbsd",
			target_os = "netbsd"
		))]
		{
			use std::env::var as env_var;
			if let Ok(xdg_config_dir) = env_var("XDG_CONFIG_HOME") {
				let mut path = PathBuf::from(xdg_config_dir);
				path.push("bridge_env.ini");
				return Some(path);
			} else if let Ok(home_dir) = env_var("HOME") {
				let mut path = PathBuf::from(home_dir);
				path.push(".config");
				path.push("bridge_env.ini");
				return Some(path);
			}

			return None;
		}

		None
	}
}

#[cfg(test)]
mod unit_tests {
	use super::*;

	#[test]
	pub fn bridge_type_parsing() {
		// No values get mapped to none.
		assert_eq!(
			BridgeType::hardware_type_to_value(None),
			None,
			"Empty hardware type did not map to a null bridge type?"
		);

		// Static Toucan & MION values.
		assert_eq!(
			BridgeType::hardware_type_to_value(Some("ev")),
			Some(BridgeType::Toucan),
			"Hardware type `ev` was not a `Toucan` bridge!"
		);
		assert_eq!(
			BridgeType::hardware_type_to_value(Some("ev_x4")),
			Some(BridgeType::Mion),
			"Hardware type `ev_x4` was not a `Mion` bridge!",
		);

		// Parsed Toucan & MION Values.
		assert_eq!(
			BridgeType::hardware_type_to_value(Some("catdevmp")),
			Some(BridgeType::Mion),
			"Hardware type `catdevmp` was not a `Mion` bridge!"
		);
		assert_eq!(
			BridgeType::hardware_type_to_value(Some("catdev200")),
			Some(BridgeType::Toucan),
			"Hardware type `catdev200` was not a `Toucan` bridge!"
		);

		// Check that we don't just do an endswith mp:
		assert_eq!(
			BridgeType::hardware_type_to_value(Some("catdevdevmp")),
			None,
			"Invalid hardware type did not get mapped to an empty bridge!",
		);
	}

	#[test]
	pub fn bridge_type_default_is_mion() {
		assert_eq!(
			BridgeType::default(),
			BridgeType::Mion,
			"Default bridge type was not mion!"
		);
	}

	#[test]
	pub fn can_find_host_env() {
		assert!(
			BridgeHostState::get_default_host_path().is_some(),
			"Failed to find the host state path for your particular OS, please file an issue!",
		);
	}

	#[tokio::test]
	pub async fn can_load_ini_files() {
		// First test loading the actual real configuration file completely not
		// touched by our tools, and just rsync'd into the source tree from the
		// real machine.
		let mut test_data_dir = PathBuf::from(
			std::env::var("CARGO_MANIFEST_DIR")
				.expect("Failed to read `CARGO_MANIFEST_DIR` to locate test files!"),
		);
		test_data_dir.push("src");
		test_data_dir.push("mion");
		test_data_dir.push("test-data");

		{
			let mut real_config_path = test_data_dir.clone();
			real_config_path.push("real-bridge-env.ini");
			let real_config = BridgeHostState::load_explicit_path(real_config_path)
				.await
				.expect("Failed to load a real `bridge_env.ini`!");

			let all_bridges = real_config.list_bridges();
			assert_eq!(
				all_bridges.len(),
				1,
				"Didn't find the single bridge that should've been in our real life `bridge_env.ini`!",
			);
			assert_eq!(
				all_bridges.get("00-25-5C-BA-5A-00").cloned(),
				Some((Some(Ipv4Addr::new(192, 168, 7, 40)), true)),
				"Failed to find a default bridge returned through listed bridges.",
			);
			assert_eq!(
				real_config.get_default_bridge(),
				Some((
					"00-25-5C-BA-5A-00".to_owned(),
					Some(Ipv4Addr::new(192, 168, 7, 40)),
				)),
				"Failed to get default bridge"
			);
			assert_eq!(
				real_config.get_bridge("00-25-5C-BA-5A-00"),
				Some((Some(Ipv4Addr::new(192, 168, 7, 40)), true))
			);
		}

		{
			let mut real_config_path = test_data_dir.clone();
			real_config_path.push("fake-valid-bridge-env.ini");
			let real_config = BridgeHostState::load_explicit_path(real_config_path)
				.await
				.expect("Failed to load a real `bridge_env.ini`!");

			assert_eq!(
				real_config.get_default_bridge(),
				Some((
					"00-25-5C-BA-5A-00".to_owned(),
					Some(Ipv4Addr::new(192, 168, 7, 40))
				)),
			);
			let all_bridges = real_config.list_bridges();
			assert_eq!(
				all_bridges.len(),
				3,
				"Didn't find the three bridge that should've been in our fake but valid `bridge_env.ini`!",
			);
			assert_eq!(
				all_bridges.get("00-25-5C-BA-5A-00").cloned(),
				Some((Some(Ipv4Addr::new(192, 168, 7, 40)), true)),
				"Failed to find a default bridge returned through listed bridges in fake but valid bridge env.",
			);
			assert_eq!(
				all_bridges.get("00-25-5C-BA-5A-01").cloned(),
				Some((Some(Ipv4Addr::new(192, 168, 7, 41)), false)),
				"Failed to find a non-default bridge returned through listed bridges in fake but valid bridge env.",
			);
			assert_eq!(
				all_bridges.get("00-25-5C-BA-5A-02").cloned(),
				Some((None, false)),
				"Failed to find a non-default bridge returned through listed bridges in fake but valid bridge env.",
			);
		}

		{
			let mut real_config_path = test_data_dir.clone();
			real_config_path.push("default-but-no-value.ini");
			let real_config = BridgeHostState::load_explicit_path(real_config_path)
				.await
				.expect("Failed to load a real `bridge_env.ini`!");

			assert_eq!(
				real_config.get_default_bridge(),
				Some(("00-25-5C-BA-5A-01".to_owned(), None)),
			);
			let all_bridges = real_config.list_bridges();
			assert_eq!(
				all_bridges.get("00-25-5C-BA-5A-00").cloned(),
				Some((Some(Ipv4Addr::new(192, 168, 7, 40)), false)),
				"Failed to find a default bridge returned through listed bridges in bridge env with default but no value.",
			);
		}

		{
			let mut real_config_path = test_data_dir.clone();
			real_config_path.push("default-but-invalid-value.ini");
			let real_config = BridgeHostState::load_explicit_path(real_config_path)
				.await
				.expect("Failed to load a real `bridge_env.ini`!");

			assert_eq!(
				real_config.get_default_bridge(),
				Some(("00-25-5C-BA-5A-00".to_owned(), None)),
			);
			let all_bridges = real_config.list_bridges();
			assert_eq!(
				all_bridges.get("00-25-5C-BA-5A-00").cloned(),
				Some((None, true)),
			);
		}

		{
			let mut real_config_path = test_data_dir.clone();
			real_config_path.push("invalid-ini-file.ini");

			assert!(matches!(
				BridgeHostState::load_explicit_path(real_config_path).await,
				Err(FSError::InvalidDataNeedsToBeINI(_)),
			));
		}
	}

	#[tokio::test]
	pub async fn can_set_and_write_to_file() {
		use tempfile::tempdir;
		use tokio::fs::File;

		let temporary_directory =
			tempdir().expect("Failed to create temporary directory for tests!");
		let mut path = PathBuf::from(temporary_directory.path());
		path.push("bridge_env_custom_made.ini");
		{
			File::create(&path)
				.await
				.expect("Failed to create test file to write too!");
		}
		let mut host_env = BridgeHostState::load_explicit_path(path.clone())
			.await
			.expect("Failed to load empty file to write too!");

		assert_eq!(
			host_env.set_default_bridge("00-25-5C-BA-5A-00"),
			Err(MionAPIError::DefaultDeviceMustExist),
		);
		assert_eq!(
			host_env.upsert_bridge("", Ipv4Addr::new(192, 168, 1, 1)),
			Err(MionAPIError::DeviceNameCannotBeEmpty),
		);
		assert_eq!(
			host_env.upsert_bridge("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", Ipv4Addr::new(192, 168, 1, 1)),
			Err(MionAPIError::DeviceNameTooLong(256)),
		);
		assert_eq!(
			host_env.upsert_bridge("ð’€€", Ipv4Addr::new(192, 168, 1, 1)),
			Err(MionAPIError::DeviceNameMustBeAscii),
		);

		assert!(
			host_env
				.upsert_bridge(" with spaces ", Ipv4Addr::new(192, 168, 1, 1))
				.is_ok()
		);
		assert!(host_env.set_default_bridge(" with spaces ").is_ok());
		assert!(
			host_env
				.upsert_bridge("00-25-5C-BA-5A-00", Ipv4Addr::new(192, 168, 1, 2))
				.is_ok()
		);
		assert!(
			host_env
				.upsert_bridge(" with spaces ", Ipv4Addr::new(192, 168, 1, 3))
				.is_ok()
		);
		assert!(host_env.set_default_bridge("00-25-5C-BA-5A-00").is_ok());
		assert!(host_env.write_to_disk().await.is_ok());

		let read_data = String::from_utf8(
			tokio::fs::read(path)
				.await
				.expect("Failed to read written data!"),
		)
		.expect("Written INI file wasn't UTF8?");
		// Ordering isn't guaranteed has to be one of these!
		let choices = [
			"[HOST_BRIDGES]\r\nBRIDGE_NAME_00-25-5C-BA-5A-00=192.168.1.2\r\nBRIDGE_DEFAULT_NAME=BRIDGE_NAME_00-25-5C-BA-5A-00\r\nBRIDGE_NAME_ with spaces =192.168.1.3\r\n".to_owned(),
			"[HOST_BRIDGES]\r\nBRIDGE_NAME_00-25-5C-BA-5A-00=192.168.1.2\r\nBRIDGE_NAME_ with spaces =192.168.1.3\r\nBRIDGE_DEFAULT_NAME=BRIDGE_NAME_00-25-5C-BA-5A-00\r\n".to_owned(),
			"[HOST_BRIDGES]\r\nBRIDGE_NAME_ with spaces =192.168.1.3\r\nBRIDGE_NAME_00-25-5C-BA-5A-00=192.168.1.2\r\nBRIDGE_DEFAULT_NAME=BRIDGE_NAME_00-25-5C-BA-5A-00\r\n".to_owned(),
			"[HOST_BRIDGES]\r\nBRIDGE_NAME_ with spaces =192.168.1.3\r\nBRIDGE_DEFAULT_NAME=BRIDGE_NAME_00-25-5C-BA-5A-00\r\nBRIDGE_NAME_00-25-5C-BA-5A-00=192.168.1.2\r\n".to_owned(),
			"[HOST_BRIDGES]\r\nBRIDGE_DEFAULT_NAME=BRIDGE_NAME_00-25-5C-BA-5A-00\r\nBRIDGE_NAME_ with spaces =192.168.1.3\r\nBRIDGE_NAME_00-25-5C-BA-5A-00=192.168.1.2\r\n".to_owned(),
			"[HOST_BRIDGES]\r\nBRIDGE_DEFAULT_NAME=BRIDGE_NAME_00-25-5C-BA-5A-00\r\nBRIDGE_NAME_00-25-5C-BA-5A-00=192.168.1.2\r\nBRIDGE_NAME_ with spaces =192.168.1.3\r\n".to_owned(),
		];

		if !choices.contains(&read_data) {
			panic!("Unexpected host bridges ini file:\n{read_data}");
		}
	}
}