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

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

use necsim_core::lineage::Lineage;

#[derive(Deserialize)]
#[serde(try_from = "LineageFileSaverRaw")]
#[allow(clippy::module_name_repetitions)]
pub struct LineageFileSaver {
    file: File,
    path: PathBuf,
    temp: bool,
}

impl Drop for LineageFileSaver {
    fn drop(&mut self) {
        if self.temp {
            std::mem::drop(fs::remove_file(&self.path));
        }
    }
}

impl fmt::Debug for LineageFileSaver {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct(stringify!(LineageFileSaver))
            .field("path", &self.path)
            .finish_non_exhaustive()
    }
}

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

impl LineageFileSaver {
    /// # Errors
    ///
    /// Fails if a new lineage file cannot be created at `path`
    pub fn try_new(path: &Path) -> anyhow::Result<Self> {
        let file = OpenOptions::new().create_new(true).write(true).open(path)?;

        Ok(Self {
            file,
            path: path.to_owned(),
            temp: true,
        })
    }

    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// # Errors
    ///
    /// Fails if a the lineages could not be written to the file at `path`
    pub fn write<'a, I: Iterator<Item = &'a Lineage>>(mut self, lineages: I) -> anyhow::Result<()> {
        let mut serializer =
            bincode::Serializer::new(BufWriter::new(&mut self.file), bincode::options());

        serializer.collect_seq(lineages)?;

        self.temp = false;

        Ok(())
    }
}

impl TryFrom<LineageFileSaverRaw> for LineageFileSaver {
    type Error = anyhow::Error;

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

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