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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
use log::warn;
use std::cell::RefCell;
use std::convert::TryInto;
use std::ffi::c_void;
use std::mem;
use std::ptr;
use std::rc::Rc;
use crate::convert::Error;
use crate::def::ClassLike;
use crate::sys;
use crate::value::types::{Ruby, Rust};
use crate::value::{self, Value};
use crate::{Mrb, MrbError};
pub trait RustBackedValue
where
Self: 'static + Sized,
{
unsafe fn try_into_ruby(
self,
interp: &Mrb,
slf: Option<sys::mrb_value>,
) -> Result<Value, MrbError> {
let mrb = interp.borrow().mrb;
let spec = interp
.borrow()
.class_spec::<Self>()
.ok_or(MrbError::ConvertToRuby(Error {
from: Rust::Object,
to: Ruby::Object,
}))?;
let rclass = spec
.borrow()
.rclass(interp)
.ok_or(MrbError::ConvertToRuby(Error {
from: Rust::Object,
to: Ruby::Object,
}))?;
let mut slf = if let Some(slf) = slf {
slf
} else {
let args = self.new_obj_args(interp);
if args.len() > value::MRB_FUNCALL_ARGC_MAX {
warn!(
"Too many args supplied to initialize: given {}, max {}.",
args.len(),
value::MRB_FUNCALL_ARGC_MAX
);
return Err(MrbError::TooManyArgs {
given: args.len(),
max: value::MRB_FUNCALL_ARGC_MAX,
});
}
let len = args.len().try_into().unwrap_or_default();
sys::mrb_obj_new(mrb, rclass, len, args.as_ptr() as *const sys::mrb_value)
};
let data = Rc::new(RefCell::new(self));
let ptr = Rc::into_raw(data);
sys::mrb_sys_data_init(&mut slf, ptr as *mut c_void, spec.borrow().data_type());
Ok(Value::new(interp, slf))
}
unsafe fn try_from_ruby(interp: &Mrb, slf: &Value) -> Result<Rc<RefCell<Self>>, MrbError> {
let mrb = interp.borrow().mrb;
if slf.ruby_type() != Ruby::Data {
return Err(MrbError::ConvertToRust(Error {
from: slf.ruby_type(),
to: Rust::Object,
}));
}
let spec = interp
.borrow()
.class_spec::<Self>()
.ok_or_else(|| MrbError::NotDefined("class".to_owned()))?;
if let Some(rclass) = spec.borrow().rclass(interp) {
if !ptr::eq(sys::mrb_sys_class_of_value(mrb, slf.inner()), rclass) {
return Err(MrbError::ConvertToRust(Error {
from: slf.ruby_type(),
to: Rust::Object,
}));
}
} else {
return Err(MrbError::NotDefined("class".to_owned()));
}
let ptr = {
let borrow = spec.borrow();
sys::mrb_data_get_ptr(mrb, slf.inner(), borrow.data_type())
};
let data = Rc::from_raw(ptr as *const RefCell<Self>);
let value = Rc::clone(&data);
mem::forget(data);
Ok(value)
}
fn new_obj_args(&self, interp: &Mrb) -> Vec<sys::mrb_value> {
let _ = interp;
vec![]
}
}
impl<T> RustBackedValue for Box<T> where T: RustBackedValue {}
#[cfg(test)]
mod tests {
use std::rc::Rc;
use crate::convert::object::RustBackedValue;
use crate::convert::FromMrb;
use crate::def::{rust_data_free, ClassLike, Define};
use crate::sys;
use crate::value::{Value, ValueLike};
struct Container {
inner: String,
}
impl Container {
unsafe extern "C" fn value(
mrb: *mut sys::mrb_state,
slf: sys::mrb_value,
) -> sys::mrb_value {
let interp = unwrap_interpreter!(mrb);
let value = Value::new(&interp, slf);
if let Ok(container) = Self::try_from_ruby(&interp, &value) {
let borrow = container.borrow();
Value::from_mrb(&interp, borrow.inner.as_str()).inner()
} else {
Value::from_mrb(&interp, None::<Value>).inner()
}
}
}
impl RustBackedValue for Container {}
#[derive(Default)]
struct Other {
_inner: bool,
}
impl RustBackedValue for Other {}
#[test]
fn convert_obj_roundtrip() {
let interp = crate::interpreter().expect("mrb init");
let spec = interp.borrow_mut().def_class::<Container>(
"Container",
None,
Some(rust_data_free::<Container>),
);
spec.borrow_mut().mrb_value_is_rust_backed(true);
spec.borrow_mut()
.add_method("value", Container::value, sys::mrb_args_none());
spec.borrow().define(&interp).expect("class install");
let obj = Container {
inner: "contained string contents".to_owned(),
};
let value = unsafe { obj.try_into_ruby(&interp, None) }.expect("convert");
let class = value.funcall::<Value, _, _>("class", &[]).expect("funcall");
assert_eq!(class.to_s(), "Container");
let data = unsafe { Container::try_from_ruby(&interp, &value) }.expect("convert");
assert_eq!(Rc::strong_count(&data), 2);
assert_eq!(&data.borrow().inner, "contained string contents");
drop(data);
let inner = value
.funcall::<String, _, _>("value", &[])
.expect("funcall");
assert_eq!(&inner, "contained string contents");
}
#[test]
fn convert_obj_not_data() {
let interp = crate::interpreter().expect("mrb init");
let spec = interp.borrow_mut().def_class::<Container>(
"Container",
None,
Some(rust_data_free::<Container>),
);
spec.borrow_mut().mrb_value_is_rust_backed(true);
spec.borrow_mut()
.add_method("value", Container::value, sys::mrb_args_none());
spec.borrow().define(&interp).expect("class install");
let spec = interp.borrow_mut().def_class::<Box<Other>>(
"Other",
None,
Some(rust_data_free::<Container>),
);
spec.borrow_mut().mrb_value_is_rust_backed(true);
spec.borrow().define(&interp).expect("class install");
let value = Value::from_mrb(&interp, "string");
let class = value.funcall::<Value, _, _>("class", &[]).expect("funcall");
assert_eq!(class.to_s(), "String");
let data = unsafe { Container::try_from_ruby(&interp, &value) };
assert!(data.is_err());
let value =
unsafe { Box::new(Other::default()).try_into_ruby(&interp, None) }.expect("convert");
let class = value.funcall::<Value, _, _>("class", &[]).expect("funcall");
assert_eq!(class.to_s(), "Other");
let data = unsafe { Container::try_from_ruby(&interp, &value) };
assert!(data.is_err());
}
}