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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//! Functions for working with Ruby's Garbage Collector.
//!
//! See also [`Ruby`](Ruby#gc) for more GC related methods.

use std::{marker::PhantomData, ops::Range};

use rb_sys::{
    rb_gc_adjust_memory_usage, rb_gc_count, rb_gc_disable, rb_gc_enable, rb_gc_mark,
    rb_gc_mark_locations, rb_gc_register_address, rb_gc_register_mark_object, rb_gc_start,
    rb_gc_stat, rb_gc_unregister_address, VALUE,
};
#[cfg(ruby_gte_2_7)]
use rb_sys::{rb_gc_location, rb_gc_mark_movable};

use crate::{
    error::{protect, Error},
    r_hash::RHash,
    symbol::IntoSymbol,
    value::{private::ReprValue as _, ReprValue, Value},
    Ruby,
};

mod private {
    use super::*;

    pub trait Mark {
        fn raw(self) -> VALUE;
    }

    pub trait Locate {
        fn raw(self) -> VALUE;

        fn from_raw(val: VALUE) -> Self;
    }
}

/// Trait indicating types that can be passed to GC marking functions.
///
/// See [`Marker`].
pub trait Mark: private::Mark {}

impl<T> private::Mark for T
where
    T: ReprValue,
{
    fn raw(self) -> VALUE {
        self.as_rb_value()
    }
}
impl<T> Mark for T where T: ReprValue {}

impl<T> private::Mark for crate::value::Opaque<T>
where
    T: ReprValue,
{
    fn raw(self) -> VALUE {
        unsafe { Ruby::get_unchecked() }
            .get_inner(self)
            .as_rb_value()
    }
}
impl<T> Mark for crate::value::Opaque<T> where T: ReprValue {}

/// A handle to GC marking functions.
///
/// See also
/// [`DataTypeFunctions::mark`](`crate::typed_data::DataTypeFunctions::mark`).
pub struct Marker(PhantomData<*mut ()>);

impl Marker {
    pub(crate) fn new() -> Self {
        Self(PhantomData)
    }

    /// Mark an Object.
    ///
    /// Used to mark any stored Ruby objects when implementing
    /// [`DataTypeFunctions::mark`](`crate::typed_data::DataTypeFunctions::mark`).
    pub fn mark<T>(&self, value: T)
    where
        T: Mark,
    {
        unsafe { rb_gc_mark(value.raw()) };
    }

    /// Mark multiple Objects.
    ///
    /// Used to mark any stored Ruby objects when implementing
    /// [`DataTypeFunctions::mark`](`crate::typed_data::DataTypeFunctions::mark`).
    pub fn mark_slice<T>(&self, values: &[T])
    where
        T: Mark,
    {
        let Range { start, end } = values.as_ptr_range();
        unsafe { rb_gc_mark_locations(start as *const VALUE, end as *const VALUE) }
    }

    /// Mark an Object and let Ruby know it is moveable.
    ///
    /// The [`Value`] type is effectly a pointer to a Ruby object. Ruby's
    /// garbage collector will avoid moving objects exposed to extensions,
    /// unless you use this function to mark them during the GC marking phase.
    ///
    /// Used to mark any stored Ruby objects when implementing
    /// [`DataTypeFunctions::mark`](`crate::typed_data::DataTypeFunctions::mark`)
    /// and you have also implemented
    /// [`DataTypeFunctions::compact`](`crate::typed_data::DataTypeFunctions::compact`).
    ///
    /// Beware that any Ruby object passed to this function may later become
    /// invalid to use from Rust when GC is run, you must update any stored
    /// objects with [`Compactor::location`] inside your implementation of
    /// [`DataTypeFunctions::compact`](`crate::typed_data::DataTypeFunctions::compact`).
    #[cfg(any(ruby_gte_2_7, docsrs))]
    #[cfg_attr(docsrs, doc(cfg(ruby_gte_2_7)))]
    pub fn mark_movable<T>(&self, value: T)
    where
        T: Mark,
    {
        unsafe { rb_gc_mark_movable(value.raw()) };
    }
}

/// Trait indicating types that can given to [`Compactor::location`].
pub trait Locate: private::Locate {}

impl<T> private::Locate for T
where
    T: ReprValue,
{
    fn raw(self) -> VALUE {
        self.as_rb_value()
    }

    fn from_raw(val: VALUE) -> Self {
        unsafe { Self::from_value_unchecked(Value::new(val)) }
    }
}
impl<T> Locate for T where T: ReprValue {}

impl<T> private::Locate for crate::value::Opaque<T>
where
    T: ReprValue,
{
    fn raw(self) -> VALUE {
        unsafe { Ruby::get_unchecked() }
            .get_inner(self)
            .as_rb_value()
    }

    fn from_raw(val: VALUE) -> Self {
        unsafe { T::from_value_unchecked(Value::new(val)) }.into()
    }
}
impl<T> Locate for crate::value::Opaque<T> where T: ReprValue {}

/// A handle to functions relating to GC compaction.
///
/// See also
/// [`DataTypeFunctions::compact`](`crate::typed_data::DataTypeFunctions::compact`).
pub struct Compactor(PhantomData<*mut ()>);

impl Compactor {
    pub(crate) fn new() -> Self {
        Self(PhantomData)
    }

    /// Get the new location of an object.
    ///
    /// The [`Value`] type is effectly a pointer to a Ruby object. Ruby's
    /// garbage collector will avoid moving objects exposed to extensions,
    /// unless the object has been marked with [`mark_movable`]. When
    /// implementing
    /// [`DataTypeFunctions::compact`](`crate::typed_data::DataTypeFunctions::compact`)
    /// you will need to update any Ruby objects you are storing.
    ///
    /// Returns a new `T` that is pointing to the object that `value` used to
    /// point to. If `value` hasn't moved, simply returns `value`.
    #[cfg(any(ruby_gte_2_7, docsrs))]
    #[cfg_attr(docsrs, doc(cfg(ruby_gte_2_7)))]
    pub fn location<T>(&self, value: T) -> T
    where
        T: Locate,
    {
        unsafe { T::from_raw(rb_gc_location(value.raw())) }
    }
}

#[doc(hidden)]
#[deprecated(since = "0.6.0", note = "please use `Marker::mark` instead")]
pub fn mark<T>(value: T)
where
    T: ReprValue,
{
    Marker::new().mark(value)
}

#[doc(hidden)]
#[deprecated(since = "0.6.0", note = "please use `Marker::mark_slice` instead")]
pub fn mark_slice<T>(values: &[T])
where
    T: ReprValue,
{
    Marker::new().mark_slice(values)
}

#[doc(hidden)]
#[deprecated(since = "0.6.0", note = "please use `Marker::mark_movable` instead")]
#[cfg(any(ruby_gte_2_7, docsrs))]
#[cfg_attr(docsrs, doc(cfg(ruby_gte_2_7)))]
pub fn mark_movable<T>(value: T)
where
    T: ReprValue,
{
    Marker::new().mark_movable(value)
}

#[doc(hidden)]
#[deprecated(since = "0.6.0", note = "please use `Compactor::location` instead")]
#[cfg(any(ruby_gte_2_7, docsrs))]
pub fn location<T>(value: T) -> T
where
    T: ReprValue,
{
    Compactor::new().location(value)
}

/// Registers `value` to never be garbage collected.
///
/// This is essentially a deliberate memory leak.
///
/// # Examples
///
/// ```
/// use magnus::{gc, RArray, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// // will never be collected
/// let root = RArray::new();
/// gc::register_mark_object(root);
///
/// // won't be collected while it is in out `root` array
/// let s = RString::new("example");
/// root.push(s).unwrap();
/// ```
pub fn register_mark_object<T>(value: T)
where
    T: Mark,
{
    unsafe { rb_gc_register_mark_object(value.raw()) }
}

/// Inform Ruby's garbage collector that `valref` points to a live Ruby object.
///
/// Prevents Ruby moving or collecting `valref`. This should be used on
/// `static` items to prevent them being collected instead of relying on Ruby
/// constants/globals to allways refrence the value.
///
/// See also [`BoxValue`](crate::value::BoxValue).
///
/// # Examples
///
/// ```
/// use magnus::{gc, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let s = RString::new("example");
///
/// // s won't be collected even though it's on the heap
/// let boxed = Box::new(s);
/// gc::register_address(&*boxed);
///
/// // ...
///
/// // allow s to be collected
/// gc::unregister_address(&*boxed);
/// drop(boxed);
/// ```
pub fn register_address<T>(valref: &T)
where
    T: Mark,
{
    unsafe { rb_gc_register_address(valref as *const _ as *mut VALUE) }
}

/// Inform Ruby's garbage collector that `valref` that was previously
/// registered with [`register_address`] no longer points to a live Ruby
/// object.
///
/// # Examples
///
/// ```
/// use magnus::{gc, RString};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let s = RString::new("example");
///
/// // s won't be collected even though it's on the heap
/// let boxed = Box::new(s);
/// gc::register_address(&*boxed);
///
/// // ...
///
/// // allow s to be collected
/// gc::unregister_address(&*boxed);
/// drop(boxed);
/// ```
pub fn unregister_address<T>(valref: &T)
where
    T: Mark,
{
    unsafe { rb_gc_unregister_address(valref as *const _ as *mut VALUE) }
}

/// # GC
///
/// Functions for working with Ruby's Garbage Collector.
///
/// See also the [`gc`](self) module.
impl Ruby {
    /// Disable automatic GC runs.
    ///
    /// This could result in other Ruby api functions unexpectedly raising
    /// `NoMemError`.
    ///
    /// Returns `true` if GC was already disabled, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let was_disabled = ruby.gc_disable();
    ///
    ///     // GC is off
    ///
    ///     // return GC to previous state
    ///     if !was_disabled {
    ///         ruby.gc_enable();
    ///     }
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn gc_disable(&self) -> bool {
        unsafe { Value::new(rb_gc_disable()).to_bool() }
    }

    /// Enable automatic GC run.
    ///
    /// Garbage Collection is enabled by default, calling this function only
    /// makes sense if [`disable`] was previously called.
    ///
    /// Returns `true` if GC was previously disabled, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let was_disabled = ruby.gc_enable();
    ///
    ///     // GC is on
    ///
    ///     // return GC to previous state
    ///     if was_disabled {
    ///         ruby.gc_disable();
    ///     }
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn gc_enable(&self) -> bool {
        unsafe { Value::new(rb_gc_enable()).to_bool() }
    }

    /// Trigger a "full" GC run.
    ///
    /// This will perform a full mark phase and a complete sweep phase, but may
    /// not run every single proceess associated with garbage collection.
    ///
    /// Finalisers will be deferred to run later.
    ///
    /// Currently (with versions of Ruby that support compaction) it will not
    /// trigger compaction.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     ruby.gc_start();
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn gc_start(&self) {
        unsafe { rb_gc_start() };
    }

    /// Inform Ruby of external memory usage.
    ///
    /// The Ruby GC is run when Ruby thinks it's running out of memory, but
    /// won't take into account any memory allocated outside of Ruby api
    /// functions. This function can be used to give Ruby a more accurate idea
    /// of how much memory the process is using.
    ///
    /// Pass negative numbers to indicate memory has been freed.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let buf = Vec::<u8>::with_capacity(1024 * 1024);
    ///     let mem_size = buf.capacity() * std::mem::size_of::<u8>();
    ///     ruby.gc_adjust_memory_usage(mem_size as isize);
    ///
    ///     // ...
    ///
    ///     drop(buf);
    ///     ruby.gc_adjust_memory_usage(-(mem_size as isize));
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn gc_adjust_memory_usage(&self, diff: isize) {
        unsafe { rb_gc_adjust_memory_usage(diff as _) };
    }

    /// Returns the number of garbage collections that have been run since the
    /// start of the process.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let before = ruby.gc_count();
    ///     ruby.gc_start();
    ///     assert!(ruby.gc_count() > before);
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn gc_count(&self) -> usize {
        unsafe { rb_gc_count() as usize }
    }

    /// Returns the GC profiling value for `key`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     assert!(ruby.gc_stat("heap_live_slots")? > 1);
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn gc_stat<T>(&self, key: T) -> Result<usize, Error>
    where
        T: IntoSymbol,
    {
        let sym = key.into_symbol_with(self);
        let mut res = 0;
        protect(|| {
            res = unsafe { rb_gc_stat(sym.as_rb_value()) as usize };
            self.qnil()
        })?;
        Ok(res)
    }

    /// Returns all possible key/value pairs for [`stat`] as a Ruby Hash.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let stats = ruby.gc_all_stats();
    ///     let live_slots: usize = stats.fetch(ruby.to_symbol("heap_live_slots"))?;
    ///     assert!(live_slots > 1);
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn gc_all_stats(&self) -> RHash {
        let res = self.hash_new();
        unsafe { rb_gc_stat(res.as_rb_value()) };
        res
    }
}

/// Disable automatic GC runs.
///
/// This could result in other Ruby api functions unexpectedly raising
/// `NoMemError`.
///
/// Returns `true` if GC was already disabled, `false` otherwise.
///
/// # Panics
///
/// Panics if called from a non-Ruby thread. See [`Ruby::gc_disable`] for the
/// non-panicking version.
///
/// # Examples
///
/// ```
/// use magnus::gc;
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let was_disabled = gc::disable();
///
/// // GC is off
///
/// // return GC to previous state
/// if !was_disabled {
///     gc::enable();
/// }
/// ```
#[cfg_attr(
    not(feature = "friendly-api"),
    deprecated(note = "please use `Ruby::gc_disable` instead")
)]
#[inline]
pub fn disable() -> bool {
    get_ruby!().gc_disable()
}

/// Enable automatic GC run.
///
/// Garbage Collection is enabled by default, calling this function only makes
/// sense if [`disable`] was previously called.
///
/// Returns `true` if GC was previously disabled, `false` otherwise.
///
/// # Panics
///
/// Panics if called from a non-Ruby thread. See [`Ruby::gc_enable`] for the
/// non-panicking version.
///
/// # Examples
///
/// ```
/// use magnus::gc;
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let was_disabled = gc::enable();
///
/// // GC is on
///
/// // return GC to previous state
/// if was_disabled {
///     gc::disable();
/// }
/// ```
#[cfg_attr(
    not(feature = "friendly-api"),
    deprecated(note = "please use `Ruby::gc_enable` instead")
)]
#[inline]
pub fn enable() -> bool {
    get_ruby!().gc_enable()
}

/// Trigger a "full" GC run.
///
/// This will perform a full mark phase and a complete sweep phase, but may not
/// run every single proceess associated with garbage collection.
///
/// Finalisers will be deferred to run later.
///
/// Currently (with versions of Ruby that support compaction) it will not
/// trigger compaction.
///
/// # Panics
///
/// Panics if called from a non-Ruby thread. See [`Ruby::gc_start`] for the
/// non-panicking version.
///
/// # Examples
///
/// ```
/// use magnus::gc;
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// gc::start();
/// ```
#[cfg_attr(
    not(feature = "friendly-api"),
    deprecated(note = "please use `Ruby::gc_start` instead")
)]
#[inline]
pub fn start() {
    get_ruby!().gc_start()
}

/// Inform Ruby of external memory usage.
///
/// The Ruby GC is run when Ruby thinks it's running out of memory, but won't
/// take into account any memory allocated outside of Ruby api functions. This
/// function can be used to give Ruby a more accurate idea of how much memory
/// the process is using.
///
/// Pass negative numbers to indicate memory has been freed.
///
/// # Panics
///
/// Panics if called from a non-Ruby thread. See
/// [`Ruby::gc_adjust_memory_usage`] for the non-panicking version.
///
/// # Examples
///
/// ```
/// use magnus::gc;
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let buf = Vec::<u8>::with_capacity(1024 * 1024);
/// let mem_size = buf.capacity() * std::mem::size_of::<u8>();
/// gc::adjust_memory_usage(mem_size as isize);
///
/// // ...
///
/// drop(buf);
/// gc::adjust_memory_usage(-(mem_size as isize));
/// ```
#[cfg_attr(
    not(feature = "friendly-api"),
    deprecated(note = "please use `Ruby::gc_adjust_memory_usage` instead")
)]
#[inline]
pub fn adjust_memory_usage(diff: isize) {
    get_ruby!().gc_adjust_memory_usage(diff)
}

/// Returns the number of garbage collections that have been run since the
/// start of the process.
///
/// # Panics
///
/// Panics if called from a non-Ruby thread. See [`Ruby::gc_count`] for the
/// non-panicking version.
///
/// # Examples
///
/// ```
/// use magnus::gc;
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let before = gc::count();
/// gc::start();
/// assert!(gc::count() > before);
/// ```
#[cfg_attr(
    not(feature = "friendly-api"),
    deprecated(note = "please use `Ruby::gc_count` instead")
)]
#[inline]
pub fn count() -> usize {
    get_ruby!().gc_count()
}

/// Returns the GC profiling value for `key`.
///
/// # Panics
///
/// Panics if called from a non-Ruby thread. See [`Ruby::gc_stat`] for the
/// non-panicking version.
///
/// # Examples
///
/// ```
/// use magnus::gc;
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert!(gc::stat("heap_live_slots").unwrap() > 1);
/// ```
#[cfg_attr(
    not(feature = "friendly-api"),
    deprecated(note = "please use `Ruby::gc_stat` instead")
)]
#[inline]
pub fn stat<T>(key: T) -> Result<usize, Error>
where
    T: IntoSymbol,
{
    let handle = get_ruby!();
    handle.gc_stat(key.into_symbol_with(&handle))
}

/// Returns all possible key/value pairs for [`stat`] as a Ruby Hash.
///
/// # Panics
///
/// Panics if called from a non-Ruby thread. See [`Ruby::gc_all_stats`] for the
/// non-panicking version.
///
/// # Examples
///
/// ```
/// use magnus::{gc, Symbol};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let stats = gc::all_stats();
/// let live_slots: usize = stats.fetch(Symbol::new("heap_live_slots")).unwrap();
/// assert!(live_slots > 1);
/// ```
#[cfg_attr(
    not(feature = "friendly-api"),
    deprecated(note = "please use `Ruby::gc_all_stats` instead")
)]
#[inline]
pub fn all_stats() -> RHash {
    get_ruby!().gc_all_stats()
}