Coverage Report

Created: 2024-02-20 21:15

/builds/xfbs/cindy/common/src/cache/value.rs
Line
Count
Source (jump to first uncovered line)
1
use std::{any::Any, rc::Rc, sync::Arc};
2
3
0
#[derive(Clone, Debug, PartialEq, Eq)]
4
pub struct Value<T> {
5
    /// Valid means the data is usable.
6
    valid: bool,
7
    data: Option<T>,
8
}
9
10
pub type RcValue<V = dyn Any> = Value<Rc<V>>;
11
pub type ArcValue<V = dyn Any + Send + Sync> = Value<Arc<V>>;
12
13
impl Value<Rc<dyn Any>> {
14
0
    pub fn downcast<T: 'static>(self) -> Option<Value<Rc<T>>> {
15
0
        let value = Value {
16
0
            valid: self.valid,
17
0
            data: match self.data {
18
0
                None => None,
19
0
                Some(data) => Some(data.downcast::<T>().ok()?),
20
            },
21
        };
22
0
        Some(value)
23
0
    }
24
}
25
26
impl Value<Arc<dyn Any + Send + Sync>> {
27
0
    pub fn downcast<T: Any + Send + Sync>(self) -> Option<Value<Arc<T>>> {
28
0
        let value = Value {
29
0
            valid: self.valid,
30
0
            data: match self.data {
31
0
                None => None,
32
0
                Some(data) => Some(data.downcast::<T>().ok()?),
33
            },
34
        };
35
0
        Some(value)
36
0
    }
37
}
38
39
impl<T> Default for Value<T> {
40
0
    fn default() -> Self {
41
0
        Self {
42
0
            valid: false,
43
0
            data: None,
44
0
        }
45
0
    }
46
}
47
48
impl<T> Value<T> {
49
0
    pub fn new(data: T) -> Self {
50
0
        Self {
51
0
            data: Some(data),
52
0
            valid: true,
53
0
        }
54
0
    }
55
56
0
    pub fn data(&self) -> Option<&T> {
57
0
        self.data.as_ref()
58
0
    }
59
60
0
    pub fn valid(&self) -> bool {
61
0
        self.valid
62
0
    }
63
64
0
    pub fn invalidate(&mut self) {
65
0
        self.valid = false;
66
0
    }
67
}