rb-sys 0.9.127

Rust bindings for the CRuby API
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
//! Stable ABI functions which provide access to Ruby internals that
//! is compatible across Ruby versions, and are guaranteed to be not break due
//! to Ruby binary changes.
//!
//! ### Goals
//!
//! 1. To provide access to Ruby internals that are not exposed by the libruby
//!    (i.e. C macros and inline functions).
//! 2. Provide support for Ruby development versions, which can make breaking
//!    changes without semantic versioning. We want to support these versions
//!    to ensure Rust extensions don't prevent the Ruby core team from testing
//!    changes in production.

use crate::{ID, VALUE};
use std::{
    os::raw::{c_char, c_long},
    ptr::NonNull,
    time::Duration,
};

pub trait StableApiDefinition {
    const VERSION_MAJOR: u32;
    const VERSION_MINOR: u32;

    fn version(&self) -> (u32, u32) {
        (Self::VERSION_MAJOR, Self::VERSION_MINOR)
    }

    /// Get the length of a Ruby string (akin to `RSTRING_LEN`).
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying Ruby data. The caller must ensure that the pointer
    /// is valid.
    unsafe fn rstring_len(&self, obj: VALUE) -> c_long;

    /// Get a pointer to the bytes of a Ruby string (akin to `RSTRING_PTR`).
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying Ruby data. The caller must ensure that the pointer
    /// is valid.
    unsafe fn rstring_ptr(&self, obj: VALUE) -> *const c_char;

    /// Get the length of a Ruby array (akin to `RARRAY_LEN`).
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying Ruby data. The caller must ensure that the pointer
    /// is valid.
    unsafe fn rarray_len(&self, obj: VALUE) -> c_long;

    /// Get a pointer to the elements of a Ruby array (akin to `RARRAY_CONST_PTR`).
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying Ruby data. The caller must ensure that the pointer
    /// is valid.
    unsafe fn rarray_const_ptr(&self, obj: VALUE) -> *const VALUE;

    /// Get element from array by index (akin to `RARRAY_AREF`).
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying Ruby data. The caller must ensure that the pointer
    /// is valid and that the index is within bounds.
    unsafe fn rarray_aref(&self, obj: VALUE, idx: isize) -> VALUE;

    /// Set element in array by index (akin to `RARRAY_ASET`).
    ///
    /// Includes GC write barrier for safety.
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying Ruby data. The caller must ensure that the pointer
    /// is valid and that the index is within bounds.
    unsafe fn rarray_aset(&self, obj: VALUE, idx: isize, val: VALUE);

    /// Get the class from a VALUE which contains an RBasic struct.
    ///
    /// `VALUE` is a valid pointer to a non-immediate object.
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying RBasic struct. The caller must ensure that the
    /// `VALUE` is a valid pointer to an RBasic struct.
    unsafe fn rbasic_class(&self, obj: VALUE) -> Option<NonNull<VALUE>>;

    /// Checks if the given object is frozen.
    ///
    /// `VALUE` is a valid pointer to a non-immediate object.
    ///
    /// # Safety
    /// This function is unsafe because it may dereference a raw pointer to get
    /// access to underlying RBasic struct. The caller must ensure that the
    /// `VALUE` is a valid pointer to an RBasic struct.
    unsafe fn frozen_p(&self, obj: VALUE) -> bool;

    /// Tests if a bignum is positive.
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying RBasic struct. The caller must ensure that the
    /// `VALUE` is a valid pointer to a bignum.
    unsafe fn bignum_positive_p(&self, obj: VALUE) -> bool;

    /// Tests if a bignum is negative.
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying RBasic struct. The caller must ensure that the
    /// `VALUE` is a valid pointer to a bignum.
    #[inline]
    unsafe fn bignum_negative_p(&self, obj: VALUE) -> bool {
        !self.bignum_positive_p(obj)
    }

    /// Tests if the given value is a special constant.
    fn special_const_p(&self, value: VALUE) -> bool;

    /// Queries the type of the object.
    ///
    /// # Note
    /// The input `obj` must not be a special constant.
    ///
    /// # Safety
    /// This function is unsafe because it could dereference a raw pointer when
    /// attemping to access the underlying [`RBasic`] struct.
    unsafe fn builtin_type(&self, obj: VALUE) -> crate::ruby_value_type;

    /// Tests if the object's type is the given type.
    ///
    /// # Safety
    /// This function is unsafe because it could dereference a raw pointer when
    /// attemping to access the underlying [`RBasic`] struct.
    unsafe fn type_p(&self, obj: VALUE, ty: crate::ruby_value_type) -> bool;

    /// Checks if the given object is nil.
    fn nil_p(&self, obj: VALUE) -> bool;

    /// Checks if the given object is a so-called Fixnum.
    fn fixnum_p(&self, obj: VALUE) -> bool;

    /// Checks if the given object is a dynamic symbol.
    ///
    /// # Safety
    /// This function is unsafe because it could dereference a raw pointer when
    /// attemping to access the underlying [`RBasic`] struct.
    unsafe fn dynamic_sym_p(&self, obj: VALUE) -> bool;

    /// Checks if the given object is a static symbol.
    fn static_sym_p(&self, obj: VALUE) -> bool;

    /// Checks if the given object is a symbol.
    ///
    /// # Safety
    /// This function is unsafe because it could dereference a raw pointer when
    /// attemping to access the underlying [`RBasic`] struct.
    unsafe fn symbol_p(&self, obj: VALUE) -> bool;

    /// Checks if the given object is a so-called Flonum.
    ///
    /// # Safety
    /// This function is unsafe because it could dereference a raw pointer when
    /// attemping to access the underlying [`RBasic`] struct.
    unsafe fn float_type_p(&self, obj: VALUE) -> bool;

    /// Checks if the given object is an integer type
    ///
    /// # Safety
    /// This function is unsafe because it could dereference a raw pointer when
    /// attemping to access the underlying [`RBasic`] struct.
    unsafe fn integer_type_p(&self, obj: VALUE) -> bool;

    /// Checks if the given object is a so-called Flonum.
    fn flonum_p(&self, obj: VALUE) -> bool;

    /// Checks if the given  object is  an immediate  i.e. an  object which  has
    /// no corresponding storage inside of the object space.
    fn immediate_p(&self, obj: VALUE) -> bool;

    /// Emulates Ruby's "if" statement by testing if the given `obj` is neither `Qnil` or `Qfalse`.
    ///
    /// # Safety
    /// This function is unsafe because it could dereference a raw pointer when
    /// attemping to access the underlying [`RBasic`] struct.
    fn rb_test(&self, ob: VALUE) -> bool;

    /// Queries the type of the object. Identical to `StableApi.builtin_type`,
    /// except it can also accept special constants.
    ///
    /// # Safety
    /// This function is unsafe because it could dereference a raw pointer when
    /// attemping to access the underlying [`RBasic`] struct.
    unsafe fn rb_type(&self, obj: VALUE) -> crate::ruby_value_type;

    /// Check if a Ruby string is interned (akin to `RSTRING_FSTR`).
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying flags of the RString. The caller must ensure that
    /// the `VALUE` is a valid pointer to an RString.
    unsafe fn rstring_interned_p(&self, obj: VALUE) -> bool;

    /// Blocks the current thread until the given duration has passed.
    fn thread_sleep(&self, duration: Duration);

    /// Checks if the given object is an RTypedData.
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying Ruby data. The caller must ensure that the pointer
    /// is valid and points to a T_DATA object.
    unsafe fn rtypeddata_p(&self, obj: VALUE) -> bool;

    /// Gets the data type from an RTypedData object.
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying Ruby data. The caller must ensure that the pointer
    /// is valid and points to an RTypedData object.
    unsafe fn rtypeddata_type(&self, obj: VALUE) -> *const crate::rb_data_type_t;

    /// Gets the data pointer from an RTypedData object.
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying Ruby data. The caller must ensure that the pointer
    /// is valid and points to an RTypedData object.
    unsafe fn rtypeddata_get_data(&self, obj: VALUE) -> *mut std::ffi::c_void;

    /// Get pointer to end of string contents (akin to `RSTRING_END`).
    ///
    /// Returns a pointer to the byte after the last character of the string.
    ///
    /// # Safety
    /// - `obj` must be a valid Ruby String object
    unsafe fn rstring_end(&self, obj: VALUE) -> *const c_char;

    /// Get data pointer from RData/TypedData object (akin to `DATA_PTR`).
    ///
    /// Returns the user data pointer stored in an RData or TypedData object.
    ///
    /// # Safety
    /// - `obj` must be a valid RData or TypedData object
    unsafe fn rdata_ptr(&self, obj: VALUE) -> *mut std::ffi::c_void;

    /// Freeze an object (akin to `RB_OBJ_FREEZE`).
    ///
    /// Sets the frozen flag on an object, preventing further modification.
    ///
    /// # Safety
    /// - `obj` must be a valid heap-allocated Ruby object
    unsafe fn rb_obj_freeze(&self, obj: VALUE);

    /// Check if object is promoted to old GC generation (akin to `RB_OBJ_PROMOTED`).
    ///
    /// Returns true if the object has been promoted to the old generation
    /// in Ruby's generational GC.
    ///
    /// # Safety
    /// - `obj` must be a valid VALUE
    unsafe fn rb_obj_promoted(&self, obj: VALUE) -> bool;

    /// Raw version assuming FL_ABLE (akin to `RB_OBJ_PROMOTED_RAW`).
    ///
    /// # Safety
    /// - `obj` must be a valid heap-allocated Ruby object (FL_ABLE must be true)
    unsafe fn rb_obj_promoted_raw(&self, obj: VALUE) -> bool;

    /// Convert Ruby numeric to C double (akin to `NUM2DBL`).
    ///
    /// Works for Float (including Flonum), Fixnum, and other numeric types.
    ///
    /// # Safety
    /// This function is unsafe because it may dereference a raw pointer to get
    /// access to underlying Ruby data. The caller must ensure that the pointer
    /// is valid.
    unsafe fn num2dbl(&self, obj: VALUE) -> std::os::raw::c_double;

    /// Convert C double to Ruby Float VALUE (akin to `DBL2NUM`).
    ///
    /// May return a Flonum (tagged pointer) for small values on 64-bit platforms,
    /// or a heap-allocated Float object.
    fn dbl2num(&self, val: std::os::raw::c_double) -> VALUE;

    /// Get hash size (akin to `RHASH_SIZE`).
    ///
    /// Returns the number of entries in the hash.
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying Ruby data. The caller must ensure that the pointer
    /// is valid and points to a Hash object.
    unsafe fn rhash_size(&self, obj: VALUE) -> usize;

    /// Check if hash is empty (akin to `RHASH_EMPTY_P`).
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying Ruby data. The caller must ensure that the pointer
    /// is valid and points to a Hash object.
    unsafe fn rhash_empty_p(&self, obj: VALUE) -> bool;

    /// Get encoding index from object (akin to `ENCODING_GET`).
    ///
    /// Returns the encoding index stored in the object's flags.
    ///
    /// # Safety
    /// This function is unsafe because it dereferences a raw pointer to get
    /// access to underlying Ruby data. The caller must ensure that the pointer
    /// is valid and points to an object with encoding (String, Regexp, Symbol).
    unsafe fn encoding_get(&self, obj: VALUE) -> std::os::raw::c_int;

    /// Check if an object can have flags (akin to `RB_FL_ABLE`).
    ///
    /// Returns false for immediate values (nil, true, false, Fixnum, Symbol, Flonum)
    /// which don't have flag storage. Returns true for heap-allocated objects.
    fn fl_able(&self, obj: VALUE) -> bool;

    /// Convert Fixnum to long (akin to `FIX2LONG`).
    ///
    /// Extracts the integer value from a Fixnum VALUE.
    ///
    /// # Safety assumptions
    /// - `obj` must be a valid Fixnum VALUE
    fn fix2long(&self, obj: VALUE) -> std::os::raw::c_long;

    /// Convert Fixnum to unsigned long (akin to `FIX2ULONG`).
    ///
    /// Extracts the unsigned integer value from a Fixnum VALUE.
    ///
    /// # Safety assumptions
    /// - `obj` must be a valid positive Fixnum VALUE
    fn fix2ulong(&self, obj: VALUE) -> std::os::raw::c_ulong;

    /// Convert long to Fixnum (akin to `LONG2FIX`).
    ///
    /// Creates a Fixnum VALUE from a long integer.
    ///
    /// # Safety assumptions
    /// - `val` must be in the valid Fixnum range
    fn long2fix(&self, val: std::os::raw::c_long) -> VALUE;

    /// Check if long value can be represented as Fixnum (akin to `FIXABLE`).
    ///
    /// Returns true if the value fits in a Fixnum.
    fn fixable(&self, val: std::os::raw::c_long) -> bool;

    /// Check if unsigned long value can be represented as positive Fixnum (akin to `POSFIXABLE`).
    ///
    /// Returns true if the value fits in a positive Fixnum.
    fn posfixable(&self, val: std::os::raw::c_ulong) -> bool;

    /// Convert Ruby Integer to long (akin to `NUM2LONG`).
    ///
    /// Converts any Ruby Integer (Fixnum or Bignum) to a C long.
    /// May raise an exception if the value is out of range.
    ///
    /// # Safety
    /// - `obj` must be a valid Integer VALUE
    /// - May call into Ruby runtime (for Bignum conversion)
    unsafe fn num2long(&self, obj: VALUE) -> std::os::raw::c_long;

    /// Convert Ruby Integer to unsigned long (akin to `NUM2ULONG`).
    ///
    /// Converts any Ruby Integer (Fixnum or Bignum) to a C unsigned long.
    /// May raise an exception if the value is out of range or negative.
    ///
    /// # Safety
    /// - `obj` must be a valid Integer VALUE
    /// - May call into Ruby runtime (for Bignum conversion)
    unsafe fn num2ulong(&self, obj: VALUE) -> std::os::raw::c_ulong;

    /// Convert long to Ruby Integer (akin to `LONG2NUM`).
    ///
    /// Creates a Ruby Integer (Fixnum or Bignum) from a C long.
    /// Uses Fixnum if possible, otherwise allocates a Bignum.
    fn long2num(&self, val: std::os::raw::c_long) -> VALUE;

    /// Convert unsigned long to Ruby Integer (akin to `ULONG2NUM`).
    ///
    /// Creates a Ruby Integer (Fixnum or Bignum) from a C unsigned long.
    /// Uses Fixnum if possible, otherwise allocates a Bignum.
    fn ulong2num(&self, val: std::os::raw::c_ulong) -> VALUE;

    /// Convert ID to Symbol (akin to `RB_ID2SYM`).
    ///
    /// Converts an internal ID to its corresponding Symbol VALUE.
    /// This is a safe operation - just bit manipulation for static symbols.
    fn id2sym(&self, id: ID) -> VALUE;

    /// Convert Symbol to ID (akin to `RB_SYM2ID`).
    ///
    /// Converts a Symbol VALUE to its internal ID representation.
    ///
    /// # Safety
    /// - `obj` must be a valid Symbol VALUE
    /// - For dynamic symbols, this may access the heap
    unsafe fn sym2id(&self, obj: VALUE) -> ID;

    /// Execute GC write barrier when storing a reference (akin to `RB_OBJ_WRITE`).
    ///
    /// Must be called when storing a VALUE reference from one heap object to another.
    /// This is critical for GC correctness - without it, the GC may collect objects
    /// that are still referenced.
    ///
    /// # Safety
    /// - `old` must be a valid heap-allocated Ruby object
    /// - `slot` must be a valid pointer to a VALUE within `old`
    /// - `young` must be a valid VALUE
    unsafe fn rb_obj_write(&self, old: VALUE, slot: *mut VALUE, young: VALUE) -> VALUE;

    /// Declare a write barrier without actually writing (akin to `RB_OBJ_WRITTEN`).
    ///
    /// Use this when you've already written a reference but need to inform the GC.
    ///
    /// # Safety
    /// - `old` must be a valid heap-allocated Ruby object
    /// - `oldv` is the previous value (can be any VALUE)
    /// - `young` must be a valid VALUE that was written
    unsafe fn rb_obj_written(&self, old: VALUE, oldv: VALUE, young: VALUE) -> VALUE;
}

#[cfg(stable_api_enable_compiled_mod)]
mod compiled;
#[cfg(stable_api_export_compiled_as_api)]
use compiled as api;

#[cfg(stable_api_include_rust_impl)]
#[cfg_attr(ruby_eq_2_7, path = "stable_api/ruby_2_7.rs")]
#[cfg_attr(ruby_eq_3_0, path = "stable_api/ruby_3_0.rs")]
#[cfg_attr(ruby_eq_3_1, path = "stable_api/ruby_3_1.rs")]
#[cfg_attr(ruby_eq_3_2, path = "stable_api/ruby_3_2.rs")]
#[cfg_attr(ruby_eq_3_3, path = "stable_api/ruby_3_3.rs")]
#[cfg_attr(ruby_eq_3_4, path = "stable_api/ruby_3_4.rs")]
#[cfg_attr(ruby_eq_4_0, path = "stable_api/ruby_4_0.rs")]
mod rust;
#[cfg(not(stable_api_export_compiled_as_api))]
use rust as api;

impl std::fmt::Debug for api::Definition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StableApiDefinition")
            .field("VERSION_MAJOR", &api::Definition::VERSION_MAJOR)
            .field("VERSION_MINOR", &api::Definition::VERSION_MINOR)
            .finish()
    }
}

/// Get the default stable API definition for the current Ruby version.
#[inline(always)]
pub const fn get_default() -> &'static api::Definition {
    const API: api::Definition = api::Definition {};
    &API
}

/// Get the fallback stable API definition for the current Ruby version, which
/// is compiled C code that is linked into to this crate.
#[inline(always)]
#[cfg(stable_api_enable_compiled_mod)]
pub const fn get_compiled() -> &'static compiled::Definition {
    const COMPILED_API: compiled::Definition = compiled::Definition {};
    &COMPILED_API
}