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
use crate::internal::*;
use std::rc::Rc;

use tract_ndarray::Array;
use TValue::*;

#[derive(Clone, PartialEq, Eq)]
pub enum TValue {
    Const(Arc<Tensor>),
    Var(Rc<Tensor>),
}

impl std::fmt::Debug for TValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (**self).fmt(f)
    }
}

impl TValue {
    pub fn is_exclusive(&self) -> bool {
        match self {
            Var(it) => Rc::strong_count(it) == 1,
            Const(_) => false,
        }
    }

    pub fn from_const(t: Arc<Tensor>) -> Self {
        Const(t)
    }
}

impl From<Tensor> for TValue {
    fn from(t: Tensor) -> Self {
        TValue::Var(std::rc::Rc::new(t))
    }
}

impl std::ops::Deref for TValue {
    type Target = Tensor;
    fn deref(&self) -> &Self::Target {
        match self {
            Const(it) => it,
            Var(it) => it,
        }
    }
}

impl std::borrow::Borrow<Tensor> for TValue {
    fn borrow(&self) -> &Tensor {
        self
    }
}

impl IntoTensor for TValue {
    fn into_tensor(self) -> Tensor {
        match self {
            Var(it) => Rc::try_unwrap(it).unwrap_or_else(|t| (*t).clone()),
            Const(it) => it.into_tensor(),
        }
    }
}

impl IntoArcTensor for TValue {
    fn into_arc_tensor(self) -> Arc<Tensor> {
        match self {
            Var(ref _it) => self.into_tensor().into_arc_tensor(),
            Const(t) => t,
        }
    }
}

pub trait IntoTValue {
    fn into_tvalue(self) -> TValue;
}

impl IntoTValue for Tensor {
    fn into_tvalue(self) -> TValue {
        self.into_tensor().into()
    }
}

impl IntoTValue for Arc<Tensor> {
    fn into_tvalue(self) -> TValue {
        Const(self)
    }
}

impl<D: ::ndarray::Dimension, T: Datum> IntoTValue for Array<T, D> {
    fn into_tvalue(self) -> TValue {
        Tensor::from(self).into_tvalue()
    }
}