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
//! Types and functions for working with Ruby's Struct class.
//!
//! See also [`Ruby`](Ruby#struct) for more Struct related methods.

use std::{
    borrow::Cow,
    ffi::CString,
    fmt,
    os::raw::c_char,
    ptr::{null, NonNull},
    slice,
};

use rb_sys::{
    rb_struct_aref, rb_struct_aset, rb_struct_define, rb_struct_getmember, rb_struct_members,
    rb_struct_size, ruby_value_type, VALUE,
};
use seq_macro::seq;

use crate::{
    class::RClass,
    error::{protect, Error},
    into_value::IntoValue,
    object::Object,
    r_array::RArray,
    symbol::Symbol,
    try_convert::TryConvert,
    value::{self, private::ReprValue as _, IntoId, NonZeroValue, ReprValue, Value},
    Ruby,
};

// Ruby provides some inline functions to get a pointer to the struct's
// contents, but we have to reimplement those for Rust. The for that we need
// the definition of RStruct, but that isn't public, so we have to duplicate it
// here.
mod sys {
    #[cfg(ruby_lt_3_0)]
    use rb_sys::ruby_fl_type::RUBY_FL_USHIFT;
    #[cfg(ruby_gte_3_0)]
    use rb_sys::ruby_fl_ushift::RUBY_FL_USHIFT;
    use rb_sys::{ruby_fl_type, RBasic, VALUE};

    #[cfg(ruby_gte_2_7)]
    pub const EMBED_LEN_MAX: u32 = rb_sys::ruby_rvalue_flags::RVALUE_EMBED_LEN_MAX as u32;

    #[cfg(ruby_lt_2_7)]
    pub const EMBED_LEN_MAX: u32 = 3;

    pub const EMBED_LEN_MASK: u32 =
        ruby_fl_type::RUBY_FL_USER2 as u32 | ruby_fl_type::RUBY_FL_USER1 as u32;
    pub const EMBED_LEN_SHIFT: u32 = RUBY_FL_USHIFT as u32 + 1;

    #[repr(C)]
    #[derive(Copy, Clone)]
    pub struct RStruct {
        pub basic: RBasic,
        pub as_: As,
    }
    #[repr(C)]
    #[derive(Copy, Clone)]
    pub union As {
        pub heap: Heap,
        pub ary: [VALUE; EMBED_LEN_MAX as usize],
    }
    #[repr(C)]
    #[derive(Debug, Copy, Clone)]
    pub struct Heap {
        pub len: std::os::raw::c_long,
        pub ptr: *const VALUE,
    }
}

/// A Value pointer to a RStruct struct, Ruby’s internal representation of
/// 'Structs'.
///
/// See the [`ReprValue`] and [`Object`] traits for additional methods
/// available on this type.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct RStruct(NonZeroValue);

impl RStruct {
    /// Return `Some(RStruct)` if `val` is a `RStruct`, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{define_global_const, eval, r_struct::define_struct, RStruct};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let struct_class = define_struct(None, ("foo", "bar")).unwrap();
    /// define_global_const("Example", struct_class).unwrap();
    ///
    /// assert!(RStruct::from_value(eval(r#"Example.new(1, 2)"#).unwrap()).is_some());
    /// assert!(RStruct::from_value(eval(r#"Object.new"#).unwrap()).is_none());
    /// ```
    #[inline]
    pub fn from_value(val: Value) -> Option<Self> {
        unsafe {
            (val.rb_type() == ruby_value_type::RUBY_T_STRUCT)
                .then(|| Self(NonZeroValue::new_unchecked(val)))
        }
    }

    pub(crate) unsafe fn from_rb_value_unchecked(val: VALUE) -> Self {
        Self(NonZeroValue::new_unchecked(Value::new(val)))
    }

    fn as_internal(self) -> NonNull<sys::RStruct> {
        // safe as inner value is NonZero
        unsafe { NonNull::new_unchecked(self.0.get().as_rb_value() as *mut _) }
    }

    /// Return the members of the struct as a slice of [`Value`]s. The order
    /// will be the order the of the member names when the struct class was
    /// defined.
    ///
    /// # Safety
    ///
    /// Ruby may modify or free the memory backing the returned slice, the
    /// caller must ensure this does not happen.
    #[deprecated(since = "0.6.0")]
    pub unsafe fn as_slice(&self) -> &[Value] {
        self.as_slice_unconstrained()
    }

    unsafe fn as_slice_unconstrained<'a>(self) -> &'a [Value] {
        debug_assert_value!(self);
        let r_basic = self.r_basic_unchecked();
        let flags = r_basic.as_ref().flags;
        if (flags & sys::EMBED_LEN_MASK as VALUE) != 0 {
            let len = (flags & sys::EMBED_LEN_MASK as VALUE) >> sys::EMBED_LEN_SHIFT as VALUE;
            slice::from_raw_parts(
                &self.as_internal().as_ref().as_.ary as *const VALUE as *const Value,
                len as usize,
            )
        } else {
            let h = self.as_internal().as_ref().as_.heap;
            slice::from_raw_parts(h.ptr as *const Value, h.len as usize)
        }
    }

    /// Return the value for the member at `index`, where members are ordered
    /// as per the member names when the struct class was defined.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, r_struct::define_struct, RStruct};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let struct_class = define_struct(None, ("foo", "bar")).unwrap();
    /// let instance = RStruct::from_value(struct_class.new_instance((1, 2)).unwrap()).unwrap();
    /// assert_eq!(instance.get::<i64>(0).unwrap(), 1);
    /// assert_eq!(instance.get::<i64>(1).unwrap(), 2);
    /// ```
    #[allow(deprecated)]
    pub fn get<T>(self, index: usize) -> Result<T, Error>
    where
        T: TryConvert,
    {
        unsafe {
            let slice = self.as_slice();
            slice
                .get(index)
                .copied()
                .ok_or_else(|| {
                    Error::new(
                        Ruby::get_with(self).exception_index_error(),
                        format!(
                            "offset {} too large for struct(size:{})",
                            index,
                            slice.len()
                        ),
                    )
                })
                .and_then(TryConvert::try_convert)
        }
    }

    /// Return the value for the member at `index`.
    ///
    /// `index` may be an integer, string, or [`Symbol`].
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, r_struct::define_struct, RStruct, Symbol};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let struct_class = define_struct(None, ("foo", "bar", "baz")).unwrap();
    /// let instance = RStruct::from_value(struct_class.new_instance((1, 2, 3)).unwrap()).unwrap();
    /// assert_eq!(instance.aref::<_, i64>(0).unwrap(), 1);
    /// assert_eq!(instance.aref::<_, i64>("bar").unwrap(), 2);
    /// assert_eq!(instance.aref::<_, i64>(Symbol::new("baz")).unwrap(), 3);
    /// ```
    pub fn aref<T, U>(self, index: T) -> Result<U, Error>
    where
        T: IntoValue,
        U: TryConvert,
    {
        let index = Ruby::get_with(self).into_value(index);
        protect(|| unsafe { Value::new(rb_struct_aref(self.as_rb_value(), index.as_rb_value())) })
            .and_then(TryConvert::try_convert)
    }

    /// Set the value for the member at `index`.
    ///
    /// `index` may be an integer, string, or [`Symbol`].
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, r_struct::define_struct, rb_assert, RStruct, Symbol};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let struct_class = define_struct(None, ("foo", "bar", "baz")).unwrap();
    /// let instance = RStruct::from_value(struct_class.new_instance((1, 2, 3)).unwrap()).unwrap();
    ///
    /// instance.aset(0, 4).unwrap();
    /// rb_assert!("instance.foo == 4", instance);
    ///
    /// instance.aset("bar", 5).unwrap();
    /// rb_assert!("instance.bar == 5", instance);
    ///
    /// instance.aset(Symbol::new("baz"), 6).unwrap();
    /// rb_assert!("instance.baz == 6", instance);
    /// ```
    pub fn aset<T, U>(self, index: T, val: U) -> Result<(), Error>
    where
        T: IntoValue,
        U: IntoValue,
    {
        let handle = Ruby::get_with(self);
        let index = handle.into_value(index);
        let val = handle.into_value(val);
        unsafe {
            protect(|| {
                Value::new(rb_struct_aset(
                    self.as_rb_value(),
                    index.as_rb_value(),
                    val.as_rb_value(),
                ))
            })?;
        }
        Ok(())
    }

    /// Returns the count of members this struct has.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, r_struct::define_struct, RStruct};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let struct_class = define_struct(None, ("foo", "bar", "baz")).unwrap();
    /// let instance = RStruct::from_value(struct_class.new_instance(()).unwrap()).unwrap();
    ///
    /// assert_eq!(instance.size(), 3);
    /// ```
    pub fn size(self) -> usize {
        unsafe { usize::try_convert(Value::new(rb_struct_size(self.as_rb_value()))).unwrap() }
    }

    /// Returns the member names for this struct.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, r_struct::define_struct, RStruct};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let struct_class = define_struct(None, ("foo", "bar", "baz")).unwrap();
    /// let instance = RStruct::from_value(struct_class.new_instance(()).unwrap()).unwrap();
    ///
    /// assert_eq!(instance.members().unwrap(), &["foo", "bar", "baz"]);
    /// ```
    pub fn members(self) -> Result<Vec<Cow<'static, str>>, Error> {
        unsafe {
            let array = RArray::from_rb_value_unchecked(rb_struct_members(self.as_rb_value()));
            array
                .as_slice()
                .iter()
                .map(|v| Symbol::from_value(*v).unwrap().name())
                .collect()
        }
    }

    /// Return the value for the member named `id`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, r_struct::define_struct, RStruct};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let struct_class = define_struct(None, ("foo", "bar")).unwrap();
    /// let instance = RStruct::from_value(struct_class.new_instance((1, 2)).unwrap()).unwrap();
    /// assert_eq!(instance.getmember::<_, i64>("foo").unwrap(), 1);
    /// assert_eq!(instance.getmember::<_, i64>("bar").unwrap(), 2);
    /// ```
    pub fn getmember<T, U>(self, id: T) -> Result<U, Error>
    where
        T: IntoId,
        U: TryConvert,
    {
        let id = id.into_id_with(&Ruby::get_with(self));
        protect(|| unsafe { Value::new(rb_struct_getmember(self.as_rb_value(), id.as_rb_id())) })
            .and_then(TryConvert::try_convert)
    }
}

impl fmt::Display for RStruct {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", unsafe { self.to_s_infallible() })
    }
}

impl fmt::Debug for RStruct {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inspect())
    }
}

impl IntoValue for RStruct {
    #[inline]
    fn into_value_with(self, _: &Ruby) -> Value {
        self.0.get()
    }
}

impl Object for RStruct {}

unsafe impl value::private::ReprValue for RStruct {}

impl ReprValue for RStruct {}

impl TryConvert for RStruct {
    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 Struct", unsafe {
                    val.classname()
                },),
            )
        })
    }
}

/// # `Struct`
///
/// Functions that can be used to create Ruby `Struct` classes.
///
/// See also the [`struct`](self) module.
impl Ruby {
    /// Define a Ruby Struct class.
    ///
    /// `members` is a tuple of `&str`, of between lengths 1 to 12 inclusive.
    ///
    /// # Examples
    ///
    /// When providing `None` for the `name` the struct class's name will be
    /// taken from the first constant it is assigned to:
    ///
    /// ```
    /// use magnus::{prelude::*, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let struct_class = ruby.define_struct(None, ("foo", "bar"))?;
    ///     ruby.define_global_const("Example", struct_class)?;
    ///
    ///     assert_eq!(unsafe { struct_class.name().to_owned() }, "Example");
    ///
    ///     let instance = struct_class.new_instance((1, 2))?;
    ///     assert_eq!(instance.inspect(), "#<struct Example foo=1, bar=2>");
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    ///
    /// When providing `Some("Name")` for the `name` the struct will be defined
    /// under `Struct`:
    ///
    /// ```
    /// use magnus::{prelude::*, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let struct_class = ruby.define_struct(Some("Example"), ("foo", "bar"))?;
    ///
    ///     assert_eq!(unsafe { struct_class.name().to_owned() }, "Struct::Example");
    ///
    ///     let instance = struct_class.new_instance((1, 2))?;
    ///     assert_eq!(instance.inspect(), "#<struct Struct::Example foo=1, bar=2>");
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn define_struct<T>(&self, name: Option<&str>, members: T) -> Result<RClass, Error>
    where
        T: StructMembers,
    {
        members.define(name)
    }
}

/// Define a Ruby Struct class.
///
/// `members` is a tuple of `&str`, of between lengths 1 to 12 inclusive.
///
/// # Panics
///
/// Panics if called from a non-Ruby thread. See [`Ruby::define_struct`] for
/// the non-panicking version.
///
/// # Examples
///
/// When providing `None` for the `name` the struct class's name will be taken
/// from the first constant it is assigned to:
///
/// ```
/// use magnus::{define_global_const, prelude::*, r_struct::define_struct};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let struct_class = define_struct(None, ("foo", "bar")).unwrap();
/// define_global_const("Example", struct_class).unwrap();
///
/// assert_eq!(unsafe { struct_class.name().to_owned() }, "Example");
///
/// let instance = struct_class.new_instance((1, 2)).unwrap();
/// assert_eq!(instance.inspect(), "#<struct Example foo=1, bar=2>")
/// ```
///
/// When providing `Some("Name")` for the `name` the struct will be defined
/// under `Struct`:
///
/// ```
/// use magnus::{prelude::*, r_struct::define_struct};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let struct_class = define_struct(Some("Example"), ("foo", "bar")).unwrap();
///
/// assert_eq!(unsafe { struct_class.name().to_owned() }, "Struct::Example");
///
/// let instance = struct_class.new_instance((1, 2)).unwrap();
/// assert_eq!(instance.inspect(), "#<struct Struct::Example foo=1, bar=2>")
/// ```
#[cfg_attr(
    not(feature = "friendly-api"),
    deprecated(note = "please use `Ruby::define_struct` instead")
)]
#[inline]
pub fn define_struct<T>(name: Option<&str>, members: T) -> Result<RClass, Error>
where
    T: StructMembers,
{
    get_ruby!().define_struct(name, members)
}

mod private {
    use super::*;

    pub trait StructMembers {
        fn define(self, name: Option<&str>) -> Result<RClass, Error>;
    }
}
use private::StructMembers;

macro_rules! impl_struct_members {
    ($n:literal) => {
        seq!(N in 0..$n {
            impl StructMembers for (#(&str,)*) {
                fn define(self, name: Option<&str>) -> Result<RClass, Error> {
                    let name = name.map(|n| CString::new(n).unwrap());
                    #(let arg~N = CString::new(self.N).unwrap();)*
                    protect(|| unsafe {
                        RClass::from_rb_value_unchecked(rb_struct_define(
                            name.as_ref().map(|n| n.as_ptr()).unwrap_or_else(null),
                            #(arg~N.as_ptr(),)*
                            null::<c_char>(),
                        ))
                    })
                }
            }
        });
    }
}

seq!(N in 1..=12 {
    impl_struct_members!(N);
});