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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//! Types and functions for working with Ruby's Fiber class.
use std::{fmt, mem::size_of, os::raw::c_int, slice};
#[cfg(ruby_lt_3_2)]
use rb_sys::rb_fiber_new;
#[cfg(ruby_gte_3_2)]
use rb_sys::rb_fiber_new_storage;
use rb_sys::{
rb_data_typed_object_wrap, rb_fiber_alive_p, rb_fiber_current, rb_fiber_resume_kw,
rb_fiber_yield_kw, VALUE,
};
#[cfg(ruby_gte_3_1)]
use rb_sys::{rb_fiber_raise, rb_fiber_transfer_kw, rb_obj_is_fiber};
#[cfg(any(ruby_gte_3_2, docsrs))]
use crate::r_hash::RHash;
use crate::{
api::Ruby,
block::Proc,
data_type_builder,
error::{protect, Error},
exception::Exception,
gc,
into_value::{kw_splat, ArgList, IntoValue},
method::{Block, BlockReturn},
object::Object,
r_typed_data::RTypedData,
try_convert::TryConvert,
typed_data::{DataType, DataTypeFunctions},
value::{
private::{self, ReprValue as _},
ReprValue, Value, QUNDEF,
},
};
/// # `Fiber`
///
/// Functions to create and work with Ruby `Fiber`s.
///
/// See also the [`Fiber`] type.
impl Ruby {
/// Create a Ruby Fiber.
///
/// As `func` is a function pointer, only functions and closures that do
/// not capture any variables are permitted. For more flexibility (at the
/// cost of allocating) see [`fiber_new_from_fn`](Ruby::fiber_new_from_fn).
///
/// # Examples
///
/// ```
/// use magnus::{prelude::*, rb_assert, Error, Ruby, Value};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let fib = ruby.fiber_new(Default::default(), |ruby, args, _block| {
/// let mut a = u64::try_convert(*args.get(0).unwrap())?;
/// let mut b = u64::try_convert(*args.get(1).unwrap())?;
/// while let Some(c) = a.checked_add(b) {
/// let _: Value = ruby.fiber_yield((c,))?;
/// a = b;
/// b = c;
/// }
/// Ok(())
/// })?;
///
/// rb_assert!(ruby, "fib.resume(0, 1) == 1", fib);
/// rb_assert!(ruby, "fib.resume == 2", fib);
/// rb_assert!(ruby, "fib.resume == 3", fib);
/// rb_assert!(ruby, "fib.resume == 5", fib);
/// rb_assert!(ruby, "fib.resume == 8", fib);
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn fiber_new<R>(
&self,
storage: Storage,
func: fn(&Ruby, &[Value], Option<Proc>) -> R,
) -> Result<Fiber, Error>
where
R: BlockReturn,
{
unsafe extern "C" fn call<R>(
_yielded_arg: VALUE,
callback_arg: VALUE,
argc: c_int,
argv: *const VALUE,
blockarg: VALUE,
) -> VALUE
where
R: BlockReturn,
{
let func =
std::mem::transmute::<VALUE, fn(&Ruby, &[Value], Option<Proc>) -> R>(callback_arg);
func.call_handle_error(argc, argv as *const Value, Value::new(blockarg))
.as_rb_value()
}
let call_func =
call::<R> as unsafe extern "C" fn(VALUE, VALUE, c_int, *const VALUE, VALUE) -> VALUE;
unsafe {
protect(|| {
#[cfg(ruby_gte_3_2)]
let value =
rb_fiber_new_storage(Some(call_func), func as VALUE, storage.as_rb_value());
#[cfg(ruby_lt_3_2)]
let value = rb_fiber_new(Some(call_func), func as VALUE);
Fiber::from_rb_value_unchecked(value)
})
}
}
/// Create a Ruby Fiber.
///
/// See also [`fiber_new`](Ruby::fiber_new), which is more efficient when
/// `func` is a function or closure that does not capture any variables.
///
/// # Examples
///
/// ```
/// use magnus::{rb_assert, Error, Ruby, Value};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let mut a = 0_u64;
/// let mut b = 1_u64;
///
/// let fib = ruby.fiber_new_from_fn(Default::default(), move |ruby, _args, _block| {
/// while let Some(c) = a.checked_add(b) {
/// let _: Value = ruby.fiber_yield((c,))?;
/// a = b;
/// b = c;
/// }
/// Ok(())
/// })?;
///
/// rb_assert!(ruby, "fib.resume == 1", fib);
/// rb_assert!(ruby, "fib.resume == 2", fib);
/// rb_assert!(ruby, "fib.resume == 3", fib);
/// rb_assert!(ruby, "fib.resume == 5", fib);
/// rb_assert!(ruby, "fib.resume == 8", fib);
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn fiber_new_from_fn<F, R>(&self, storage: Storage, func: F) -> Result<Fiber, Error>
where
F: 'static + Send + FnOnce(&Ruby, &[Value], Option<Proc>) -> R,
R: BlockReturn,
{
unsafe extern "C" fn call<F, R>(
_yielded_arg: VALUE,
callback_arg: VALUE,
argc: c_int,
argv: *const VALUE,
blockarg: VALUE,
) -> VALUE
where
F: FnOnce(&Ruby, &[Value], Option<Proc>) -> R,
R: BlockReturn,
{
let closure = (*(callback_arg as *mut Option<F>)).take().unwrap();
closure
.call_handle_error(argc, argv as *const Value, Value::new(blockarg))
.as_rb_value()
}
let (closure, keepalive) = wrap_closure(func);
let call_func =
call::<F, R> as unsafe extern "C" fn(VALUE, VALUE, c_int, *const VALUE, VALUE) -> VALUE;
protect(|| {
#[cfg(ruby_gte_3_2)]
let fiber = unsafe {
Fiber::from_rb_value_unchecked(rb_fiber_new_storage(
Some(call_func),
closure as VALUE,
storage.as_rb_value(),
))
};
#[cfg(ruby_lt_3_2)]
let fiber = unsafe {
Fiber::from_rb_value_unchecked(rb_fiber_new(Some(call_func), closure as VALUE))
};
// ivar without @ prefix is invisible from Ruby
fiber.ivar_set("__rust_closure", keepalive).unwrap();
fiber
})
}
/// Return the currently executing Fiber.
///
/// # Examples
///
/// ```
/// use magnus::{rb_assert, Error, Ruby};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let fiber = ruby.fiber_current();
///
/// rb_assert!(ruby, "fiber.is_a?(Fiber)", fiber);
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn fiber_current(&self) -> Fiber {
unsafe { Fiber::from_rb_value_unchecked(rb_fiber_current()) }
}
/// Transfer execution back to where the current Fiber was resumed.
///
/// # Examples
///
/// ```
/// use magnus::{rb_assert, value::Opaque, Error, Ruby, Value};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let ary = ruby.ary_new();
/// let send_array = Opaque::from(ary);
///
/// let fiber = ruby.fiber_new_from_fn(Default::default(), move |ruby, _args, _block| {
/// let ary = ruby.get_inner(send_array);
/// ary.push(1)?;
/// let _: Value = ruby.fiber_yield(())?;
/// ary.push(2)?;
/// let _: Value = ruby.fiber_yield(())?;
/// ary.push(3)?;
/// let _: Value = ruby.fiber_yield(())?;
/// Ok(())
/// })?;
///
/// ary.push("a")?;
/// let _: Value = fiber.resume(())?;
/// ary.push("b")?;
/// let _: Value = fiber.resume(())?;
/// ary.push("c")?;
/// let _: Value = fiber.resume(())?;
///
/// rb_assert!(ruby, r#"ary == ["a", 1, "b", 2, "c", 3]"#, ary);
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn fiber_yield<A, T>(&self, args: A) -> Result<T, Error>
where
A: ArgList,
T: TryConvert,
{
let kw_splat = kw_splat(&args);
let args = args.into_arg_list_with(self);
let slice = args.as_ref();
unsafe {
protect(|| {
Value::new(rb_fiber_yield_kw(
slice.len() as c_int,
slice.as_ptr() as *const VALUE,
kw_splat as c_int,
))
})
.and_then(TryConvert::try_convert)
}
}
}
/// Wrapper type for a Value known to be an instance of Ruby's Fiber class.
///
/// See the [`ReprValue`] and [`Object`] traits for additional methods
/// available on this type. See [`Ruby`](Ruby#fiber) for methods to create a
/// `Fiber` and [`Ruby::fiber_yield`].
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Fiber(RTypedData);
impl Fiber {
/// Return `Some(Fiber)` if `val` is a `Fiber`, `None` otherwise.
///
/// # Examples
///
/// ```
/// use magnus::eval;
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert!(magnus::Fiber::from_value(eval("Fiber.new {1 + 2}").unwrap()).is_some());
/// assert!(magnus::Fiber::from_value(eval("Thread.new {1 + 2}").unwrap()).is_none());
/// assert!(magnus::Fiber::from_value(eval("Proc.new {1 + 2}").unwrap()).is_none());
/// ```
#[inline]
pub fn from_value(val: Value) -> Option<Self> {
unsafe {
Value::new(rb_obj_is_fiber(val.as_rb_value()))
.to_bool()
.then(|| Self::from_rb_value_unchecked(val.as_rb_value()))
}
}
#[inline]
pub(crate) unsafe fn from_rb_value_unchecked(val: VALUE) -> Self {
Self(RTypedData::from_rb_value_unchecked(val))
}
/// Return `true` if `self` can be resumed, `false` otherwise.
///
/// # Examples
///
/// ```
/// use magnus::{Error, Ruby, Value};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let fiber = ruby.fiber_new(Default::default(), move |ruby, _args, _block| {
/// let _: Value = ruby.fiber_yield((1,))?;
/// let _: Value = ruby.fiber_yield((3,))?;
/// Ok(5)
/// })?;
///
/// assert!(fiber.is_alive());
/// assert_eq!(fiber.resume::<_, u64>(())?, 1);
/// assert!(fiber.is_alive());
/// assert_eq!(fiber.resume::<_, u64>(())?, 3);
/// assert!(fiber.is_alive());
/// assert_eq!(fiber.resume::<_, u64>(())?, 5);
/// assert!(!fiber.is_alive());
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn is_alive(self) -> bool {
unsafe { Value::new(rb_fiber_alive_p(self.as_rb_value())).to_bool() }
}
/// Resume the execution of `self`.
///
/// # Examples
///
/// ```
/// use magnus::{prelude::*, Error, Ruby, Value};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let fib = ruby.fiber_new(Default::default(), |ruby, args, _block| {
/// let mut a = u64::try_convert(*args.get(0).unwrap())?;
/// let mut b = u64::try_convert(*args.get(1).unwrap())?;
/// while let Some(c) = a.checked_add(b) {
/// let _: Value = ruby.fiber_yield((c,))?;
/// a = b;
/// b = c;
/// }
/// Ok(())
/// })?;
///
/// assert_eq!(fib.resume::<_, u64>((0, 1))?, 1);
/// assert_eq!(fib.resume::<_, u64>(())?, 2);
/// assert_eq!(fib.resume::<_, u64>(())?, 3);
/// assert_eq!(fib.resume::<_, u64>(())?, 5);
/// assert_eq!(fib.resume::<_, u64>(())?, 8);
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn resume<A, T>(self, args: A) -> Result<T, Error>
where
A: ArgList,
T: TryConvert,
{
let kw_splat = kw_splat(&args);
let args = args.into_arg_list_with(&Ruby::get_with(self));
let slice = args.as_ref();
unsafe {
protect(|| {
Value::new(rb_fiber_resume_kw(
self.as_rb_value(),
slice.len() as c_int,
slice.as_ptr() as *const VALUE,
kw_splat as c_int,
))
})
.and_then(TryConvert::try_convert)
}
}
/// Transfer control to another Fiber.
///
/// `transfer` is an alternate API to
/// [`resume`](Fiber::resume)/[`yield`](Ruby::fiber_yield). The two APIs
/// can not be mixed, a Fiber muse use *either* `transfer` or
/// `resume`/`yield` to pass control.
///
/// # Examples
///
/// ```
/// use magnus::{Error, Fiber, Ruby, TryConvert, Value};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let fib = ruby.fiber_new(Default::default(), |_ruby, args, _block| {
/// let root = Fiber::try_convert(*args.get(0).unwrap())?;
/// let mut a = u64::try_convert(*args.get(1).unwrap())?;
/// let mut b = u64::try_convert(*args.get(2).unwrap())?;
/// while let Some(c) = a.checked_add(b) {
/// let _: Value = root.transfer((c,))?;
/// a = b;
/// b = c;
/// }
/// Ok(())
/// })?;
///
/// assert_eq!(fib.transfer::<_, u64>((ruby.fiber_current(), 0, 1))?, 1);
/// assert_eq!(fib.transfer::<_, u64>(())?, 2);
/// assert_eq!(fib.transfer::<_, u64>(())?, 3);
/// assert_eq!(fib.transfer::<_, u64>(())?, 5);
/// assert_eq!(fib.transfer::<_, u64>(())?, 8);
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn transfer<A, T>(self, args: A) -> Result<T, Error>
where
A: ArgList,
T: TryConvert,
{
let kw_splat = kw_splat(&args);
let args = args.into_arg_list_with(&Ruby::get_with(self));
let slice = args.as_ref();
unsafe {
protect(|| {
Value::new(rb_fiber_transfer_kw(
self.as_rb_value(),
slice.len() as c_int,
slice.as_ptr() as *const VALUE,
kw_splat as c_int,
))
})
.and_then(TryConvert::try_convert)
}
}
/// Resume the execution of `self`, raising the exception `e`.
///
/// # Examples
///
/// ```
/// use magnus::{prelude::*, Error, Ruby, Value};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let fiber = ruby.fiber_new(Default::default(), move |ruby, _args, _block| {
/// assert!(ruby.fiber_yield::<_, Value>(()).is_err());
/// })?;
///
/// let _: Value = fiber.resume(())?;
/// let _: Value = fiber.raise(ruby.exception_runtime_error().new_instance(("oh no!",))?)?;
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn raise<T>(self, e: Exception) -> Result<T, Error>
where
T: TryConvert,
{
unsafe {
protect(|| {
#[cfg(ruby_lte_3_4)]
let e = &e.as_rb_value() as *const VALUE;
#[cfg(ruby_gt_3_4)]
let e = &mut e.as_rb_value() as *mut VALUE;
Value::new(rb_fiber_raise(self.as_rb_value(), 1, e))
})
.and_then(TryConvert::try_convert)
}
}
}
impl fmt::Display for Fiber {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", unsafe { self.to_s_infallible() })
}
}
impl fmt::Debug for Fiber {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.inspect())
}
}
impl IntoValue for Fiber {
#[inline]
fn into_value_with(self, _: &Ruby) -> Value {
self.0.as_value()
}
}
impl Object for Fiber {}
unsafe impl private::ReprValue for Fiber {}
impl ReprValue for Fiber {}
impl TryConvert for Fiber {
fn try_convert(val: Value) -> Result<Self, Error> {
Self::from_value(val).ok_or_else(|| {
Error::new(
Ruby::get_with(val).exception_type_error(),
format!("no implicit conversion of {} into Fiber", unsafe {
val.classname()
},),
)
})
}
}
/// Options for initialising Fiber-local storage.
pub enum Storage {
/// Inherit the storage from the current Fiber.
Inherit,
/// Initialise a new empty storage when needed.
#[cfg(any(ruby_gte_3_2, docsrs))]
#[cfg_attr(docsrs, doc(cfg(ruby_gte_3_2)))]
Lazy,
/// Use the given Hash as the Fiber's storage.
#[cfg(any(ruby_gte_3_2, docsrs))]
#[cfg_attr(docsrs, doc(cfg(ruby_gte_3_2)))]
Use(RHash),
}
#[cfg(ruby_gte_3_2)]
impl Storage {
unsafe fn as_rb_value(&self) -> VALUE {
#[cfg(ruby_gte_3_2)]
let ruby = Ruby::get_unchecked();
match self {
Self::Inherit => QUNDEF.as_value().as_rb_value(),
#[cfg(ruby_gte_3_2)]
Self::Lazy => ruby.qnil().as_rb_value(),
#[cfg(ruby_gte_3_2)]
Self::Use(hash) => hash.as_rb_value(),
}
}
}
impl Default for Storage {
fn default() -> Self {
Self::Inherit
}
}
fn wrap_closure<F, R>(func: F) -> (*mut Option<F>, Value)
where
F: FnOnce(&Ruby, &[Value], Option<Proc>) -> R,
R: BlockReturn,
{
struct Closure<F>(Option<F>, DataType);
unsafe impl<F> Send for Closure<F> {}
impl<F> DataTypeFunctions for Closure<F> {
fn mark(&self, marker: &gc::Marker) {
// Attempt to mark any Ruby values captured in a closure.
// Rust's closures are structs that contain all the values they
// have captured. This reads that struct as a slice of VALUEs and
// calls rb_gc_mark_locations which calls gc_mark_maybe which
// marks VALUEs and ignores non-VALUEs
marker.mark_slice(unsafe {
slice::from_raw_parts(
&self.0 as *const _ as *const Value,
size_of::<F>() / size_of::<Value>(),
)
});
}
}
let data_type = data_type_builder!(Closure<F>, "rust closure")
.free_immediately()
.mark()
.build();
let boxed = Box::new(Closure(Some(func), data_type));
let ptr = Box::into_raw(boxed);
let value = unsafe {
Value::new(rb_data_typed_object_wrap(
0, // using 0 for the class will hide the object from ObjectSpace
ptr as *mut _,
(*ptr).1.as_rb_data_type() as *const _,
))
};
unsafe { (&mut (*ptr).0 as *mut Option<F>, value) }
}