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
216
217
218
219
use std::convert::{TryFrom, TryInto};
use std::iter::{FromIterator, IntoIterator, Iterator};
use std::marker::PhantomData;
use crate::errors::Error;
use crate::object::{IsObjectRef, Object, ObjectPtr, ObjectRef};
use crate::{
external,
function::{Function, Result},
ArgValue, RetValue,
};
#[repr(C)]
#[derive(Clone)]
pub struct Array<T: IsObjectRef> {
object: ObjectRef,
_data: PhantomData<T>,
}
external! {
#[name("runtime.ArrayGetItem")]
fn array_get_item(array: ObjectRef, index: isize) -> ObjectRef;
#[name("runtime.ArraySize")]
fn array_size(array: ObjectRef) -> i64;
}
impl<T: IsObjectRef + 'static> IsObjectRef for Array<T> {
type Object = Object;
fn as_ptr(&self) -> Option<&ObjectPtr<Self::Object>> {
self.object.as_ptr()
}
fn into_ptr(self) -> Option<ObjectPtr<Self::Object>> {
self.object.into_ptr()
}
fn from_ptr(object_ptr: Option<ObjectPtr<Self::Object>>) -> Self {
let object_ref = match object_ptr {
Some(o) => o.into(),
_ => panic!(),
};
Array {
object: object_ref,
_data: PhantomData,
}
}
}
impl<T: IsObjectRef> Array<T> {
pub fn from_vec(data: Vec<T>) -> Result<Array<T>> {
let iter = data.iter().map(T::into_arg_value).collect();
let func = Function::get("runtime.Array").expect(
"runtime.Array function is not registered, this is most likely a build or linking error",
);
let array_data: ObjectPtr<Object> = func.invoke(iter)?.try_into()?;
debug_assert!(
array_data.count() >= 1,
"array reference count is {}",
array_data.count()
);
Ok(Array {
object: array_data.into(),
_data: PhantomData,
})
}
pub fn get(&self, index: isize) -> Result<T>
where
T: TryFrom<RetValue, Error = Error>,
{
let oref: ObjectRef = array_get_item(self.object.clone(), index)?;
oref.downcast()
}
pub fn len(&self) -> i64 {
array_size(self.object.clone()).expect("size should never fail")
}
}
impl<T: IsObjectRef> std::fmt::Debug for Array<T> {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
let as_vec: Vec<T> = self.clone().into_iter().collect();
write!(formatter, "{:?}", as_vec)
}
}
pub struct IntoIter<T: IsObjectRef> {
array: Array<T>,
pos: isize,
size: isize,
}
impl<T: IsObjectRef> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.pos < self.size {
let item =
self.array.get(self.pos)
.expect("Can not index as in-bounds position after bounds checking.\nNote: this error can only be do to an uncaught issue with API bindings.");
self.pos += 1;
Some(item)
} else {
None
}
}
}
impl<T: IsObjectRef> IntoIterator for Array<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
let size = self.len() as isize;
IntoIter {
array: self,
pos: 0,
size: size,
}
}
}
impl<T: IsObjectRef> FromIterator<T> for Array<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Array::from_vec(iter.into_iter().collect()).unwrap()
}
}
impl<'a, T: IsObjectRef> From<&'a Array<T>> for ArgValue<'a> {
fn from(array: &'a Array<T>) -> ArgValue<'a> {
(&array.object).into()
}
}
impl<T: IsObjectRef> From<Array<T>> for RetValue {
fn from(array: Array<T>) -> RetValue {
array.object.into()
}
}
impl<'a, T: IsObjectRef> TryFrom<ArgValue<'a>> for Array<T> {
type Error = Error;
fn try_from(array: ArgValue<'a>) -> Result<Array<T>> {
let object_ref: ObjectRef = array.try_into()?;
Ok(Array {
object: object_ref,
_data: PhantomData,
})
}
}
impl<'a, T: IsObjectRef> TryFrom<RetValue> for Array<T> {
type Error = Error;
fn try_from(array: RetValue) -> Result<Array<T>> {
let object_ref = array.try_into()?;
Ok(Array {
object: object_ref,
_data: PhantomData,
})
}
}
#[cfg(test)]
mod tests {
use super::Array;
use crate::function::Result;
use crate::object::{IsObjectRef, ObjectRef};
use crate::string::String;
#[test]
fn create_array_and_get() -> Result<()> {
let vec: Vec<String> = vec!["foo".into(), "bar".into(), "baz".into()];
let array = Array::from_vec(vec)?;
assert_eq!(array.get(0)?.to_string(), "foo");
assert_eq!(array.get(1)?.to_string(), "bar");
assert_eq!(array.get(2)?.to_string(), "baz");
Ok(())
}
#[test]
fn downcast() -> Result<()> {
let vec: Vec<String> = vec!["foo".into(), "bar".into(), "baz".into()];
let array: ObjectRef = ObjectRef::from_ptr(Array::from_vec(vec)?.into_ptr());
let array: Array<ObjectRef> = array.downcast::<Array<ObjectRef>>().unwrap();
assert_eq!(array.get(1)?.downcast::<String>().unwrap(), "bar");
Ok(())
}
}