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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
//! User-defined instance implementation.

use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::ops::Deref;

use async_hash::Hash;
use async_trait::async_trait;
use destream::{en, EncodeMap};
use futures::future::TryFutureExt;
use futures::stream::{FuturesUnordered, TryStreamExt};
use log::debug;
use safecast::TryCastFrom;
use sha2::digest::{Digest, Output};
use sha2::Sha256;

use tc_error::*;
use tc_transact::IntoView;
use tc_value::{Link, Value};
use tcgeneric::Map;

use crate::fs::Dir;
use crate::scalar::Scalar;
use crate::state::{State, StateView, ToState};
use crate::txn::Txn;

use super::{InstanceClass, Object};

/// A user-defined instance, subclassing `T`.
#[derive(Clone)]
pub struct InstanceExt<T: tcgeneric::Instance> {
    parent: Box<T>,
    class: InstanceClass,
    members: Map<State>,
}

impl<T: tcgeneric::Instance> InstanceExt<T> {
    /// Construct a new instance of the given user-defined [`InstanceClass`].
    pub fn new(parent: T, class: InstanceClass) -> InstanceExt<T> {
        InstanceExt {
            parent: Box::new(parent),
            class,
            members: Map::default(),
        }
    }

    /// Construct a new instance of an anonymous class.
    pub fn anonymous(parent: T, class: InstanceClass, members: Map<State>) -> InstanceExt<T> {
        InstanceExt {
            parent: Box::new(parent),
            class,
            members,
        }
    }

    /// Borrow the members of this instance.
    pub fn members(&self) -> &Map<State> {
        &self.members
    }

    /// Borrow the parent of this instance.
    pub fn parent(&self) -> &T {
        &self.parent
    }

    /// Borrow the class prototype of this instance.
    pub fn proto(&self) -> &Map<Scalar> {
        self.class.proto()
    }

    /// Convert the native type of this instance, if possible.
    pub fn try_into<E, O: tcgeneric::Instance + TryFrom<T, Error = E>>(
        self,
    ) -> Result<InstanceExt<O>, E> {
        let class = self.class;
        let parent = (*self.parent).try_into()?;

        Ok(InstanceExt {
            parent: Box::new(parent),
            class,
            members: self.members,
        })
    }
}

impl<T: tcgeneric::Instance> tcgeneric::Instance for InstanceExt<T> {
    type Class = InstanceClass;

    fn class(&self) -> Self::Class {
        self.class.clone()
    }
}

impl<T: tcgeneric::Instance> Deref for InstanceExt<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.parent
    }
}

impl InstanceExt<State> {
    pub async fn hash(self, txn: Txn) -> TCResult<Output<Sha256>> {
        let parent = self.parent.hash(txn).await?;

        let mut hasher = Sha256::default();
        hasher.update(Hash::<Sha256>::hash(self.class));
        hasher.update(&parent);
        Ok(hasher.finalize())
    }
}

#[async_trait]
impl<'en> IntoView<'en, Dir> for InstanceExt<State> {
    type Txn = Txn;
    type View = InstanceView<'en>;

    async fn into_view(self, txn: Txn) -> TCResult<InstanceView<'en>> {
        let mut members = if self.class.is_anonymous() {
            self.class.proto().clone().into_iter().collect()
        } else {
            Map::<State>::new()
        };

        for (id, state) in self.members {
            members.insert(id, state);
        }

        let mut into_view: FuturesUnordered<_> = members
            .into_iter()
            .map(|(id, member)| member.into_view(txn.clone()).map_ok(|view| (id, view)))
            .collect();

        let mut members = Map::new();
        while let Some((id, view)) = into_view.try_next().await? {
            members.insert(id, view);
        }

        Ok(InstanceView {
            class: self.class.link(),
            members,
        })
    }
}

impl<T: tcgeneric::Instance + fmt::Display> TryCastFrom<InstanceExt<T>> for Scalar
where
    Scalar: TryCastFrom<T>,
{
    fn can_cast_from(instance: &InstanceExt<T>) -> bool {
        debug!("Scalar::can_cast_from {}?", instance);

        Self::can_cast_from(&(*instance).parent)
    }

    fn opt_cast_from(instance: InstanceExt<T>) -> Option<Self> {
        Self::opt_cast_from(*instance.parent)
    }
}

impl<T: tcgeneric::Instance + fmt::Display> TryCastFrom<InstanceExt<T>> for Value
where
    Value: TryCastFrom<T>,
{
    fn can_cast_from(instance: &InstanceExt<T>) -> bool {
        debug!("Value::can_cast_from {}?", instance);

        Self::can_cast_from(&(*instance).parent)
    }

    fn opt_cast_from(instance: InstanceExt<T>) -> Option<Self> {
        Self::opt_cast_from(*instance.parent)
    }
}

impl<T: tcgeneric::Instance + ToState> ToState for InstanceExt<T> {
    fn to_state(&self) -> State {
        let parent = Box::new(self.parent.to_state());
        let class = self.class.clone();
        let members = self.members.clone();
        let instance = InstanceExt {
            parent,
            class,
            members,
        };

        State::Object(Object::Instance(instance))
    }
}

impl<T: tcgeneric::Instance + fmt::Debug> fmt::Debug for InstanceExt<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?} instance", tcgeneric::Instance::class(self))
    }
}

impl<T: tcgeneric::Instance + fmt::Display> fmt::Display for InstanceExt<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} instance", tcgeneric::Instance::class(self))
    }
}

/// A view of an [`InstanceExt`] at a specific [`Txn`], used for serialization.
pub struct InstanceView<'en> {
    class: Link,
    members: Map<StateView<'en>>,
}

impl<'en> en::IntoStream<'en> for InstanceView<'en> {
    fn into_stream<E: en::Encoder<'en>>(self, encoder: E) -> Result<E::Ok, E::Error> {
        let mut map = encoder.encode_map(Some(1))?;
        map.encode_entry(self.class.to_string(), self.members)?;
        map.end()
    }
}