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
use alloc::collections::BinaryHeap;
use core::cmp::Reverse;

use necsim_core::{
    cogs::{Backup, ImmigrationEntry, MathsCore},
    lineage::MigratingLineage,
};

#[allow(clippy::module_name_repetitions)]
#[derive(Debug, Default)]
pub struct BufferedImmigrationEntry {
    immigrants: BinaryHeap<Reverse<MigratingLineage>>,
}

#[contract_trait]
impl Backup for BufferedImmigrationEntry {
    unsafe fn backup_unchecked(&self) -> Self {
        Self {
            immigrants: self
                .immigrants
                .iter()
                .map(|migrating_lineage| Reverse(migrating_lineage.0.backup_unchecked()))
                .collect(),
        }
    }
}

#[contract_trait]
impl<M: MathsCore> ImmigrationEntry<M> for BufferedImmigrationEntry {
    #[must_use]
    fn next_optional_immigration(&mut self) -> Option<MigratingLineage> {
        self.immigrants.pop().map(|immigrant| immigrant.0)
    }

    #[must_use]
    fn peek_next_immigration(&self) -> Option<&MigratingLineage> {
        self.immigrants.peek().map(|immigrant| &immigrant.0)
    }
}

impl BufferedImmigrationEntry {
    pub fn reset(&mut self) {
        self.immigrants.clear();
    }

    pub fn push(&mut self, immigrant: MigratingLineage) {
        self.immigrants.push(Reverse(immigrant));
    }

    pub fn extend(&mut self, immigrants: impl Iterator<Item = MigratingLineage>) {
        self.immigrants.extend(immigrants.map(Reverse));
    }
}