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
use log::{error, trace};
use std::cell::RefCell;
use std::mem;
use std::rc::Rc;
use crate::state::State;
use crate::sys::{self, DescribeState};
use crate::{Mrb, MrbError};
pub unsafe fn from_user_data(mrb: *mut sys::mrb_state) -> Result<Mrb, MrbError> {
if mrb.is_null() {
error!("Attempted to extract Mrb from null mrb_state");
return Err(MrbError::Uninitialized);
}
let ptr = (*mrb).ud;
if ptr.is_null() {
error!("Attempted to extract Mrb from null mrb_state->ud pointer");
return Err(MrbError::Uninitialized);
}
let ud = Rc::from_raw(ptr as *const RefCell<State>);
let api = Rc::clone(&ud);
mem::forget(ud);
trace!("Extracted Mrb from user data pointer on {}", mrb.debug());
Ok(api)
}
#[cfg(test)]
mod tests {
use std::rc::Rc;
use crate::MrbError;
#[test]
fn from_user_data_null_pointer() {
let err = unsafe { super::from_user_data(std::ptr::null_mut()) };
assert_eq!(err.err(), Some(MrbError::Uninitialized));
}
#[test]
fn from_user_data_null_user_data() {
let interp = crate::interpreter().expect("mrb init");
let mrb = interp.borrow().mrb;
unsafe {
(*mrb).ud = std::ptr::null_mut();
}
let err = unsafe { super::from_user_data(mrb) };
assert_eq!(err.err(), Some(MrbError::Uninitialized));
}
#[test]
fn from_user_data() {
let interp = crate::interpreter().expect("mrb init");
let mrb = interp.borrow().mrb;
let res = unsafe { super::from_user_data(mrb) };
assert!(res.is_ok());
}
#[test]
fn from_user_data_rc_refcount() {
let interp = crate::interpreter().expect("mrb init");
assert_eq!(Rc::strong_count(&interp), 1);
let mrb = interp.borrow().mrb;
let res = unsafe { super::from_user_data(mrb) };
assert_eq!(Rc::strong_count(&interp), 2);
assert!(res.is_ok());
drop(res);
assert_eq!(Rc::strong_count(&interp), 1);
}
}