scatter_net/legacy/net/config/methods/
from_file.rs

1use std::{
2    fs::{exists, File},
3    io::Read,
4    path::Path,
5};
6
7use crate::NetConfig;
8
9impl NetConfig {
10    /// Attempts to read a file and deserialize it into a `NetConfig`.
11    pub fn from_file<P>(filename: P) -> Result<Self, NetConfigFromFileError>
12    where
13        P: AsRef<Path>,
14    {
15        let filename = filename.as_ref();
16
17        if !exists(filename)? {
18            return Ok(Self::default());
19        }
20
21        let mut file = File::open(filename)?;
22        let mut contents = String::new();
23
24        file.read_to_string(&mut contents)?;
25
26        Ok(contents.parse()?)
27    }
28}
29
30#[derive(thiserror::Error, Debug)]
31pub enum NetConfigFromFileError {
32    #[error(transparent)]
33    FromStr(#[from] crate::NetConfigFromStrError),
34    #[error(transparent)]
35    IO(#[from] std::io::Error),
36}