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
use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::ops::Deref;
use destream::{en, EncodeMap};
use tc_transact::IntoView;
use tcgeneric::Map;
use crate::fs::Dir;
use crate::scalar::Scalar;
use crate::state::State;
use crate::txn::Txn;
use super::{InstanceClass, Object};
#[derive(Clone)]
pub struct InstanceExt<T: tcgeneric::Instance> {
parent: Box<T>,
class: InstanceClass,
}
impl<T: tcgeneric::Instance> InstanceExt<T> {
pub fn new(parent: T, class: InstanceClass) -> InstanceExt<T> {
InstanceExt {
parent: Box::new(parent),
class,
}
}
pub fn parent(&self) -> &T {
&self.parent
}
pub fn proto(&self) -> &Map<Scalar> {
self.class.proto()
}
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,
})
}
}
impl<T: tcgeneric::Instance> tcgeneric::Instance for InstanceExt<T> {
type Class = InstanceClass;
fn class(&self) -> Self::Class {
self.class.clone()
}
}
impl<'en, T: tcgeneric::Instance + en::IntoStream<'en> + 'en> en::IntoStream<'en>
for InstanceExt<T>
{
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.extends().to_string(), self.parent)?;
map.end()
}
}
impl<T: tcgeneric::Instance> Deref for InstanceExt<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.parent
}
}
impl<'en> IntoView<'en, Dir> for InstanceExt<State> {
type Txn = Txn;
type View = InstanceView;
fn into_view(self, txn: Txn) -> InstanceView {
InstanceView {
instance: self,
txn,
}
}
}
impl<T: tcgeneric::Instance> From<InstanceExt<T>> for State
where
State: From<T>,
{
fn from(instance: InstanceExt<T>) -> State {
let parent = Box::new((*instance.parent).into());
let class = instance.class;
let instance = InstanceExt { parent, class };
State::Object(Object::Instance(instance))
}
}
impl<T: tcgeneric::Instance> fmt::Display for InstanceExt<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} Object", tcgeneric::Instance::class(self))
}
}
pub struct InstanceView {
instance: InstanceExt<State>,
txn: Txn,
}
impl<'en> en::IntoStream<'en> for InstanceView {
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.instance.class.extends().to_string(),
self.instance.parent.into_view(self.txn),
)?;
map.end()
}
}