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
use std::{
    convert::TryFrom,
    fs::OpenOptions,
    io::BufReader,
    path::{Path, PathBuf},
};

use serde::{Deserialize, Serialize, Serializer};

use necsim_core::lineage::Lineage;

#[derive(Debug, Deserialize, Clone)]
#[serde(try_from = "LineageFileLoaderRaw")]
#[allow(clippy::module_name_repetitions)]
pub struct LineageFileLoader {
    lineages: Vec<Lineage>,
    path: PathBuf,
}

impl Serialize for LineageFileLoader {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        LineageFileLoaderRaw {
            file: self.path.clone(),
        }
        .serialize(serializer)
    }
}

impl LineageFileLoader {
    /// # Errors
    ///
    /// Fails if the `path` cannot be read as a list of lineages
    pub fn try_new(path: &Path) -> anyhow::Result<Self> {
        let file = OpenOptions::new().read(true).write(false).open(path)?;

        let mut deserializer =
            bincode::Deserializer::with_reader(BufReader::new(file), bincode::options());

        let lineages = <Vec<Lineage>>::deserialize(&mut deserializer)?;

        Ok(Self {
            lineages,
            path: path.to_owned(),
        })
    }

    #[must_use]
    pub fn into_lineages(self) -> Vec<Lineage> {
        self.lineages
    }

    #[must_use]
    pub fn get_lineages(&self) -> &[Lineage] {
        &self.lineages
    }
}

impl TryFrom<LineageFileLoaderRaw> for LineageFileLoader {
    type Error = anyhow::Error;

    fn try_from(raw: LineageFileLoaderRaw) -> Result<Self, Self::Error> {
        Self::try_new(&raw.file)
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename = "LineageFileLoader")]
#[serde(deny_unknown_fields)]
struct LineageFileLoaderRaw {
    file: PathBuf,
}