artichoke_backend/extn/core/string/
ffi.rs

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
#![allow(clippy::cast_possible_wrap)]

use core::char;
use core::convert::TryFrom;
use core::hash::{BuildHasher, Hash, Hasher};
use core::num::Wrapping;
use core::ptr;
use core::slice;
use core::str;
use std::collections::TryReserveError;
use std::ffi::{c_char, c_double, c_int, c_void, CStr};
use std::io::Write as _;
use std::ptr::NonNull;

use artichoke_core::convert::Convert;
use artichoke_core::hash::Hash as _;
use bstr::ByteSlice;
use spinoso_exception::ArgumentError;
use spinoso_exception::NoMemoryError;
use spinoso_string::{RawParts, String};

use super::trampoline;
use crate::convert::BoxUnboxVmValue;
use crate::error;
use crate::sys;
use crate::value::Value;

// ```c
// MRB_API mrb_value mrb_str_new_capa(mrb_state *mrb, size_t capa)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_new_capa(mrb: *mut sys::mrb_state, capa: sys::mrb_int) -> sys::mrb_value {
    let capa = if let Ok(capa) = usize::try_from(capa) {
        capa
    } else {
        return sys::mrb_sys_nil_value();
    };
    unwrap_interpreter!(mrb, to => guard);
    let result = String::with_capacity(capa);
    let result = String::alloc_value(result, &mut guard);
    match result {
        Ok(value) => value.inner(),
        Err(exception) => error::raise(guard, exception),
    }
}

// ```c
// MRB_API mrb_value mrb_str_new(mrb_state *mrb, const char *p, size_t len)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_new(mrb: *mut sys::mrb_state, p: *const c_char, len: sys::mrb_int) -> sys::mrb_value {
    let len = if let Ok(len) = usize::try_from(len) {
        len
    } else {
        return sys::mrb_sys_nil_value();
    };
    unwrap_interpreter!(mrb, to => guard);
    let s = if p.is_null() {
        String::utf8(vec![0; len])
    } else {
        let bytes = slice::from_raw_parts(p.cast::<u8>(), len);
        let bytes = bytes.to_vec();
        String::utf8(bytes)
    };
    let result = String::alloc_value(s, &mut guard);
    match result {
        Ok(value) => value.inner(),
        Err(exception) => error::raise(guard, exception),
    }
}

// ```c
// MRB_API mrb_value mrb_str_new_cstr(mrb_state *mrb, const char *p)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_new_cstr(mrb: *mut sys::mrb_state, p: *const c_char) -> sys::mrb_value {
    unwrap_interpreter!(mrb, to => guard);
    let cstr = CStr::from_ptr(p);
    let bytes = cstr.to_bytes().to_vec();
    let result = String::utf8(bytes);
    let result = String::alloc_value(result, &mut guard);
    match result {
        Ok(value) => value.inner(),
        Err(exception) => error::raise(guard, exception),
    }
}

// ```c
// MRB_API mrb_value mrb_str_new_static(mrb_state *mrb, const char *p, size_t len)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_new_static(
    mrb: *mut sys::mrb_state,
    p: *const c_char,
    len: sys::mrb_int,
) -> sys::mrb_value {
    // Artichoke doesn't have a static string optimization.
    mrb_str_new(mrb, p, len)
}

// ```c
// MRB_API mrb_int mrb_str_index(mrb_state *mrb, mrb_value str, const char *sptr, mrb_int slen, mrb_int offset)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_index(
    mrb: *mut sys::mrb_state,
    s: sys::mrb_value,
    sptr: *const c_char,
    slen: sys::mrb_int,
    offset: sys::mrb_int,
) -> sys::mrb_int {
    unwrap_interpreter!(mrb, to => guard, or_else = -1);
    let mut value = s.into();
    let string = if let Ok(string) = String::unbox_from_value(&mut value, &mut guard) {
        string
    } else {
        return -1;
    };

    /*
    len = RSTRING_LEN(str);
    if (offset < 0) {
      offset += len;
      if (offset < 0) return -1;
    }
    if (len - offset < slen) return -1;
    s = RSTRING_PTR(str);
    if (offset) {
      s += offset;
    }
    if (slen == 0) return offset;
    /* need proceed one character at a time */
    len = RSTRING_LEN(str) - offset;
    */
    let mut offset = isize::try_from(offset).unwrap_or(0);
    let length = isize::try_from(string.len()).unwrap_or(0);
    if offset < 0 {
        offset += length;
    }
    let offset = if let Ok(offset) = usize::try_from(offset) {
        offset
    } else {
        return -1;
    };
    let haystack = if let Some(haystack) = string.get(offset..) {
        haystack
    } else {
        return -1;
    };
    let needle = slice::from_raw_parts(sptr.cast::<u8>(), usize::try_from(slen).unwrap_or(0));
    if needle.is_empty() {
        return offset as sys::mrb_int;
    }
    haystack.find(needle).map_or(-1, |pos| pos as sys::mrb_int)
}

// ```c
// mrb_value mrb_str_aref(mrb_state *mrb, mrb_value str, mrb_value indx, mrb_value alen)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_aref(
    mrb: *mut sys::mrb_state,
    s: sys::mrb_value,
    indx: sys::mrb_value,
    alen: sys::mrb_value,
) -> sys::mrb_value {
    unwrap_interpreter!(mrb, to => guard);
    let value = Value::from(s);
    let indx = Value::from(indx);
    let alen = Value::from(alen);

    let alen = if alen.is_unreachable() { None } else { Some(alen) };

    let result = trampoline::aref(&mut guard, value, indx, alen);
    match result {
        Ok(value) => value.into(),
        Err(_) => Value::nil().into(),
    }
}

// ```c
// MRB_API mrb_int mrb_str_strlen(mrb_state *mrb, struct RString *s)
// ```
//
// NOTE: Implemented in C in `mruby-sys/src/mruby-sys/ext.c`.

// ```c
// MRB_API void mrb_str_modify_keep_ascii(mrb_state *mrb, struct RString *s)
// MRB_API void mrb_str_modify(mrb_state *mrb, struct RString *s)
// ```
//
// NOTE: Implemented in C in `mruby-sys/src/mruby-sys/ext.c`.

// ```c
// MRB_API mrb_value mrb_str_resize(mrb_state *mrb, mrb_value str, mrb_int len)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_resize(mrb: *mut sys::mrb_state, s: sys::mrb_value, len: sys::mrb_int) -> sys::mrb_value {
    fn try_resize(s: &mut String, len: usize) -> Result<(), TryReserveError> {
        match len.checked_sub(s.len()) {
            Some(0) => {}
            Some(additional) => s.try_reserve(additional)?,
            // If the given length is less than the length of the `String`, truncate.
            None => s.truncate(len),
        }
        Ok(())
    }

    unwrap_interpreter!(mrb, to => guard, or_else = s);
    let mut value = s.into();
    let mut string = if let Ok(string) = String::unbox_from_value(&mut value, &mut guard) {
        string
    } else {
        return s;
    };
    let len = if let Ok(len) = usize::try_from(len) {
        len
    } else {
        return s;
    };
    // SAFETY: The string is repacked before any intervening uses of `interp`
    // which means no mruby heap allocations can occur.
    let string_mut = string.as_inner_mut();

    let result = try_resize(string_mut, len);

    let inner = string.take();
    let value = String::box_into_value(inner, value, &mut guard).expect("String reboxing should not fail");

    // `allow` for clarity and to potentially handle `TryReserveErrorKind`.
    #[allow(clippy::single_match_else)]
    match result {
        Ok(()) => value.inner(),
        // NOTE: Ideally this code would distinguish between a capacity overflow
        // (string too large) vs an out of memory condition (allocation failure).
        // This is not possible on stable Rust since `TryReserveErrorKind` is
        // unstable.
        Err(_) => {
            // NOTE: This code can't use an `Error` unified exception trait object.
            // Since we're in memory error territory, we're not sure if we can
            // allocate the `Box` it requires.
            let err = NoMemoryError::with_message("out of memory");
            error::raise(guard, err);
        }
    }
}

// ```c
// MRB_API char* mrb_str_to_cstr(mrb_state *mrb, mrb_value str0)
// ```
//
// NOTE: Not implemented.

// ```c
// MRB_API void mrb_str_concat(mrb_state *mrb, mrb_value self, mrb_value other)
// ```
//
// NOTE: Implemented in C in `mruby-sys/src/mruby-sys/ext.c`.
//
// ```
// #[no_mangle]
// unsafe extern "C" mrb_str_concat(mrb: *mut sys::mrb_state, this: sys::mrb_value, other: sys::mrb_value) {
//     unwrap_interpreter!(mrb, to => guard, or_else = ());
// }
// ```

// ```c
// MRB_API mrb_value mrb_str_plus(mrb_state *mrb, mrb_value a, mrb_value b)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_plus(mrb: *mut sys::mrb_state, a: sys::mrb_value, b: sys::mrb_value) -> sys::mrb_value {
    unwrap_interpreter!(mrb, to => guard);
    let mut a = Value::from(a);
    let mut b = Value::from(b);

    let a = if let Ok(a) = String::unbox_from_value(&mut a, &mut guard) {
        a
    } else {
        return Value::nil().into();
    };
    let b = if let Ok(b) = String::unbox_from_value(&mut b, &mut guard) {
        b
    } else {
        return Value::nil().into();
    };

    let mut s = String::with_capacity_and_encoding(a.len() + b.len(), a.encoding());

    s.extend_from_slice(a.as_slice());
    s.extend_from_slice(b.as_slice());

    let s = String::alloc_value(s, &mut guard).unwrap_or_default();
    s.into()
}

// ```c
// MRB_API int mrb_str_cmp(mrb_state *mrb, mrb_value str1, mrb_value str2)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_cmp(mrb: *mut sys::mrb_state, str1: sys::mrb_value, str2: sys::mrb_value) -> c_int {
    unwrap_interpreter!(mrb, to => guard, or_else = -1);
    let mut a = Value::from(str1);
    let mut b = Value::from(str2);

    let a = if let Ok(a) = String::unbox_from_value(&mut a, &mut guard) {
        a
    } else {
        return -1;
    };
    let b = if let Ok(b) = String::unbox_from_value(&mut b, &mut guard) {
        b
    } else {
        return -1;
    };

    a.cmp(&*b) as c_int
}

// ```c
// MRB_API mrb_bool mrb_str_equal(mrb_state *mrb, mrb_value str1, mrb_value str2)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_equal(
    mrb: *mut sys::mrb_state,
    str1: sys::mrb_value,
    str2: sys::mrb_value,
) -> sys::mrb_bool {
    unwrap_interpreter!(mrb, to => guard, or_else = false);
    let mut a = Value::from(str1);
    let mut b = Value::from(str2);

    let a = if let Ok(a) = String::unbox_from_value(&mut a, &mut guard) {
        a
    } else {
        return false;
    };
    let b = if let Ok(b) = String::unbox_from_value(&mut b, &mut guard) {
        b
    } else {
        return false;
    };

    *a == *b
}

// ```c
// MRB_API const char* mrb_string_value_ptr(mrb_state *mrb, mrb_value str)
// ```
//
// obsolete: use `RSTRING_PTR()`
//
// NOTE: not implemented

// ```c
// MRB_API mrb_int mrb_string_value_len(mrb_state *mrb, mrb_value ptr)
// ```
//
// obsolete: use `RSTRING_LEN()`
//
// NOTE: not implemented

// ```c
// MRB_API mrb_value mrb_str_dup(mrb_state *mrb, mrb_value str)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_dup(mrb: *mut sys::mrb_state, s: sys::mrb_value) -> sys::mrb_value {
    unwrap_interpreter!(mrb, to => guard);
    let mut string = Value::from(s);
    let basic = sys::mrb_sys_basic_ptr(s).cast::<sys::RString>();
    let class = (*basic).c;

    if let Ok(string) = String::unbox_from_value(&mut string, &mut guard) {
        let dup = string.clone();
        if let Ok(value) = String::alloc_value(dup, &mut guard) {
            let value = value.inner();

            // dup'd strings keep the class of the source `String`.
            let dup_basic = sys::mrb_sys_basic_ptr(value).cast::<sys::RString>();
            (*dup_basic).c = class;

            return value;
        }
    }
    Value::nil().into()
}

// ```c
// MRB_API mrb_value mrb_str_substr(mrb_state *mrb, mrb_value str, mrb_int beg, mrb_int len)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_substr(
    mrb: *mut sys::mrb_state,
    s: sys::mrb_value,
    beg: sys::mrb_int,
    len: sys::mrb_int,
) -> sys::mrb_value {
    if len < 0 {
        return Value::nil().into();
    }
    unwrap_interpreter!(mrb, to => guard);

    let mut string = Value::from(s);
    let string = if let Ok(string) = String::unbox_from_value(&mut string, &mut guard) {
        string
    } else {
        return Value::nil().into();
    };

    let offset = if let Ok(offset) = usize::try_from(beg) {
        offset
    } else {
        let offset = beg
            .checked_neg()
            .and_then(|offset| usize::try_from(offset).ok())
            .and_then(|offset| offset.checked_sub(string.len()));
        if let Some(offset) = offset {
            offset
        } else {
            return Value::nil().into();
        }
    };

    // FIXME: mruby treats this as a character offset, not a byte offset.
    if let Some(slice) = string.get(offset..) {
        let substr = String::with_bytes_and_encoding(slice.to_vec(), string.encoding());
        String::alloc_value(substr, &mut guard).unwrap_or_default().into()
    } else {
        Value::nil().into()
    }
}

// ```c
// MRB_API mrb_value mrb_ptr_to_str(mrb_state *mrb, void *p)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_ptr_to_str(mrb: *mut sys::mrb_state, p: *mut c_void) -> sys::mrb_value {
    unwrap_interpreter!(mrb, to => guard);
    let mut s = String::with_capacity(16 + 2);
    let _ignore = write!(s, "{p:p}");
    String::alloc_value(s, &mut guard).unwrap_or_default().into()
}

// ```c
// MRB_API mrb_value mrb_cstr_to_inum(mrb_state *mrb, const char *str, mrb_int base, mrb_bool badcheck)
// ```
//
// NOTE: not implemented.

// ```c
// MRB_API const char* mrb_string_value_cstr(mrb_state *mrb, mrb_value *ptr)
// ```
//
// obsolete: use `RSTRING_CSTR()` or `mrb_string_cstr()`
#[no_mangle]
unsafe extern "C" fn mrb_string_value_cstr(mrb: *mut sys::mrb_state, ptr: *mut sys::mrb_value) -> *const c_char {
    unwrap_interpreter!(mrb, to => guard, or_else = ptr::null());
    let mut s = Value::from(*ptr);
    let mut string = if let Ok(string) = String::unbox_from_value(&mut s, &mut guard) {
        if let Some(b'\0') = string.last() {
            return string.as_ptr().cast();
        }
        string
    } else {
        return ptr::null();
    };
    // SAFETY: The string is repacked before any intervening uses of `interp`
    // which means no mruby heap allocations can occur.
    let string_mut = string.as_inner_mut();
    string_mut.push_byte(b'\0');
    // SAFETY: This raw pointer will not be invalidated since we rebox this
    // `String` into the mruby heap where the GC will keep it alive.
    let cstr = string.as_ptr().cast::<c_char>();

    let inner = string.take();
    String::box_into_value(inner, s, &mut guard).expect("String reboxing should not fail");

    cstr
}

// ```c
// MRB_API const char* mrb_string_cstr(mrb_state *mrb, mrb_value str)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_string_cstr(mrb: *mut sys::mrb_state, s: sys::mrb_value) -> *const c_char {
    unwrap_interpreter!(mrb, to => guard, or_else = ptr::null());
    let mut s = Value::from(s);
    let mut string = if let Ok(string) = String::unbox_from_value(&mut s, &mut guard) {
        if let Some(b'\0') = string.last() {
            return string.as_ptr().cast();
        }
        string
    } else {
        return ptr::null();
    };
    // SAFETY: The string is repacked before any intervening uses of `interp`
    // which means no mruby heap allocations can occur.
    let string_mut = string.as_inner_mut();
    string_mut.push_byte(b'\0');
    // SAFETY: This raw pointer will not be invalidated since we rebox this
    // `String` into the mruby heap where the GC will keep it alive.
    let cstr = string.as_ptr().cast::<c_char>();

    let inner = string.take();
    String::box_into_value(inner, s, &mut guard).expect("String reboxing should not fail");

    cstr
}

// ```c
// MRB_API mrb_value mrb_str_to_integer(mrb_state *mrb, mrb_value str, mrb_int base, mrb_bool badcheck);
// /* obsolete: use mrb_str_to_integer() */
// #define mrb_str_to_inum(mrb, str, base, badcheck) mrb_str_to_integer(mrb, str, base, badcheck)
// ```
//
// This function converts a numeric string to numeric `mrb_value` with the given base.
#[no_mangle]
unsafe extern "C" fn mrb_str_to_integer(
    mrb: *mut sys::mrb_state,
    s: sys::mrb_value,
    base: sys::mrb_int,
    badcheck: sys::mrb_bool,
) -> sys::mrb_value {
    unwrap_interpreter!(mrb, to => guard);
    let mut s = Value::from(s);
    let s = if let Ok(s) = String::unbox_from_value(&mut s, &mut guard) {
        s
    } else if badcheck {
        let err = ArgumentError::with_message("not a string");
        error::raise(guard, err);
    } else {
        return guard.convert(0_i64).into();
    };
    let num = if let Ok(s) = str::from_utf8(s.as_slice()) {
        if let Ok(num) = s.parse::<i64>() {
            num
        } else if badcheck {
            let err = ArgumentError::with_message("invalid number");
            error::raise(guard, err);
        } else {
            return guard.convert(0_i64).into();
        }
    } else if badcheck {
        let err = ArgumentError::with_message("invalid number");
        error::raise(guard, err);
    } else {
        return guard.convert(0_i64).into();
    };
    let radix = match u32::try_from(base) {
        Ok(base) if (2..=36).contains(&base) => base,
        Ok(_) | Err(_) => {
            let err = ArgumentError::with_message("illegal radix");
            error::raise(guard, err);
        }
    };
    let mut result = vec![];
    let mut x = num;

    loop {
        let m = u32::try_from(x % base).expect("base must be <= 36, which guarantees the result is in range for u32");
        x /= base;

        // will panic if you use a bad radix (< 2 or > 36).
        result.push(char::from_digit(m, radix).unwrap());
        if x == 0 {
            break;
        }
    }
    let int = result.into_iter().rev().collect::<String>();
    String::alloc_value(int, &mut guard).unwrap_or_default().into()
}

// ```c
// MRB_API double mrb_cstr_to_dbl(mrb_state *mrb, const char *s, mrb_bool badcheck)
// ```
//
// NOTE: not implemented

// ```c
// MRB_API double mrb_str_to_dbl(mrb_state *mrb, mrb_value str, mrb_bool badcheck)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_to_dbl(mrb: *mut sys::mrb_state, s: sys::mrb_value, badcheck: sys::mrb_bool) -> c_double {
    unwrap_interpreter!(mrb, to => guard, or_else = 0.0);
    let mut s = Value::from(s);
    let s = if let Ok(s) = String::unbox_from_value(&mut s, &mut guard) {
        s
    } else if badcheck {
        let err = ArgumentError::with_message("not a string");
        error::raise(guard, err);
    } else {
        return 0.0;
    };
    if let Ok(s) = str::from_utf8(s.as_slice()) {
        if let Ok(num) = s.parse::<c_double>() {
            num
        } else if badcheck {
            let err = ArgumentError::with_message("invalid number");
            error::raise(guard, err);
        } else {
            0.0
        }
    } else if badcheck {
        let err = ArgumentError::with_message("invalid number");
        error::raise(guard, err);
    } else {
        0.0
    }
}

// ```c
// MRB_API mrb_value mrb_str_cat(mrb_state *mrb, mrb_value str, const char *ptr, size_t len)
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_cat(
    mrb: *mut sys::mrb_state,
    s: sys::mrb_value,
    ptr: *const c_char,
    len: usize,
) -> sys::mrb_value {
    unwrap_interpreter!(mrb, to => guard, or_else = s);
    let mut s = Value::from(s);
    if let Ok(mut string) = String::unbox_from_value(&mut s, &mut guard) {
        let slice = slice::from_raw_parts(ptr.cast::<u8>(), len);

        // SAFETY: The string is repacked before any intervening uses of
        // `interp` which means no mruby heap allocations can occur.
        let string_mut = string.as_inner_mut();
        string_mut.extend_from_slice(slice);
        let inner = string.take();
        let value = String::box_into_value(inner, s, &mut guard).expect("String reboxing should not fail");

        value.inner()
    } else {
        s.inner()
    }
}

// ```c
// MRB_API mrb_value mrb_str_cat_cstr(mrb_state *mrb, mrb_value str, const char *ptr)
// MRB_API mrb_value mrb_str_cat_str(mrb_state *mrb, mrb_value str, mrb_value str2)
// MRB_API mrb_value mrb_str_append(mrb_state *mrb, mrb_value str1, mrb_value str2)
// ```
//
// NOTE: Implemented in C in `mruby-sys/src/mruby-sys/ext.c`.

// ```c
// MRB_API double mrb_float_read(const char *string, char **endPtr)
// ```
//
// NOTE: impl kept in C.

// ```c
// uint32_t mrb_str_hash(mrb_state *mrb, mrb_value str);
// ```
#[no_mangle]
unsafe extern "C" fn mrb_str_hash(mrb: *mut sys::mrb_state, s: sys::mrb_value) -> u32 {
    unwrap_interpreter!(mrb, to => guard, or_else = 0);
    let mut s = Value::from(s);
    let mut hasher = if let Ok(global_build_hasher) = guard.global_build_hasher() {
        global_build_hasher.build_hasher()
    } else {
        return 0;
    };

    let s = if let Ok(s) = String::unbox_from_value(&mut s, &mut guard) {
        s
    } else {
        return 0;
    };
    s.as_slice().hash(&mut hasher);
    #[allow(clippy::cast_possible_truncation)]
    let hash = hasher.finish() as u32;
    hash
}

// ```c
// #define FNV_32_PRIME ((uint32_t)0x01000193)
// #define FNV1_32_INIT ((uint32_t)0x811c9dc5)
//
// uint32_t mrb_byte_hash(const uint8_t*, mrb_int);
// uint32_t mrb_byte_hash_step(const uint8_t*, mrb_int, uint32_t);
// ```

const FNV_32_PRIME: Wrapping<u32> = Wrapping(0x0100_0193);
const FNV1_32_INIT: Wrapping<u32> = Wrapping(0x811c_9dc5);

#[no_mangle]
unsafe extern "C" fn mrb_byte_hash(s: *const u8, len: sys::mrb_int) -> u32 {
    mrb_byte_hash_step(s, len, FNV1_32_INIT)
}

#[no_mangle]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
unsafe extern "C" fn mrb_byte_hash_step(s: *const u8, len: sys::mrb_int, mut hval: Wrapping<u32>) -> u32 {
    let slice = slice::from_raw_parts(s, len as usize);
    // FNV-1 hash each octet in the buffer
    for &byte in slice {
        // multiply by the 32 bit FNV magic prime mod 2^32
        hval *= FNV_32_PRIME;
        // xor the bottom with the current octet
        hval ^= u32::from(byte);
    }
    // return our new hash value
    hval.0
}

#[no_mangle]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
unsafe extern "C" fn mrb_gc_free_str(mrb: *mut sys::mrb_state, string: *mut sys::RString) {
    let _ = mrb;

    let Some(ptr) = NonNull::<c_char>::new((*string).as_.heap.ptr) else {
        // An allocated but uninitialized string has no backing byte buffer, so
        // there is nothing to free.
        return;
    };
    let length = (*string).as_.heap.len as usize;
    let capacity = (*string).as_.heap.aux.capa as usize;

    // we don't need to free the encoding since `Encoding` is `Copy` and we pack
    // it into the `RString` flags as a `u32`.

    let raw_parts = RawParts {
        ptr: ptr.cast::<u8>().as_mut(),
        length,
        capacity,
    };
    drop(String::from_raw_parts(raw_parts));
}