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 super::dep_node::{DepNode, Dependent};
use std::{
    any::type_name,
    borrow::Borrow,
    fmt::{Debug, Formatter, Result as FmtResult},
};

/// A CacheCell represents the storage used for a particular input/output pair
/// on the heap.
#[derive(Clone, Default, Hash, Eq, PartialEq)]
pub(crate) struct CacheCell<Input, Output> {
    dep: DepNode,
    input: Input,
    output: Output,
}

impl<Input, Output> CacheCell<Input, Output> {
    pub fn new(input: Input, output: Output, dep: DepNode) -> Self {
        Self { dep, input, output }
    }

    /// Return a reference to the output if the input is equal, marking it live
    /// in the process. If get fails, returns its own `Dependent` to be used as
    /// a dependency of any queries which are invoked to re-initialize this
    /// cell.
    pub fn get<Arg>(&self, input: &Arg, dependent: Dependent) -> Result<&Output, Dependent>
    where
        Arg: PartialEq<Input> + ?Sized,
        Input: Borrow<Arg>,
    {
        self.dep.root_read(dependent);
        if input == &self.input {
            Ok(&self.output)
        } else {
            Err(self.dep.as_dependent())
        }
    }

    /// Store a new input/output and mark the storage live.
    pub fn store(&mut self, input: Input, output: Output, dependent: Dependent, revision: u64) {
        self.dep.root_write(dependent, revision);
        self.input = input;
        self.output = output;
    }

    pub fn is_live(&self) -> bool {
        self.dep.is_known_live()
    }

    pub fn update_liveness(&mut self, current_revision: u64) {
        self.dep.update_liveness(current_revision);
    }

    pub fn mark_dead(&mut self) {
        self.dep.mark_dead();
    }
}

impl<Input, Output> Debug for CacheCell<Input, Output>
where
    Input: 'static,
    Output: 'static,
{
    // someday specialization might save us from these lame debug impls?
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        f.debug_map()
            .entry(&"input", &type_name::<Input>())
            .entry(&"output", &type_name::<Output>())
            .finish()
    }
}