rutie 0.10.3

The tie between Ruby and Rust.
Documentation
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
use crate::{
    binding::{gc, vm},
    AnyException, AnyObject, Hash, Object, Symbol,
};

/// Garbage collection
pub struct GC;

impl GC {
    /// Registers `finalizer` to be called with the object's id after
    /// `object` is garbage collected (Ruby's `ObjectSpace.define_finalizer`,
    /// `rb_define_finalizer`), or returns the error: an `ArgumentError` if
    /// `finalizer` is not callable, a `FrozenError` for a frozen object.
    ///
    /// The finalizer must not refer to `object`, or it is never collected.
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{GC, NilClass, Object, Proc, VM};
    /// # VM::init();
    ///
    /// let object = VM::eval("Object.new").unwrap();
    /// let finalizer = Proc::new(|_| NilClass::new().into());
    ///
    /// assert!(GC::define_finalizer(&object, &finalizer).is_ok());
    /// assert!(GC::define_finalizer(&object, &NilClass::new()).is_err());
    ///
    /// GC::undefine_finalizer(&object);
    /// ```
    pub fn define_finalizer<T: Object, F: Object>(
        object: &T,
        finalizer: &F,
    ) -> Result<(), AnyException> {
        let (object, finalizer) = (object.value(), finalizer.value());

        vm::protect_value(|| gc::define_finalizer(object, finalizer))
            .map(|_| ())
            .map_err(AnyException::from)
    }

    /// Removes the finalizers of `object` (Ruby's
    /// `ObjectSpace.undefine_finalizer`, `rb_undefine_finalizer`).
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{GC, NilClass, Object, Proc, VM};
    /// use std::sync::atomic::{AtomicBool, Ordering};
    ///
    /// static FINALIZED: AtomicBool = AtomicBool::new(false);
    ///
    /// # VM::init();
    /// let object = VM::eval("Object.new").unwrap();
    /// let finalizer = Proc::new(|_| {
    ///     FINALIZED.store(true, Ordering::SeqCst);
    ///     NilClass::new().into()
    /// });
    /// GC::define_finalizer(&object, &finalizer).unwrap();
    /// GC::undefine_finalizer(&object);
    ///
    /// // Shutting the VM down runs the finalizers still defined; this one is gone.
    /// unsafe { VM::cleanup() };
    /// assert!(!FINALIZED.load(Ordering::SeqCst));
    /// ```
    pub fn undefine_finalizer<T: Object>(object: &T) {
        gc::undefine_finalizer(object.value());
    }

    /// Returns information about the latest garbage collection, such as
    /// `:major_by` and `:gc_by` (Ruby's `GC.latest_gc_info`,
    /// `rb_gc_latest_gc_info`).
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{GC, Symbol, VM};
    /// # VM::init();
    ///
    /// GC::start();
    ///
    /// assert!(GC::latest_info().has_key(&Symbol::new("gc_by")));
    /// ```
    pub fn latest_info() -> Hash {
        let info = Hash::new();

        Hash::from(gc::latest_gc_info(info.value()))
    }

    /// Tells the generational GC that `parent` now references `child`
    /// (`rb_gc_writebarrier`, C's `RB_OBJ_WRITTEN`).
    ///
    /// Only needed for objects created as write-barrier protected, which
    /// Rutie's `wrappable_struct!` data objects are not.
    ///
    /// # Safety
    ///
    /// `parent` must be a heap object (not an immediate like a `Fixnum`).
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Array, GC, RString, VM};
    /// # VM::init();
    ///
    /// let parent = Array::new();
    /// let child = RString::new_utf8("child");
    ///
    /// unsafe { GC::write_barrier(&parent, &child) };
    ///
    /// GC::start();
    /// assert_eq!(child.to_str(), "child");
    /// ```
    pub unsafe fn write_barrier<P: Object, C: Object>(parent: &P, child: &C) {
        gc::writebarrier(parent.value(), child.value());
    }

    /// Marks `object` as not write-barrier protected, so the generational GC
    /// always rescans it (`rb_gc_writebarrier_unprotect`).
    ///
    /// # Safety
    ///
    /// `object` must be a heap object (not an immediate like a `Fixnum`).
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Array, GC, VM};
    /// # VM::init();
    ///
    /// let array = Array::new();
    /// unsafe { GC::write_barrier_unprotect(&array) };
    ///
    /// GC::start();
    /// assert_eq!(array.length(), 0);
    /// ```
    pub unsafe fn write_barrier_unprotect<T: Object>(object: &T) {
        gc::writebarrier_unprotect(object.value());
    }

    /// Notify memory usage to the GC engine by extension libraries, to trigger GC
    /// This is useful when you wrap large rust objects using wrap_data,
    /// when you do so, ruby is unaware of the allocated memory and might not run GC
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{GC, VM};
    /// # VM::init();
    ///
    ///
    /// let collections = GC::count();
    /// let before = GC::stat("malloc_increase_bytes");
    ///
    /// GC::adjust_memory_usage(25_000); // Tell ruby that we somehow allocated 25_000 bytes of mem
    ///
    /// // Ruby counts it towards its next collection (unless one just ran).
    /// if GC::count() == collections {
    ///     assert!(GC::stat("malloc_increase_bytes") >= before + 25_000);
    /// }
    ///
    /// GC::adjust_memory_usage(-25_000); // Tell ruby that freed 25_000 bytes of mem
    /// ```
    pub fn adjust_memory_usage(diff: isize) {
        gc::adjust_memory_usage(diff)
    }

    /// The number of times GC occurred.
    ///
    /// It returns the number of times GC occurred since the process started.
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{GC, VM};
    /// # VM::init();
    ///
    /// let before = GC::count();
    /// GC::start();
    ///
    /// assert_eq!(GC::count(), before + 1);
    /// ```
    pub fn count() -> usize {
        gc::count()
    }

    /// Disable the garbage collector
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{GC, VM};
    /// # VM::init();
    ///
    /// // Returns whether it was already disabled.
    /// assert!(!GC::disable());
    /// assert!(GC::disable());
    ///
    /// // While disabled, not even an explicit start collects.
    /// let before = GC::count();
    /// GC::start();
    /// assert_eq!(GC::count(), before);
    ///
    /// GC::enable();
    /// ```
    pub fn disable() -> bool {
        gc::disable().is_true()
    }

    /// Enable the garbage collector
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{GC, VM};
    /// # VM::init();
    ///
    /// // Returns whether it was disabled.
    /// assert!(!GC::enable());
    ///
    /// GC::disable();
    /// assert!(GC::enable());
    /// ```
    pub fn enable() -> bool {
        gc::enable().is_true()
    }

    /// Forcibly GC object.
    ///
    /// # Examples
    ///
    /// The object must not be used afterwards. (From Ruby 3.1 this is a no-op,
    /// and Ruby 3.4 removes it; see `docs/ruby3-upgrade-plan.md`.)
    ///
    /// ```
    /// use rutie::{Fixnum, Hash, Module, Object, RString, Symbol, GC, VM};
    /// # VM::init();
    ///
    /// let live_strings = || {
    ///     let counts = unsafe { Module::from_existing("ObjectSpace").send("count_objects", &[]) };
    ///     let counts = counts.try_convert_to::<Hash>().unwrap();
    ///
    ///     counts.at(&Symbol::new("T_STRING")).try_convert_to::<Fixnum>().unwrap().to_i64()
    /// };
    ///
    /// let obj = RString::new_utf8("asdf");
    ///
    /// GC::disable();
    /// live_strings(); // the first call allocates while looking names up
    /// let before = live_strings();
    /// GC::force_recycle(obj);
    /// assert_eq!(live_strings(), before - 1);
    /// GC::enable();
    /// ```
    pub fn force_recycle(object: impl Object) {
        gc::force_recycle(object.value())
    }

    /// Check if object is marked
    ///
    /// CAUTION: THIS FUNCTION IS ENABLED *ONLY BEFORE* SWEEPING.
    /// This function is only for GC_END_MARK timing.
    ///
    /// # Examples
    ///
    /// Use it from a `wrappable_struct!` mark function, while the GC is
    /// marking. A panic there aborts the process, so record the result instead:
    ///
    /// ```
    /// #[macro_use] extern crate rutie;
    /// #[macro_use] extern crate lazy_static;
    ///
    /// use rutie::{AnyObject, Class, Object, RString, GC, VM};
    /// use std::sync::atomic::{AtomicBool, Ordering};
    ///
    /// static MARKED: AtomicBool = AtomicBool::new(false);
    ///
    /// pub struct Holder {
    ///     name: RString,
    /// }
    ///
    /// wrappable_struct! {
    ///     Holder,
    ///     HolderWrapper,
    ///     HOLDER_WRAPPER,
    ///
    ///     mark(data) {
    ///         GC::mark(&data.name);
    ///         MARKED.store(unsafe { GC::is_marked(&data.name) }, Ordering::SeqCst);
    ///     }
    /// }
    ///
    /// fn main() {
    ///     # VM::init();
    ///     let holder: AnyObject = Class::new("Holder", None)
    ///         .wrap_data(Holder { name: RString::new_utf8("held") }, &*HOLDER_WRAPPER);
    ///
    ///     GC::start();
    ///
    ///     assert!(MARKED.load(Ordering::SeqCst), "Object was not marked");
    ///     assert_eq!(holder.get_data(&*HOLDER_WRAPPER).name.to_str(), "held");
    /// }
    /// ```
    pub unsafe fn is_marked(object: &impl Object) -> bool {
        gc::is_marked(object.value())
    }

    /// Mark an object for Ruby to avoid garbage collecting item.
    ///
    /// If the wrapped struct in Rust references Ruby objects, then
    /// you'll have to mark those in the mark callback you are passing
    /// to wrapped struct.
    ///
    /// # Examples
    ///
    /// ```
    /// #[macro_use] extern crate rutie;
    /// #[macro_use] extern crate lazy_static;
    ///
    /// use rutie::{AnyObject, Class, Object, RString, GC, VM};
    ///
    /// pub struct Names {
    ///     names: Vec<RString>,
    /// }
    ///
    /// wrappable_struct! {
    ///     Names,
    ///     NamesWrapper,
    ///     NAMES_WRAPPER,
    ///
    ///     // Called by the GC; the Rust heap is not scanned, so these objects
    ///     // are only kept alive by being marked here.
    ///     mark(data) {
    ///         for name in &data.names { GC::mark(name); }
    ///     }
    /// }
    ///
    /// fn main() {
    ///     # VM::init();
    ///     let names = (0..4).map(|i| RString::new_utf8(&i.to_string())).collect();
    ///     let object: AnyObject = Class::new("Names", None)
    ///         .wrap_data(Names { names }, &*NAMES_WRAPPER);
    ///
    ///     GC::start();
    ///
    ///     let names = &object.get_data(&*NAMES_WRAPPER).names;
    ///     assert_eq!(names[3].to_str(), "3");
    /// }
    /// ```
    pub fn mark(object: &impl Object) {
        gc::mark(object.value());
    }

    /// Mark all of the object from `start` to `end` of the array for the GC.
    ///
    /// # Examples
    ///
    /// ```
    /// #[macro_use] extern crate rutie;
    /// #[macro_use] extern crate lazy_static;
    ///
    /// use rutie::{AnyObject, Class, Object, RString, GC, VM};
    ///
    /// pub struct Names {
    ///     names: Vec<RString>,
    /// }
    ///
    /// wrappable_struct! {
    ///     Names,
    ///     NamesWrapper,
    ///     NAMES_WRAPPER,
    ///
    ///     // Called by the GC; the Rust heap is not scanned, so these objects
    ///     // are only kept alive by being marked here.
    ///     mark(data) {
    ///         GC::mark_locations(&data.names);
    ///     }
    /// }
    ///
    /// fn main() {
    ///     # VM::init();
    ///     let names = (0..4).map(|i| RString::new_utf8(&i.to_string())).collect();
    ///     let object: AnyObject = Class::new("Names", None)
    ///         .wrap_data(Names { names }, &*NAMES_WRAPPER);
    ///
    ///     GC::start();
    ///
    ///     let names = &object.get_data(&*NAMES_WRAPPER).names;
    ///     assert_eq!(names[3].to_str(), "3");
    /// }
    /// ```
    pub fn mark_locations(range: &[impl Object]) {
        for object in range {
            GC::mark_maybe(object)
        }
    }

    /// Maybe mark an object for Ruby to avoid garbage collecting item.
    ///
    /// If the wrapped struct in Rust references Ruby objects, then
    /// you'll have to mark those in the mark callback you are passing
    /// to wrapped struct.
    ///
    /// # Examples
    ///
    /// ```
    /// #[macro_use] extern crate rutie;
    /// #[macro_use] extern crate lazy_static;
    ///
    /// use rutie::{AnyObject, Class, Object, RString, GC, VM};
    ///
    /// pub struct Names {
    ///     names: Vec<RString>,
    /// }
    ///
    /// wrappable_struct! {
    ///     Names,
    ///     NamesWrapper,
    ///     NAMES_WRAPPER,
    ///
    ///     // Called by the GC; the Rust heap is not scanned, so these objects
    ///     // are only kept alive by being marked here.
    ///     mark(data) {
    ///         for name in &data.names { GC::mark_maybe(name); }
    ///     }
    /// }
    ///
    /// fn main() {
    ///     # VM::init();
    ///     let names = (0..4).map(|i| RString::new_utf8(&i.to_string())).collect();
    ///     let object: AnyObject = Class::new("Names", None)
    ///         .wrap_data(Names { names }, &*NAMES_WRAPPER);
    ///
    ///     GC::start();
    ///
    ///     let names = &object.get_data(&*NAMES_WRAPPER).names;
    ///     assert_eq!(names[3].to_str(), "3");
    /// }
    /// ```
    pub fn mark_maybe(object: &impl Object) {
        gc::mark_maybe(object.value());
    }

    /// Keeps `object` alive until a matching [`GC::unregister`](#method.unregister),
    /// even when nothing else references it (for example when only a raw
    /// `Value` is kept in Rust heap memory, which the GC does not scan).
    ///
    /// Registrations are counted: an object registered twice needs two
    /// `unregister` calls. (Before 0.10 this registered the address of a
    /// temporary copy with `rb_gc_register_address`, which did not protect
    /// the object and left the GC reading a stale stack slot.)
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{Fixnum, Object, RString, GC, VM};
    /// # VM::init();
    ///
    /// let id = {
    ///     let object = RString::new_utf8("kept");
    ///     GC::register(&object);
    ///
    ///     unsafe { object.send("object_id", &[]) }
    /// };
    ///
    /// GC::start();
    ///
    /// let object_space = rutie::Module::from_existing("ObjectSpace");
    /// let found = object_space.protect_send("_id2ref", &[id]).unwrap();
    /// assert_eq!(found.try_convert_to::<RString>().unwrap().to_str(), "kept");
    ///
    /// GC::unregister(&found);
    /// ```
    pub fn register(object: &impl Object) {
        gc::register(object.value())
    }

    /// Mark an object as in use for Ruby to avoid garbage collecting item.
    ///
    /// If the wrapped struct in Rust references Ruby objects, then
    /// you'll have to mark those in the mark callback you are passing
    /// to wrapped struct.
    ///
    /// # Examples
    ///
    /// Unlike [`GC::register`](#method.register) this is permanent: the
    /// object lives until the process exits.
    ///
    /// ```
    /// use rutie::{Module, Object, RString, GC, VM};
    /// # VM::init();
    ///
    /// let id = {
    ///     let object = RString::new_utf8("permanent");
    ///     GC::register_mark(&object);
    ///
    ///     unsafe { object.send("object_id", &[]) }
    /// };
    ///
    /// GC::start();
    ///
    /// let found = Module::from_existing("ObjectSpace").protect_send("_id2ref", &[id]).unwrap();
    /// assert_eq!(found.try_convert_to::<RString>().unwrap().to_str(), "permanent");
    /// ```
    pub fn register_mark(object: &impl Object) {
        gc::register_mark(object.value());
    }

    /// Start the garbage collector
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{GC, VM};
    /// # VM::init();
    ///
    /// let before = GC::count();
    ///
    /// GC::start();
    ///
    /// assert_eq!(GC::count(), before + 1);
    /// ```
    pub fn start() {
        gc::start()
    }

    /// Get the GC stats for a specific key
    ///
    /// Note: Will panic if provided an invalid key.
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{GC, VM};
    /// # VM::init();
    ///
    /// assert!(GC::stat("heap_allocated_pages") > 0);
    /// assert_eq!(GC::stat("count"), GC::count());
    /// ```
    pub fn stat(key: &str) -> usize {
        let key = Symbol::new(key);

        gc::stat(key.value())
    }

    /// Undoes one [`GC::register`](#method.register) of `object`; once every
    /// registration is undone, the GC may collect it again. Unregistering an
    /// object that is not registered does nothing.
    ///
    /// # Examples
    ///
    /// ```
    /// use rutie::{RString, GC, VM};
    /// # VM::init();
    ///
    /// let object = RString::new_utf8("1");
    ///
    /// GC::register(&object);
    /// GC::register(&object);
    /// GC::unregister(&object);
    /// GC::unregister(&object);
    ///
    /// // Extra calls are harmless.
    /// GC::unregister(&object);
    ///
    /// // Unregistering only lets the GC collect it once nothing references
    /// // it; `object` is still in use here.
    /// GC::start();
    /// assert_eq!(object.to_str(), "1");
    /// ```
    pub fn unregister(object: &impl Object) {
        gc::unregister(object.value())
    }
}

#[cfg(test)]
mod tests {
    use crate::{Fixnum, NilClass, Object, Proc, Symbol, GC, VM};
    use std::sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    };

    #[test]
    fn test_finalizers_run_after_collection() {
        crate::on_ruby_thread(|| {
            let finalized = Arc::new(AtomicUsize::new(0));

            for _ in 0..20 {
                let object = VM::eval("Object.new").unwrap();
                let counter = finalized.clone();
                let finalizer = Proc::new(move |_| {
                    counter.fetch_add(1, Ordering::SeqCst);
                    NilClass::new().into()
                });

                GC::define_finalizer(&object, &finalizer).unwrap();
            }

            GC::start();
            GC::start();
            VM::eval("20.times { Object.new }").unwrap();

            assert!(finalized.load(Ordering::SeqCst) > 0, "no finalizer ran");

            let frozen = VM::eval("Object.new.freeze").unwrap();
            assert!(GC::define_finalizer(&frozen, &Proc::new(|_| NilClass::new().into())).is_err());
            assert!(
                GC::define_finalizer(&VM::eval("Object.new").unwrap(), &Fixnum::new(1)).is_err()
            );
        });
    }

    #[test]
    fn test_latest_info() {
        crate::on_ruby_thread(|| {
            GC::start();

            let info = GC::latest_info();
            assert!(info.has_key(&Symbol::new("major_by")));
            assert!(info.length() > 2);
        });
    }

    pub struct RutieGcHolder {
        objects: Vec<crate::AnyObject>,
    }

    crate::wrappable_struct! {
        RutieGcHolder,
        RutieGcHolderWrapper,
        RUTIE_GC_HOLDER,

        mark(data) {
            // `mark_locations` and `mark_maybe` are for mark functions.
            GC::mark_locations(&data.objects);
            for object in &data.objects {
                GC::mark_maybe(object);
            }
            // `is_marked` only means something during marking. A panic here
            // would abort, so the result is recorded instead.
            let marked = data.objects.iter().all(|object| unsafe { GC::is_marked(object) });
            HOLDER_CONTENTS_MARKED.store(marked, Ordering::SeqCst);
        }
    }

    static HOLDER_CONTENTS_MARKED: std::sync::atomic::AtomicBool =
        std::sync::atomic::AtomicBool::new(false);

    fn id2ref(id: &crate::AnyObject) -> Result<crate::AnyObject, crate::AnyException> {
        crate::Module::from_existing("ObjectSpace").protect_send("_id2ref", &[id.clone()])
    }

    #[test]
    fn test_gc_register_keeps_objects_alive() {
        crate::on_ruby_thread(|| {
            // Only a raw value in Rust heap memory, which the GC does not scan.
            let raw: Box<crate::types::Value> =
                Box::new(crate::RString::new_utf8("registered").value());
            let object = crate::RString::from(*raw);
            GC::register(&object);
            GC::register(&object);
            assert_eq!(crate::binding::gc::registered_count(*raw), 2);

            let id = unsafe { object.send("object_id", &[]) };
            drop(object);

            for _ in 0..3 {
                GC::start();
            }

            let found = id2ref(&id).unwrap();
            assert_eq!(
                found.try_convert_to::<crate::RString>().unwrap().to_str(),
                "registered"
            );

            GC::unregister(&found);
            assert_eq!(crate::binding::gc::registered_count(*raw), 1);
            GC::unregister(&found);
            assert_eq!(crate::binding::gc::registered_count(*raw), 0);
            GC::unregister(&found);
            assert_eq!(crate::binding::gc::registered_count(*raw), 0);

            let permanent = crate::RString::new_utf8("permanent");
            GC::register_mark(&permanent);
            GC::start();
            assert_eq!(permanent.to_str(), "permanent");
        });
    }

    #[test]
    fn test_gc_controls_and_marking() {
        crate::on_ruby_thread(|| {
            let was_disabled = GC::disable();
            assert!(
                GC::disable(),
                "second disable reports it was already disabled"
            );
            assert!(GC::enable(), "enable reports it was disabled");
            assert!(!GC::enable());
            if was_disabled {
                GC::disable();
            }

            let before = GC::count();
            GC::start();
            assert!(GC::count() > before);
            assert_eq!(GC::stat("count"), GC::count());

            GC::adjust_memory_usage(4096);
            GC::adjust_memory_usage(-4096);

            let holder = crate::Class::new("RutieGcHolderClass", None).wrap_data(
                RutieGcHolder {
                    objects: vec![crate::RString::new_utf8("held").to_any_object()],
                },
                &*RUTIE_GC_HOLDER,
            );
            let holder: crate::AnyObject = holder;
            GC::start();
            let held = holder.get_data(&*RUTIE_GC_HOLDER).objects[0].clone();
            assert_eq!(
                held.try_convert_to::<crate::RString>().unwrap().to_str(),
                "held"
            );
            assert!(HOLDER_CONTENTS_MARKED.load(Ordering::SeqCst));

            // `force_recycle` frees an object immediately; it must not be used again.
            let garbage = crate::RString::new_utf8("recycled");
            GC::force_recycle(garbage);

            let object = crate::RString::new_utf8("finalizable");
            let finalizer = Proc::new(|_| NilClass::new().into());
            GC::define_finalizer(&object, &finalizer).unwrap();
            GC::undefine_finalizer(&object);
        });
    }

    #[test]
    fn test_write_barriers() {
        crate::on_ruby_thread(|| {
            let parent = crate::Array::new();
            let child = crate::RString::new_utf8("child");

            // Required when a Rust-managed parent starts referencing a child.
            unsafe { GC::write_barrier(&parent, &child) };
            // Opting an object out of generational GC is always allowed.
            unsafe { GC::write_barrier_unprotect(&parent) };

            GC::start();
            assert_eq!(child.to_str(), "child");
        });
    }
}