ref: 7ecced3a3b68584cdcd68f5e9e79b4950368e92a rust-ruby-wrap-data/src/lib.rs -rw-r--r-- 6.2 KiB View raw
                                                                                
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
//! # Ruby Wrap Data
//!
//! `ruby_wrap_data` is a crate that provides a fairly low-level means of doing
//! what Ruby's `Data_Wrap_Struct` macro does. That is to say, you can store a
//! Rust `Box<T>` inside a Ruby object and get it back out again.
//!
//! Any heap-allocated struct, enum, or whatever should work.
//!
//! ## Example
//!
//! ```rust
//! extern crate ruby_sys;
//! extern crate ruby_wrap_data;
//!
//! use ruby_sys::{
//!     class::{rb_class_new_instance, rb_define_class},
//!     rb_cObject,
//!     types::Value,
//!     value::RubySpecialConsts::{Nil},
//!     vm::ruby_init
//! };
//!
//! use std::ffi::CString;
//! use std::mem;
//!
//! const RB_NIL: Value = Value { value: Nil as usize };
//!
//! struct MyValue {
//!     pub val: u16
//! }
//!
//! fn alloc(klass: Value) -> Value {
//!     // build your data and put it on the heap
//!     let data = Box::new(MyValue { val: 1 });
//!     // call `wrap()`, passing your klass and data
//!     ruby_wrap_data::wrap(klass, data)
//! }
//!
//! fn main() {
//!     // you may need to start the ruby vm
//!     unsafe { ruby_init() };
//!
//!     // create a ruby class and attach your alloc function
//!     let name = CString::new("Thing").unwrap().into_raw();
//!     let klass = unsafe { rb_define_class(name, rb_cObject) };
//!     ruby_wrap_data::define_alloc_func(klass, alloc);
//!
//!     // create a new instance of the class
//!     let thing = unsafe { rb_class_new_instance(0, &RB_NIL, klass) };
//!
//!     // get the data out of the ruby object
//!     let data: Option<Box<MyValue>> = ruby_wrap_data::remove(thing);
//!     assert!(data.is_some());
//!
//!     // if you try to remove it again, you get None
//!     let data: Option<Box<MyValue>> = ruby_wrap_data::remove(thing);
//!     assert!(data.is_none());
//!
//!     // set new data on the object
//!     let new_data = Box::new(MyValue { val : 2 });
//!     ruby_wrap_data::set(thing, new_data);
//! }
//! ```
extern crate ruby_sys;

use ruby_sys::types::{c_void, CallbackPtr, RBasic, Value};

use std::{mem, ptr};

extern "C" {
    pub fn rb_define_alloc_func(klass: Value, func: CallbackPtr);
    pub fn rb_data_object_wrap(
        klass: Value,
        datap: *mut c_void,
        mark: Option<extern "C" fn(*mut c_void)>,
        free: Option<extern "C" fn(*mut c_void)>,
    ) -> Value;
}

#[repr(C)]
struct RData {
    basic: RBasic,
    dmark: Option<extern "C" fn(*mut c_void)>,
    dfree: Option<extern "C" fn(*mut c_void)>,
    pub data: *mut c_void,
}

/// Defines an 'alloc' function for a Ruby class. Such a function should
/// build your initial data and call `wrap(klass, data)`.
///
/// # Arguments
///
/// * `klass` - a Ruby Class
/// * `alloc` - a function taking a Ruby Value and returning a Ruby Value
pub fn define_alloc_func(klass: Value, alloc: fn(Value) -> Value) {
    unsafe { rb_define_alloc_func(klass, alloc as CallbackPtr) };
}

/// Creates a new instance of the given class, wrapping the given
/// heap-allocated data type.
///
/// # Arguments
///
/// * `klass` - a Ruby Class
/// * `data`  - a Box<T> - the data you wish to embed in the Ruby object
pub fn wrap<T>(klass: Value, data: Box<T>) -> Value {
    let datap = Box::into_raw(data) as *mut c_void;
    unsafe { rb_data_object_wrap(klass, datap, None, Some(free::<T>)) }
}

/// Removes and returns the wrapped data from the given Ruby object.
/// Returns None if the data is currently NULL.
///
/// # Arguments
///
/// * `object` - a Ruby object
///
/// # Notes
///
/// You will need to specify the data type of the variable since it
/// cannot be inferred:
///
/// ```compile_fail
/// let data: Option<Box<MyValue>> = ruby_wrap_data::remove(thing);
/// ```
///
/// Also note, if you wish to peek at the data without removing it,
/// you will need to put it back using `set`, like this:
///
/// ```compile_fail
/// let data: Option<Box<MyValue>> = ruby_wrap_data::remove(thing);
/// ruby_wrap_data::set(thing, data.unwrap());
/// ```
pub fn remove<T>(object: Value) -> Option<Box<T>> {
    let rdata = rdata(object);
    let datap = unsafe { (*rdata).data as *mut T };
    if datap.is_null() {
        None
    } else {
        set_none(object);
        Some(unsafe { Box::from_raw(datap) })
    }
}

/// Sets the wrapped data on the given Ruby object.
///
/// # Arguments
///
/// * `object` - a Ruby object
/// * `data`   - a Box<T> - the data you wish to embed in the Ruby object
pub fn set<T>(object: Value, data: Box<T>) {
    let rdata = rdata(object);
    let datap = Box::into_raw(data) as *mut c_void;
    unsafe { (*rdata).data = datap };
}

extern "C" fn free<T>(data: *mut c_void) {
    // memory is freed when the box goes out of the scope
    let datap = data as *mut T;
    unsafe { Box::from_raw(datap) };
}

fn set_none(object: Value) {
    let rdata = rdata(object);
    unsafe { (*rdata).data = ptr::null_mut() };
}

fn rdata(object: Value) -> *mut RData {
    unsafe { mem::transmute(object) }
}

#[cfg(test)]
mod tests {
    use super::*;

    use ruby_sys::{
        class::{rb_class_new_instance, rb_define_class},
        rb_cObject,
        types::Value,
        value::RubySpecialConsts::{Nil},
        vm::ruby_init
    };

    use std::ffi::CString;

    const RB_NIL: Value = Value { value: Nil as usize };

    #[derive(Debug,PartialEq)]
    struct MyValue {
        pub val: u16
    }

    fn alloc(klass: Value) -> Value {
        let data = Box::new(MyValue { val: 1 });
        wrap(klass, data)
    }

    #[test]
    fn it_works() {
        // start ruby
        unsafe { ruby_init() };

        // create our class
        let name = CString::new("Thing").unwrap().into_raw();
        let klass = unsafe { rb_define_class(name, rb_cObject) };

        // set up our alloc function and create the object
        define_alloc_func(klass, alloc);
        let thing = unsafe { rb_class_new_instance(0, &RB_NIL, klass) };

        // the data matches what we put in
        let data: Box<MyValue> = remove(thing).unwrap();
        assert_eq!(*data, MyValue { val: 1 });

        // now it's None
        assert_eq!(remove::<Option<Box<MyValue>>>(thing), None);

        // set new data
        let new_data = Box::new(MyValue { val : 2 });
        set(thing, new_data);

        // looks right
        let data: Box<MyValue> = remove(thing).unwrap();
        assert_eq!(*data, MyValue { val: 2 });
    }
}