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
use std::ffi::c_void;
use std::fmt::Write as _;
use std::ops::Deref;

use crate::convert::{implicitly_convert_to_int, implicitly_convert_to_string, UnboxedValueGuard};
use crate::extn::prelude::*;
use crate::fmt::WriteError;

pub mod args;
mod ffi;
pub(in crate::extn) mod mruby;
pub(super) mod trampoline;
mod wrapper;

#[doc(inline)]
pub use wrapper::{Array, RawParts};

pub fn initialize(
    interp: &mut Artichoke,
    first: Option<Value>,
    second: Option<Value>,
    block: Option<Block>,
) -> Result<Array, Error> {
    let ary = match (first, second, block) {
        (Some(mut array_or_len), default, None) => {
            if let Ok(len) = array_or_len.try_convert_into::<i64>(interp) {
                let len = usize::try_from(len).map_err(|_| ArgumentError::with_message("negative array size"))?;
                let default = default.unwrap_or_else(Value::nil);
                Array::with_len_and_default(len, default)
            } else {
                let unboxed = unsafe { Array::unbox_from_value(&mut array_or_len, interp) };
                if let Ok(ary) = unboxed {
                    ary.clone()
                } else if array_or_len.respond_to(interp, "to_ary")? {
                    let mut other = array_or_len.funcall(interp, "to_ary", &[], None)?;
                    let unboxed = unsafe { Array::unbox_from_value(&mut other, interp) };
                    if let Ok(other) = unboxed {
                        other.clone()
                    } else {
                        let mut message = String::from("can't convert ");
                        let name = interp.inspect_type_name_for_value(array_or_len);
                        message.push_str(name);
                        message.push_str(" to Array (");
                        message.push_str(name);
                        message.push_str("#to_ary gives ");
                        message.push_str(interp.inspect_type_name_for_value(other));
                        return Err(TypeError::from(message).into());
                    }
                } else {
                    let len = implicitly_convert_to_int(interp, array_or_len)?;
                    let len = usize::try_from(len).map_err(|_| ArgumentError::with_message("negative array size"))?;
                    let default = default.unwrap_or_else(Value::nil);
                    Array::with_len_and_default(len, default)
                }
            }
        }
        (Some(mut array_or_len), default, Some(block)) => {
            if let Ok(len) = array_or_len.try_convert_into::<i64>(interp) {
                let len = usize::try_from(len).map_err(|_| ArgumentError::with_message("negative array size"))?;
                if default.is_some() {
                    interp.warn(b"warning: block supersedes default value argument")?;
                }
                let mut buffer = Array::with_capacity(len);
                for idx in 0..len {
                    let idx = i64::try_from(idx)
                        .map_err(|_| RangeError::with_message("bignum too big to convert into `long'"))?;
                    let idx = interp.convert(idx);
                    let elem = block.yield_arg(interp, &idx)?;
                    buffer.push(elem);
                }
                buffer
            } else {
                let unboxed = unsafe { Array::unbox_from_value(&mut array_or_len, interp) };
                if let Ok(ary) = unboxed {
                    ary.clone()
                } else if array_or_len.respond_to(interp, "to_ary")? {
                    let mut other = array_or_len.funcall(interp, "to_ary", &[], None)?;
                    let unboxed = unsafe { Array::unbox_from_value(&mut other, interp) };
                    if let Ok(other) = unboxed {
                        other.clone()
                    } else {
                        let mut message = String::from("can't convert ");
                        let name = interp.inspect_type_name_for_value(array_or_len);
                        message.push_str(name);
                        message.push_str(" to Array (");
                        message.push_str(name);
                        message.push_str("#to_ary gives ");
                        message.push_str(interp.inspect_type_name_for_value(other));
                        return Err(TypeError::from(message).into());
                    }
                } else {
                    let len = implicitly_convert_to_int(interp, array_or_len)?;
                    let len = usize::try_from(len).map_err(|_| ArgumentError::with_message("negative array size"))?;
                    if default.is_some() {
                        interp.warn(b"warning: block supersedes default value argument")?;
                    }
                    let mut buffer = Array::with_capacity(len);
                    for idx in 0..len {
                        let idx = i64::try_from(idx)
                            .map_err(|_| RangeError::with_message("bignum too big to convert into `long'"))?;
                        let idx = interp.convert(idx);
                        let elem = block.yield_arg(interp, &idx)?;
                        buffer.push(elem);
                    }
                    buffer
                }
            }
        }
        (None, None, _) => Array::new(),
        (None, Some(_), _) => {
            let err_msg = "default cannot be set if first arg is missing in Array#initialize";
            return Err(Fatal::from(err_msg).into());
        }
    };
    Ok(ary)
}

pub fn repeat(ary: &Array, n: usize) -> Result<Array, ArgumentError> {
    ary.repeat(n)
        .ok_or_else(|| ArgumentError::with_message("argument too big"))
}

pub fn join(interp: &mut Artichoke, ary: &Array, sep: &[u8]) -> Result<Vec<u8>, Error> {
    fn flatten(interp: &mut Artichoke, mut value: Value, out: &mut Vec<Vec<u8>>) -> Result<(), Error> {
        match value.ruby_type() {
            Ruby::Array => {
                let ary = unsafe { Array::unbox_from_value(&mut value, interp)? };
                out.reserve(ary.len());
                for elem in &*ary {
                    flatten(interp, elem, out)?;
                }
            }
            Ruby::Fixnum => {
                let mut buf = String::new();
                let int = unsafe { sys::mrb_sys_fixnum_to_cint(value.inner()) };
                write!(&mut buf, "{int}").map_err(WriteError::from)?;
                out.push(buf.into_bytes());
            }
            Ruby::Float => {
                let float = unsafe { sys::mrb_sys_float_to_cdouble(value.inner()) };
                let mut buf = String::new();
                write!(&mut buf, "{float}").map_err(WriteError::from)?;
                out.push(buf.into_bytes());
            }
            _ => {
                // SAFETY: `s` is converted to an owned byte `Vec` immediately
                // before any intervening operations on the VM. This ensures
                // there are no intervening garbage collections which may free
                // the `RString*` that backs this value.
                if let Ok(s) = unsafe { implicitly_convert_to_string(interp, &mut value) } {
                    out.push(s.to_vec());
                } else {
                    out.push(value.to_s(interp));
                }
            }
        }
        Ok(())
    }

    let mut vec = Vec::with_capacity(ary.len());
    for elem in ary {
        flatten(interp, elem, &mut vec)?;
    }

    Ok(bstr::join(sep, vec))
}

fn aref(interp: &mut Artichoke, ary: &Array, index: Value, len: Option<Value>) -> Result<Option<Value>, Error> {
    let (index, len) = match args::element_reference(interp, index, len, ary.len())? {
        args::ElementReference::Empty => return Ok(None),
        args::ElementReference::Index(index) => (index, None),
        args::ElementReference::StartLen(index, len) => (index, Some(len)),
    };
    let start = if let Some(start) = aref::offset_to_index(index, ary.len()) {
        start
    } else {
        return Ok(None);
    };
    if start > ary.len() {
        return Ok(None);
    }
    if let Some(len) = len {
        let result = ary.slice(start, len);
        let result = Array::alloc_value(result.into(), interp)?;
        Ok(Some(result))
    } else {
        Ok(ary.get(start))
    }
}

fn aset(
    interp: &mut Artichoke,
    ary: &mut Array,
    first: Value,
    second: Value,
    third: Option<Value>,
) -> Result<Value, Error> {
    let (start, drain, mut elem) = args::element_assignment(interp, first, second, third, ary.len())?;

    if let Some(drain) = drain {
        if let Ok(other) = unsafe { Array::unbox_from_value(&mut elem, interp) } {
            ary.set_slice(start, drain, other.as_slice());
        } else if elem.respond_to(interp, "to_ary")? {
            let mut other = elem.funcall(interp, "to_ary", &[], None)?;
            if let Ok(other) = unsafe { Array::unbox_from_value(&mut other, interp) } {
                ary.set_slice(start, drain, other.as_slice());
            } else {
                let mut message = String::from("can't convert ");
                let name = interp.inspect_type_name_for_value(elem);
                message.push_str(name);
                message.push_str(" to Array (");
                message.push_str(name);
                message.push_str("#to_ary gives ");
                message.push_str(interp.inspect_type_name_for_value(other));
                return Err(TypeError::from(message).into());
            }
        } else {
            ary.set_with_drain(start, drain, elem);
        }
    } else {
        ary.set(start, elem);
    }

    Ok(elem)
}

impl BoxUnboxVmValue for Array {
    type Unboxed = Self;
    type Guarded = Array;

    const RUBY_TYPE: &'static str = "Array";

    #[allow(clippy::cast_possible_truncation)]
    #[allow(clippy::cast_sign_loss)]
    unsafe fn unbox_from_value<'a>(
        value: &'a mut Value,
        interp: &mut Artichoke,
    ) -> Result<UnboxedValueGuard<'a, Self::Guarded>, Error> {
        let _ = interp;

        // Make sure we have an Array otherwise extraction will fail.
        if value.ruby_type() != Ruby::Array {
            let mut message = String::from("uninitialized ");
            message.push_str(Self::RUBY_TYPE);
            return Err(TypeError::from(message).into());
        }

        let value = value.inner();
        // SAFETY: The above check on the data type ensures the `value` union
        // holds an `RArray*` in the `p` variant.
        let ary = sys::mrb_sys_basic_ptr(value).cast::<sys::RArray>();

        let ptr = (*ary).as_.heap.ptr;
        let length = (*ary).as_.heap.len as usize;
        let capacity = (*ary).as_.heap.aux.capa as usize;
        let array = Array::from_raw_parts(RawParts { ptr, length, capacity });

        Ok(UnboxedValueGuard::new(array))
    }

    fn alloc_value(value: Self::Unboxed, interp: &mut Artichoke) -> Result<Value, Error> {
        let RawParts { ptr, length, capacity } = Array::into_raw_parts(value);
        let value = unsafe {
            interp.with_ffi_boundary(|mrb| {
                // SAFETY: `Array` is backed by a `Vec` which can allocate at
                // most `isize::MAX` bytes.
                //
                // `mrb_value` is not a ZST, so in practice, `len` and
                // `capacity` will never overflow `mrb_int`, which is an `i64`
                // on 64-bit targets.
                //
                // On 32-bit targets, `usize` is `u32` which will never overflow
                // `i64`. Artichoke unconditionally compiles mruby with `-DMRB_INT64`.
                let length = sys::mrb_int::try_from(length)
                    .expect("Length of an `Array` cannot exceed isize::MAX == i64::MAX == mrb_int::MAX");
                let capa = sys::mrb_int::try_from(capacity)
                    .expect("Capacity of an `Array` cannot exceed isize::MAX == i64::MAX == mrb_int::MAX");
                sys::mrb_sys_alloc_rarray(mrb, ptr, length, capa)
            })?
        };
        Ok(interp.protect(value.into()))
    }

    #[allow(clippy::cast_possible_wrap)]
    fn box_into_value(value: Self::Unboxed, into: Value, interp: &mut Artichoke) -> Result<Value, Error> {
        // Make sure we have an Array otherwise boxing will produce undefined
        // behavior. This check is critical to protecting the garbage collector
        // against use-after-free.
        assert_eq!(
            into.ruby_type(),
            Ruby::Array,
            "Tried to box Array into {:?} value",
            into.ruby_type()
        );

        let RawParts { ptr, length, capacity } = Array::into_raw_parts(value);
        unsafe {
            sys::mrb_sys_repack_into_rarray(ptr, length as sys::mrb_int, capacity as sys::mrb_int, into.inner());
        }

        Ok(interp.protect(into))
    }

    fn free(data: *mut c_void) {
        // This function is never called. `Array` is freed directly in the VM by
        // calling `mrb_ary_artichoke_free`.
        //
        // Array should not have a destructor registered in the class registry.
        let _ = data;
    }
}

impl<'a> Deref for UnboxedValueGuard<'a, Array> {
    type Target = Array;

    fn deref(&self) -> &Self::Target {
        self.as_inner_ref()
    }
}

#[cfg(test)]
mod tests {
    use crate::test::prelude::*;

    const SUBJECT: &str = "Array";
    const FUNCTIONAL_TEST: &[u8] = include_bytes!("array_functional_test.rb");

    #[test]
    fn functional() {
        let mut interp = interpreter();
        let result = interp.eval(FUNCTIONAL_TEST);
        unwrap_or_panic_with_backtrace(&mut interp, SUBJECT, result);
        let result = interp.eval(b"spec");
        unwrap_or_panic_with_backtrace(&mut interp, SUBJECT, result);
    }
}