1
//! Record of the entity lookups a script performs, for the reference preflight.
2

            
3
use std::sync::{Arc, Mutex};
4

            
5
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6
pub enum LookupKind {
7
    Account,
8
    Commodity,
9
}
10

            
11
#[derive(Debug, Clone, PartialEq, Eq)]
12
pub struct Lookup {
13
    pub kind: LookupKind,
14
    pub key: String,
15
    /// A logical-row key, which takes an id only.
16
    pub row_key: bool,
17
}
18

            
19
/// Shared by every clone of the context that carries it.
20
#[derive(Debug, Clone, Default)]
21
pub struct LookupLog(Arc<Mutex<Vec<Lookup>>>);
22

            
23
impl LookupLog {
24
12
    pub(crate) fn record(&self, kind: LookupKind, key: &str) {
25
12
        if let Ok(mut lookups) = self.0.lock() {
26
12
            lookups.push(Lookup {
27
12
                kind,
28
12
                key: key.to_string(),
29
12
                row_key: false,
30
12
            });
31
        }
32
12
    }
33

            
34
    /// The lookups recorded so far, in call order.
35
    #[must_use]
36
7
    pub fn lookups(&self) -> Vec<Lookup> {
37
7
        self.0
38
7
            .lock()
39
7
            .map(|lookups| lookups.clone())
40
            .unwrap_or_default()
41
7
    }
42
}
43

            
44
#[cfg(test)]
45
mod tests {
46
    use super::*;
47

            
48
    #[test]
49
1
    fn clones_share_one_record_in_call_order() {
50
1
        let log = LookupLog::default();
51
1
        let clone = log.clone();
52
1
        clone.record(LookupKind::Account, "Cafe");
53
1
        log.record(LookupKind::Commodity, "USD");
54

            
55
2
        let keys: Vec<_> = log.lookups().into_iter().map(|l| (l.kind, l.key)).collect();
56
1
        assert_eq!(
57
1
            keys,
58
1
            [
59
1
                (LookupKind::Account, "Cafe".to_string()),
60
1
                (LookupKind::Commodity, "USD".to_string())
61
1
            ]
62
        );
63
1
    }
64
}