logo
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
use core::convert::TryFrom;
use core::fmt::Write as _;
use core::hash::{BuildHasher, Hash, Hasher};
use core::str;

use artichoke_core::hash::Hash as _;
use artichoke_core::value::Value as _;
use bstr::ByteSlice;

use crate::convert::implicitly_convert_to_int;
use crate::convert::implicitly_convert_to_nilable_string;
use crate::convert::implicitly_convert_to_string;
use crate::extn::core::array::Array;
#[cfg(feature = "core-regexp")]
use crate::extn::core::matchdata::{self, MatchData};
#[cfg(feature = "core-regexp")]
use crate::extn::core::regexp::{self, Regexp};
use crate::extn::core::symbol::Symbol;
use crate::extn::prelude::*;
use crate::sys::protect;

pub fn mul(interp: &mut Artichoke, mut value: Value, count: Value) -> Result<Value, Error> {
    let count = implicitly_convert_to_int(interp, count)?;
    let count = usize::try_from(count).map_err(|_| ArgumentError::with_message("negative argument"))?;

    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    // This guard ensures `repeat` below does not panic on `usize` overflow.
    if count.checked_mul(s.len()).is_none() {
        return Err(RangeError::with_message("bignum too big to convert into `long'").into());
    }
    let repeated_s = s.as_slice().repeat(count).into();
    super::String::alloc_value(repeated_s, interp)
}

pub fn add(interp: &mut Artichoke, mut value: Value, mut other: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    // Safety:
    //
    // The borrowed byte slice is immediately memcpy'd into the `s` byte
    // buffer. There are no intervening interpreter accesses.
    let to_append = unsafe { implicitly_convert_to_string(interp, &mut other)? };

    let mut concatenated = s.clone();
    // XXX: This call doesn't do a check to see if we'll exceed the max allocation
    //    size and may panic.
    concatenated.extend_from_slice(to_append);
    super::String::alloc_value(concatenated, interp)
}

pub fn push(interp: &mut Artichoke, mut value: Value, mut other: Value) -> Result<Value, Error> {
    let mut s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    // Safety:
    //
    // The byte slice is immediately used and discarded after extraction. There
    // are no intervening interpreter accesses.
    let other = unsafe { implicitly_convert_to_string(interp, &mut other)? };
    // Safety:
    //
    // The string is reboxed before any intervening operations on the
    // interpreter.
    // The string is reboxed without any intervening mruby allocations.
    unsafe {
        let string_mut = s.as_inner_mut();
        // XXX: This call doesn't do a check to see if we'll exceed the max allocation
        //    size and may panic.
        string_mut.extend_from_slice(other);

        let s = s.take();
        super::String::box_into_value(s, value, interp)
    }
}

pub fn cmp_rocket(interp: &mut Artichoke, mut value: Value, mut other: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    if let Ok(other) = unsafe { super::String::unbox_from_value(&mut other, interp) } {
        let cmp = s.cmp(&*other);
        Ok(interp.convert(cmp as i64))
    } else {
        Ok(Value::nil())
    }
}

pub fn equals_equals(interp: &mut Artichoke, mut value: Value, mut other: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    if let Ok(other) = unsafe { super::String::unbox_from_value(&mut other, interp) } {
        let equals = *s == *other;
        return Ok(interp.convert(equals));
    }
    // Safety:
    //
    // The byte slice is immediately discarded after extraction. There are no
    // intervening interpreter accesses.
    if value.respond_to(interp, "to_str")? {
        let result = other.funcall(interp, "==", &[value], None)?;
        // any falsy returned value yields `false`, otherwise `true`.
        if let Ok(result) = TryConvert::<_, Option<bool>>::try_convert(interp, result) {
            let result = result.unwrap_or_default();
            Ok(interp.convert(result))
        } else {
            Ok(interp.convert(true))
        }
    } else {
        Ok(interp.convert(false))
    }
}

#[allow(unused_mut)]
pub fn aref(
    interp: &mut Artichoke,
    mut value: Value,
    mut first: Value,
    second: Option<Value>,
) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    if let Some(second) = second {
        #[cfg(feature = "core-regexp")]
        if let Ok(regexp) = unsafe { Regexp::unbox_from_value(&mut first, interp) } {
            let match_data = regexp.match_(interp, Some(s.as_slice()), None, None)?;
            if match_data.is_nil() {
                return Ok(Value::nil());
            }
            return matchdata::trampoline::element_reference(interp, match_data, second, None);
        }
        let index = implicitly_convert_to_int(interp, first)?;
        let length = implicitly_convert_to_int(interp, second)?;

        // ```
        // [3.0.1] > s = "abc"
        // => "abc"
        // [3.0.1] > s[-2, 10]
        // => "bc"
        // [3.0.1] > s[-3, 10]
        // => "abc"
        // [3.0.1] > s[-4, 10]
        // => nil
        // ```
        let index = if let Ok(index) = usize::try_from(index) {
            Some(index)
        } else {
            index
                .checked_neg()
                .and_then(|index| usize::try_from(index).ok())
                .and_then(|index| s.len().checked_sub(index))
        };
        let index = match index {
            None => return Ok(Value::nil()),
            // Short circuit with `nil` if `index > len`.
            //
            // ```
            // [3.0.1] > s = "abc"
            // => "abc"
            // [3.0.1] > s[3, 10]
            // => ""
            // [3.0.1] > s[4, 10]
            // => nil
            // ```
            //
            // Don't specialize on the case where `index == len` because the provided
            // length can change the result. Even if the length argument is not
            // given, we still need to preserve the encoding of the source string,
            // so fall through to the happy path below.
            Some(index) if index > s.len() => return Ok(Value::nil()),
            Some(index) => index,
        };

        // ```
        // [3.0.1] > s = "abc"
        // => "abc"
        // [3.0.1] > s[1, -1]
        // => nil
        // ```
        if let Ok(length) = usize::try_from(length) {
            // ```
            // [3.0.1] > s = "abc"
            // => "abc"
            // [3.0.1] > s[2**64, 2**64]
            // (irb):26:in `[]': bignum too big to convert into `long' (RangeError)
            // 	from (irb):26:in `<main>'
            // 	from /usr/local/var/rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/irb-1.3.5/exe/irb:11:in `<top (required)>'
            // 	from /usr/local/var/rbenv/versions/3.0.1/bin/irb:23:in `load'
            // 	from /usr/local/var/rbenv/versions/3.0.1/bin/irb:23:in `<main>'
            // ```
            let end = index
                .checked_add(length)
                .ok_or_else(|| RangeError::with_message("bignum too big to convert into `long'"))?;
            if let Some(slice) = s.get_char_slice(index..end) {
                // Encoding from the source string is preserved.
                //
                // ```
                // [3.0.1] > s = "abc"
                // => "abc"
                // [3.0.1] > s.encoding
                // => #<Encoding:UTF-8>
                // [3.0.1] > s[1, 2].encoding
                // => #<Encoding:UTF-8>
                // [3.0.1] > t = s.force_encoding(Encoding::ASCII)
                // => "abc"
                // [3.0.1] > t[1, 2].encoding
                // => #<Encoding:US-ASCII>
                // ```
                let s = super::String::with_bytes_and_encoding(slice.to_vec(), s.encoding());
                // ```
                // [3.0.1] > class S < String; end
                // => nil
                // [3.0.1] > S.new("abc")[1, 2].class
                // => String
                // ```
                //
                // The returned `String` is never frozen:
                //
                // ```
                // [3.0.1] > s = "abc"
                // => "abc"
                // [3.0.1] > s.frozen?
                // => false
                // [3.0.1] > s[1, 2].frozen?
                // => false
                // [3.0.1] > t = "abc".freeze
                // => "abc"
                // [3.0.1] > t[1, 2].frozen?
                // => false
                // ```
                return super::String::alloc_value(s, interp);
            }
        }
        return Ok(Value::nil());
    }
    #[cfg(feature = "core-regexp")]
    if let Ok(regexp) = unsafe { Regexp::unbox_from_value(&mut first, interp) } {
        let match_data = regexp.match_(interp, Some(s.as_slice()), None, None)?;
        if match_data.is_nil() {
            return Ok(Value::nil());
        }
        return matchdata::trampoline::element_reference(interp, match_data, interp.convert(0), None);
    }
    if let Some(protect::Range { start: index, len }) = first.is_range(interp, s.char_len() as i64)? {
        let index = if let Ok(index) = usize::try_from(index) {
            Some(index)
        } else {
            index
                .checked_neg()
                .and_then(|index| usize::try_from(index).ok())
                .and_then(|index| s.len().checked_sub(index))
        };
        let index = match index {
            None => return Ok(Value::nil()),
            Some(index) if index > s.len() => return Ok(Value::nil()),
            Some(index) => index,
        };
        if let Ok(length) = usize::try_from(len) {
            let end = index
                .checked_add(length)
                .ok_or_else(|| RangeError::with_message("bignum too big to convert into `long'"))?;
            if let Some(slice) = s.get_char_slice(index..end) {
                let s = super::String::with_bytes_and_encoding(slice.to_vec(), s.encoding());
                return super::String::alloc_value(s, interp);
            }
        }
        return Ok(Value::nil());
    }
    // The overload of `String#[]` that takes a `String` **only** takes `String`s.
    // No implicit conversion is performed.
    //
    // ```
    // [3.0.1] > s = "abc"
    // => "abc"
    // [3.0.1] > s["bc"]
    // => "bc"
    // [3.0.1] > class X; def to_str; "bc"; end; end
    // => :to_str
    // [3.0.1] > s[X.new]
    // (irb):4:in `[]': no implicit conversion of X into Integer (TypeError)
    // 	from (irb):4:in `<main>'
    // 	from /usr/local/var/rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/irb-1.3.5/exe/irb:11:in `<top (required)>'
    // 	from /usr/local/var/rbenv/versions/3.0.1/bin/irb:23:in `load'
    // 	from /usr/local/var/rbenv/versions/3.0.1/bin/irb:23:in `<main>'
    // 	```
    if let Ok(substring) = unsafe { super::String::unbox_from_value(&mut first, interp) } {
        if s.index(&*substring, None).is_some() {
            // Indexing with a `String` returns a newly allocated object that
            // has the same encoding as the index, regardless of the encoding on
            // the receiver.
            //
            // ```
            // [3.0.2] > s = "abc"
            // => "abc"
            // [3.0.2] > s.encoding
            // => #<Encoding:UTF-8>
            // [3.0.2] > s["bc"].encoding
            // => #<Encoding:UTF-8>
            // [3.0.2] > t = s.force_encoding(Encoding::ASCII_8BIT)
            // => "abc"
            // [3.0.2] > t.encoding
            // => #<Encoding:ASCII-8BIT>
            // [3.0.2] > t["bc"].encoding
            // => #<Encoding:UTF-8>
            // [3.0.2] > x = "bc"
            // => "bc"
            // [3.0.2] > x.encoding
            // => #<Encoding:UTF-8>
            // [3.0.2] > x.object_id
            // => 260
            // [3.0.2] > y = t[x]
            // => "bc"
            // [3.0.2] > y.encoding
            // => #<Encoding:UTF-8>
            // [3.0.2] > y.object_id
            // => 280
            // [3.0.2] > z = "bc".force_encoding(Encoding::ASCII)
            // => "bc"
            // [3.0.2] > y[z].encoding
            // => #<Encoding:US-ASCII>
            // [3.0.2] > t[z].encoding
            // => #<Encoding:US-ASCII>
            // [3.0.2] > s[z].encoding
            // => #<Encoding:US-ASCII>
            // ```
            let encoding = substring.encoding();
            let s = super::String::with_bytes_and_encoding(substring.to_vec(), encoding);
            return super::String::alloc_value(s, interp);
        }
        return Ok(Value::nil());
    }
    let index = implicitly_convert_to_int(interp, first)?;

    // ```
    // [3.0.1] > s = "abc"
    // => "abc"
    // [3.0.1] > s[-2]
    // => "b"
    // [3.0.1] > s[-3]
    // => "a"
    // [3.0.1] > s[-4]
    // => nil
    // ```
    let index = if let Ok(index) = usize::try_from(index) {
        Some(index)
    } else {
        index
            .checked_neg()
            .and_then(|index| usize::try_from(index).ok())
            .and_then(|index| s.len().checked_sub(index))
    };
    if let Some(index) = index {
        // Index the byte, non existent indexes return `nil`.
        //
        // ```
        // [3.0.1] > s = "abc"
        // => "abc"
        // [3.0.1] > s[2]
        // => "c"
        // [3.0.1] > s[3]
        // => nil
        // [3.0.1] > s[4]
        // => nil
        // ```
        if let Some(bytes) = s.get_char(index) {
            let s = super::String::with_bytes_and_encoding(bytes.to_vec(), s.encoding());
            return super::String::alloc_value(s, interp);
        }
    }
    Ok(Value::nil())
}

pub fn aset(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    if value.is_frozen(interp) {
        let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
        let message = "can't modify frozen String: "
            .chars()
            .chain(s.inspect())
            .collect::<super::String>();
        return Err(FrozenError::from(message.into_vec()).into());
    }

    let _s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    Err(NotImplementedError::new().into())
}

pub fn is_ascii_only(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let is_ascii_only = s.is_ascii_only();
    Ok(interp.convert(is_ascii_only))
}

pub fn b(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    super::String::alloc_value(s.to_binary(), interp)
}

pub fn bytes(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let bytes = s
        .bytes()
        .map(i64::from)
        .map(|byte| interp.convert(byte))
        .collect::<Array>();
    Array::alloc_value(bytes, interp)
}

pub fn bytesize(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let bytesize = s.bytesize();
    interp.try_convert(bytesize)
}

pub fn byteslice(
    interp: &mut Artichoke,
    mut value: Value,
    index: Value,
    length: Option<Value>,
) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    // ```
    // [3.0.2] > class A; def to_int; 1; end; end
    // => :to_int
    // [3.0.2] > s = "abc"
    // => "abc"
    // [3.0.2] > s.byteslice(A.new)
    // => "b"
    // [3.0.2] > s.byteslice(//)
    // (irb):16:in `byteslice': no implicit conversion of Regexp into Integer (TypeError)
    // 	from (irb):16:in `<main>'
    // 	from /usr/local/var/rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/irb-1.3.5/exe/irb:11:in `<top (required)>'
    // 	from /usr/local/var/rbenv/versions/3.0.2/bin/irb:23:in `load'
    // 	from /usr/local/var/rbenv/versions/3.0.2/bin/irb:23:in `<main>'
    // ```
    let index = implicitly_convert_to_int(interp, index)?;

    // ```
    // [3.0.2] > s = "abc"
    // => "abc"
    // [3.0.2] > s.byteslice(-2, 10)
    // => "bc"
    // [3.0.2] > s.byteslice(-3, 10)
    // => "abc"
    // [3.0.2] > s.byteslice(-4, 10)
    // => nil
    // ```
    let index = if let Ok(index) = usize::try_from(index) {
        Some(index)
    } else {
        index
            .checked_neg()
            .and_then(|index| usize::try_from(index).ok())
            .and_then(|index| s.len().checked_sub(index))
    };
    let index = match index {
        None => return Ok(Value::nil()),
        // Short circuit with `nil` if `index > len`.
        //
        // ```
        // [3.0.1] > s = "abc"
        // => "abc"
        // [3.0.1] > s.byteslice(3, 10)
        // => ""
        // [3.0.1] > s.byteslice(4, 10)
        // => nil
        // ```
        //
        // Don't specialize on the case where `index == len` because the provided
        // length can change the result. Even if the length argument is not
        // given, we still need to preserve the encoding of the source string,
        // so fall through to the happy path below.
        Some(index) if index > s.len() => return Ok(Value::nil()),
        Some(index) => index,
    };

    let length = if let Some(length) = length {
        length
    } else {
        // Per the docs -- https://ruby-doc.org/core-3.0.2/String.html#method-i-byteslice
        //
        // > If passed a single Integer, returns a substring of one byte at that position.
        //
        // NOTE: Index out a single byte rather than a slice to avoid having
        // to do an overflow check on the addition.
        if let Some(&byte) = s.get(index) {
            let s = super::String::with_bytes_and_encoding(vec![byte], s.encoding());
            // ```
            // [3.0.1] > class S < String; end
            // => nil
            // [3.0.1] > S.new("abc").byteslice(1, 2).class
            // => String
            // ```
            //
            // The returned `String` is never frozen:
            //
            // ```
            // [3.0.1] > s = "abc"
            // => "abc"
            // [3.0.1] > s.frozen?
            // => false
            // [3.0.1] > s.byteslice(1, 2).frozen?
            // => false
            // [3.0.1] > t = "abc".freeze
            // => "abc"
            // [3.0.1] > t.byteslice(1, 2).frozen?
            // => false
            // ```
            return super::String::alloc_value(s, interp);
        }
        return Ok(Value::nil());
    };

    // ```
    // [3.0.2] > class A; def to_int; 1; end; end
    // => :to_int
    // [3.0.2] > s = "abc"
    // => "abc"
    // [3.0.2] > s.byteslice(A.new)
    // => "b"
    // [3.0.2] > s.byteslice(A.new, A.new)
    // => "b"
    // [3.0.2] > s.byteslice(2, //)
    // (irb):17:in `byteslice': no implicit conversion of Regexp into Integer (TypeError)
    // 	from (irb):17:in `<main>'
    // 	from /usr/local/var/rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/irb-1.3.5/exe/irb:11:in `<top (required)>'
    // 	from /usr/local/var/rbenv/versions/3.0.2/bin/irb:23:in `load'
    // 	from /usr/local/var/rbenv/versions/3.0.2/bin/irb:23:in `<main>
    // ```
    let length = implicitly_convert_to_int(interp, length)?;

    // ```
    // [3.0.2] > s = "abc"
    // => "abc"
    // [3.0.2] > s.byteslice(1, -1)
    // => nil
    // ```
    if let Ok(length) = usize::try_from(length) {
        // ```
        // [3.0.2] > s = "abc"
        // => "abc"
        // [3.0.2] > s.byteslice(2**64, 2**64)
        // (irb):38:in `byteslice': bignum too big to convert into `long' (RangeError)
        // 	from (irb):38:in `<main>'
        // 	from /usr/local/var/rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/irb-1.3.5/exe/irb:11:in `<top (required)>'
        // 	from /usr/local/var/rbenv/versions/3.0.2/bin/irb:23:in `load'
        // 	from /usr/local/var/rbenv/versions/3.0.2/bin/irb:23:in `<main>'
        // ```
        let end = index
            .checked_add(length)
            .ok_or_else(|| RangeError::with_message("bignum too big to convert into `long'"))?;
        if let Some(slice) = s.get(index..end).or_else(|| s.get(index..)) {
            // Encoding from the source string is preserved.
            //
            // ```
            // [3.0.2] > s = "abc"
            // => "abc"
            // [3.0.2] > s.encoding
            // => #<Encoding:UTF-8>
            // [3.0.2] > s.byteslice(1, 2).encoding
            // => #<Encoding:UTF-8>
            // [3.0.2] > t = s.force_encoding(Encoding::ASCII)
            // => "abc"
            // [3.0.2] > t.byteslice(1, 2).encoding
            // => #<Encoding:US-ASCII>
            // ```
            let s = super::String::with_bytes_and_encoding(slice.to_vec(), s.encoding());
            // ```
            // [3.0.1] > class S < String; end
            // => nil
            // [3.0.1] > S.new("abc").byteslice(1, 2).class
            // => String
            // ```
            //
            // The returned `String` is never frozen:
            //
            // ```
            // [3.0.1] > s = "abc"
            // => "abc"
            // [3.0.1] > s.frozen?
            // => false
            // [3.0.1] > s.byteslice(1, 2).frozen?
            // => false
            // [3.0.1] > t = "abc".freeze
            // => "abc"
            // [3.0.1] > t.byteslice(1, 2).frozen?
            // => false
            // ```
            return super::String::alloc_value(s, interp);
        }
    }
    Ok(Value::nil())
}

pub fn capitalize(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let mut dup = s.clone();
    dup.make_capitalized();
    super::String::alloc_value(dup, interp)
}

pub fn capitalize_bang(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    if value.is_frozen(interp) {
        let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
        let message = "can't modify frozen String: "
            .chars()
            .chain(s.inspect())
            .collect::<super::String>();
        return Err(FrozenError::from(message.into_vec()).into());
    }

    let mut s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    // Safety:
    //
    // The string is reboxed before any intervening operations on the
    // interpreter.
    // The string is reboxed without any intervening mruby allocations.
    unsafe {
        let string_mut = s.as_inner_mut();
        // `make_capitalized` might reallocate the string and invalidate the
        // boxed pointer, capacity, length triple.
        string_mut.make_capitalized();

        let s = s.take();
        super::String::box_into_value(s, value, interp)
    }
}

pub fn casecmp_ascii(interp: &mut Artichoke, mut value: Value, mut other: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    // Safety:
    //
    // The byte slice is immediately discarded after extraction. There are no
    // intervening interpreter accesses.
    if let Ok(other) = unsafe { implicitly_convert_to_string(interp, &mut other) } {
        let cmp = s.ascii_casecmp(other) as i64;
        Ok(interp.convert(cmp))
    } else {
        Ok(Value::nil())
    }
}

pub fn casecmp_unicode(interp: &mut Artichoke, mut value: Value, mut other: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    // TODO: this needs to do an implicit conversion, but we need a Spinoso string.
    if let Ok(other) = unsafe { super::String::unbox_from_value(&mut other, interp) } {
        let eql = *s == *other;
        Ok(interp.convert(eql))
    } else {
        Ok(interp.convert(false))
    }
}

pub fn center(interp: &mut Artichoke, mut value: Value, width: Value, padstr: Option<Value>) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let width = implicitly_convert_to_int(interp, width)?;
    let width = if let Ok(width) = usize::try_from(width) {
        width
    } else {
        // ```ruby
        // [3.0.2] > "a".center(-1)
        // => "a"
        // [3.0.2] > "a".center(-10)
        // => "a"
        // [3.0.2] > x = "a"
        // => "a"
        // [3.0.2] > y = "a".center(-10)
        // => "a"
        // [3.0.2] > x.object_id == y.object_id
        // => false
        // ```
        let dup = s.clone();
        return super::String::alloc_value(dup, interp);
    };
    // Safety:
    //
    // The byte slice is immediately discarded after extraction and turned into
    // an owned value. There are no intervening interpreter accesses.
    let padstr = if let Some(mut padstr) = padstr {
        let padstr = unsafe { implicitly_convert_to_string(interp, &mut padstr)? };
        Some(padstr.to_vec())
    } else {
        None
    };
    let centered = s
        .center(width, padstr.as_deref())
        .map_err(|e| ArgumentError::with_message(e.message()))?
        .collect::<super::String>();
    super::String::alloc_value(centered, interp)
}

pub fn chars(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let chars = s.chars().collect::<Vec<&[u8]>>();
    interp.try_convert_mut(chars)
}

pub fn chomp(interp: &mut Artichoke, mut value: Value, separator: Option<Value>) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let mut dup = s.clone();
    if let Some(mut separator) = separator {
        if let Some(sep) = unsafe { implicitly_convert_to_nilable_string(interp, &mut separator)? } {
            let _ = dup.chomp(Some(sep));
        } else {
            return interp.try_convert_mut("");
        }
    } else {
        let _ = dup.chomp(None::<&[u8]>);
    }
    super::String::alloc_value(dup, interp)
}

pub fn chomp_bang(interp: &mut Artichoke, mut value: Value, separator: Option<Value>) -> Result<Value, Error> {
    if value.is_frozen(interp) {
        let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
        let message = "can't modify frozen String: "
            .chars()
            .chain(s.inspect())
            .collect::<super::String>();
        return Err(FrozenError::from(message.into_vec()).into());
    }

    let mut s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    unsafe {
        let string_mut = s.as_inner_mut();
        let modified = if let Some(mut separator) = separator {
            if let Some(sep) = implicitly_convert_to_nilable_string(interp, &mut separator)? {
                string_mut.chomp(Some(sep))
            } else {
                return Ok(Value::nil());
            }
        } else {
            string_mut.chomp(None::<&[u8]>)
        };
        if modified {
            let s = s.take();
            return super::String::box_into_value(s, value, interp);
        }
    }
    Ok(Value::nil())
}

pub fn chop(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let mut dup = s.clone();
    let _ = dup.chop();
    super::String::alloc_value(dup, interp)
}

pub fn chop_bang(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    if value.is_frozen(interp) {
        let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
        let message = "can't modify frozen String: "
            .chars()
            .chain(s.inspect())
            .collect::<super::String>();
        return Err(FrozenError::from(message.into_vec()).into());
    }

    let mut s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    if s.is_empty() {
        return Ok(Value::nil());
    }
    unsafe {
        let string_mut = s.as_inner_mut();
        let modified = string_mut.chop();
        if modified {
            let s = s.take();
            return super::String::box_into_value(s, value, interp);
        }
    }
    Ok(value)
}

pub fn chr(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let chr = s.chr();
    interp.try_convert_mut(chr)
}

pub fn clear(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    if value.is_frozen(interp) {
        let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
        let message = "can't modify frozen String: "
            .chars()
            .chain(s.inspect())
            .collect::<super::String>();
        return Err(FrozenError::from(message.into_vec()).into());
    }

    let mut s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    // Safety:
    //
    // The string is reboxed before any intervening operations on the
    // interpreter.
    // The string is reboxed without any intervening mruby allocations.
    unsafe {
        let string_mut = s.as_inner_mut();
        string_mut.clear();

        let s = s.take();
        super::String::box_into_value(s, value, interp)
    }
}

pub fn codepoints(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let codepoints = s
        .codepoints()
        .map_err(|err| ArgumentError::with_message(err.message()))?;
    let codepoints = codepoints.map(|ch| interp.convert(ch)).collect::<Array>();
    Array::alloc_value(codepoints, interp)
}

pub fn concat(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let _s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    Err(NotImplementedError::new().into())
}

pub fn downcase(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let mut dup = s.clone();
    dup.make_lowercase();
    super::String::alloc_value(dup, interp)
}

pub fn downcase_bang(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let mut s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    // Safety:
    //
    // The string is reboxed before any intervening operations on the
    // interpreter.
    // The string is reboxed without any intervening mruby allocations.
    unsafe {
        let string_mut = s.as_inner_mut();
        // `make_lowercase` might reallocate the string and invalidate the
        // boxed pointer, capacity, length triple.
        string_mut.make_lowercase();

        let s = s.take();
        super::String::box_into_value(s, value, interp)
    }
}

pub fn is_empty(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    Ok(interp.convert(s.is_empty()))
}

pub fn eql(interp: &mut Artichoke, mut value: Value, mut other: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    if let Ok(other) = unsafe { super::String::unbox_from_value(&mut other, interp) } {
        let eql = *s == *other;
        Ok(interp.convert(eql))
    } else {
        Ok(interp.convert(false))
    }
}

pub fn getbyte(interp: &mut Artichoke, mut value: Value, index: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let index = implicitly_convert_to_int(interp, index)?;
    let index = if let Ok(index) = usize::try_from(index) {
        index
    } else {
        let index = index
            .checked_neg()
            .ok_or_else(|| RangeError::with_message("bignum too big to convert into `long'"))?;
        let index = usize::try_from(index).ok().and_then(|index| s.len().checked_sub(index));
        if let Some(index) = index {
            index
        } else {
            return Ok(Value::nil());
        }
    };
    let byte = s.get(index).copied().map(i64::from);
    Ok(interp.convert(byte))
}

pub fn hash(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let mut hasher = interp.global_build_hasher()?.build_hasher();
    s.as_slice().hash(&mut hasher);
    #[allow(clippy::cast_possible_wrap)]
    let hash = hasher.finish() as i64;
    Ok(interp.convert(hash))
}

pub fn include(interp: &mut Artichoke, mut value: Value, mut other: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let other_str = unsafe { implicitly_convert_to_string(interp, &mut other)? };
    let includes = s.index(other_str, None).is_some();
    Ok(interp.convert(includes))
}

pub fn index(
    interp: &mut Artichoke,
    mut value: Value,
    mut needle: Value,
    offset: Option<Value>,
) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    #[cfg(feature = "core-regexp")]
    if let Ok(_pattern) = unsafe { Regexp::unbox_from_value(&mut needle, interp) } {
        return Err(NotImplementedError::from("String#index with Regexp pattern").into());
    }
    let needle = unsafe { implicitly_convert_to_string(interp, &mut needle)? };
    let index = if let Some(offset) = offset {
        let offset = implicitly_convert_to_int(interp, offset)?;
        let offset = if let Ok(offset) = usize::try_from(offset) {
            Some(offset)
        } else {
            offset
                .checked_neg()
                .and_then(|offset| usize::try_from(offset).ok())
                .and_then(|offset| s.len().checked_sub(offset))
        };
        s.index(needle, offset)
    } else {
        s.index(needle, None)
    };
    let index = index.and_then(|index| i64::try_from(index).ok());
    interp.try_convert(index)
}

pub fn initialize(interp: &mut Artichoke, mut value: Value, from: Option<Value>) -> Result<Value, Error> {
    // We must convert `from` to a byte buffer first in case `#to_str` raises.
    //
    // If we don't, the following scenario could leave `value` with a dangling
    // pointer.
    //
    // ```console
    // [3.0.2] > s = "abc"
    // => "abc"
    // [3.0.2] > class B; def to_str; raise 'oh no'; end; end
    // => :to_str
    // [3.0.2] > s.send(:initialize, B.new)
    // (irb):6:in `to_str': oh no (RuntimeError)
    // 	from (irb):7:in `initialize'
    // 	from (irb):7:in `<main>'
    // 	from /usr/local/var/rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/irb-1.3.5/exe/irb:11:in `<top (required)>'
    // 	from /usr/local/var/rbenv/versions/3.0.2/bin/irb:23:in `load'
    // 	from /usr/local/var/rbenv/versions/3.0.2/bin/irb:23:in `<main>'
    // [3.0.2] > s
    // => "abc"
    // ```
    let buf = if let Some(mut from) = from {
        // Safety:
        //
        // The extracted slice is immediately copied to an owned buffer.
        //
        // No intervening operations on the mruby VM occur.
        let from = unsafe { implicitly_convert_to_string(interp, &mut from)? };
        from.to_vec()
    } else {
        Vec::new()
    };

    // If we are calling `initialize` on an already initialized `String`,
    // pluck out the inner buffer and drop it so we don't leak memory.
    //
    // ```console
    // [3.0.2] > s = "abc"
    // => "abc"
    // [3.0.2] > class A; def to_str; 'foo'; end; end
    // => :to_str
    // [3.0.2] > s.send(:initialize, A.new)
    // => "foo"
    // [3.0.2] > s
    // => "foo"
    // ```
    if let Ok(s) = unsafe { super::String::unbox_from_value(&mut value, interp) } {
        unsafe {
            let inner = s.take();
            drop(inner);
        }
    }
    // We are no guaranteed that the `buf` pointer in `value` is either dangling
    // or uninitialized. We will ensure that we box the given bytes into it.
    let buf = super::String::from(buf);
    super::String::box_into_value(buf, value, interp)
}

pub fn initialize_copy(interp: &mut Artichoke, mut value: Value, mut other: Value) -> Result<Value, Error> {
    // Safety:
    //
    // The extracted slice is immediately copied to an owned buffer.
    //
    // No intervening operations on the mruby VM occur.
    let buf = unsafe {
        let from = implicitly_convert_to_string(interp, &mut other)?;
        from.to_vec()
    };
    // If we are calling `initialize_copy` on an already initialized `String`,
    // pluck out the inner buffer and drop it so we don't leak memory.
    if let Ok(s) = unsafe { super::String::unbox_from_value(&mut value, interp) } {
        unsafe {
            let inner = s.take();
            drop(inner);
        }
    }
    // XXX: This should use the encoding of the given `other`.
    let replacement = super::String::with_bytes_and_encoding(buf, super::Encoding::Utf8);
    super::String::box_into_value(replacement, value, interp)
}

pub fn inspect(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let inspect = s.inspect().collect::<super::String>();
    super::String::alloc_value(inspect, interp)
}

pub fn intern(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let bytes = s.as_slice();
    let sym = if let Some(sym) = interp.check_interned_bytes(bytes)? {
        sym
    } else {
        interp.intern_bytes(bytes.to_vec())?
    };
    Symbol::alloc_value(sym.into(), interp)
}

pub fn length(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let length = s.char_len();
    interp.try_convert(length)
}

pub fn ord(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let ord = s.ord().map_err(|err| ArgumentError::with_message(err.message()))?;
    Ok(interp.convert(ord))
}

pub fn replace(interp: &mut Artichoke, value: Value, other: Value) -> Result<Value, Error> {
    initialize_copy(interp, value, other)
}

pub fn reverse(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let mut reversed = s.clone();
    reversed.reverse();
    super::String::alloc_value(reversed, interp)
}

pub fn reverse_bang(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    if value.is_frozen(interp) {
        let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
        let message = "can't modify frozen String: "
            .chars()
            .chain(s.inspect())
            .collect::<super::String>();
        return Err(FrozenError::from(message.into_vec()).into());
    }

    let mut s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    // Safety:
    //
    // The string is reboxed before any intervening operations on the
    // interpreter.
    // The string is reboxed without any intervening mruby allocations.
    unsafe {
        let string_mut = s.as_inner_mut();
        string_mut.reverse();

        let s = s.take();
        super::String::box_into_value(s, value, interp)
    }
}

pub fn rindex(
    interp: &mut Artichoke,
    mut value: Value,
    mut needle: Value,
    offset: Option<Value>,
) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    #[cfg(feature = "core-regexp")]
    if let Ok(_pattern) = unsafe { Regexp::unbox_from_value(&mut needle, interp) } {
        return Err(NotImplementedError::from("String#index with Regexp pattern").into());
    }
    let needle = unsafe { implicitly_convert_to_string(interp, &mut needle)? };
    let index = if let Some(offset) = offset {
        let offset = implicitly_convert_to_int(interp, offset)?;
        let offset = if let Ok(offset) = usize::try_from(offset) {
            Some(offset)
        } else {
            offset
                .checked_neg()
                .and_then(|offset| usize::try_from(offset).ok())
                .and_then(|offset| s.len().checked_sub(offset))
        };
        s.rindex(needle, offset)
    } else {
        s.rindex(needle, None)
    };
    let index = index.and_then(|index| i64::try_from(index).ok());
    interp.try_convert(index)
}

pub fn scan(interp: &mut Artichoke, value: Value, mut pattern: Value, block: Option<Block>) -> Result<Value, Error> {
    if let Ruby::Symbol = pattern.ruby_type() {
        let mut message = String::from("wrong argument type ");
        message.push_str(interp.inspect_type_name_for_value(pattern));
        message.push_str(" (expected Regexp)");
        return Err(TypeError::from(message).into());
    }
    #[cfg(feature = "core-regexp")]
    if let Ok(regexp) = unsafe { Regexp::unbox_from_value(&mut pattern, interp) } {
        let haystack = value.try_convert_into_mut::<&[u8]>(interp)?;
        let scan = regexp.inner().scan(interp, haystack, block)?;
        return Ok(interp.try_convert_mut(scan)?.unwrap_or(value));
    }
    #[cfg(feature = "core-regexp")]
    // Safety:
    //
    // Convert `pattern_bytes` to an owned byte vec to ensure the underlying
    // `RString` is not garbage collected when yielding matches.
    if let Ok(pattern_bytes) = unsafe { implicitly_convert_to_string(interp, &mut pattern) } {
        let pattern_bytes = pattern_bytes.to_vec();

        let string = value.try_convert_into_mut::<&[u8]>(interp)?;
        if let Some(ref block) = block {
            let regex = Regexp::try_from(pattern_bytes.clone())?;
            let matchdata = MatchData::new(string.to_vec(), regex, ..);
            let patlen = pattern_bytes.len();
            if let Some(pos) = string.find(&pattern_bytes) {
                let mut data = matchdata.clone();
                data.set_region(pos..pos + patlen);
                let data = MatchData::alloc_value(data, interp)?;
                interp.set_global_variable(regexp::LAST_MATCH, &data)?;

                let block_arg = interp.try_convert_mut(pattern_bytes.as_slice())?;
                block.yield_arg(interp, &block_arg)?;

                interp.set_global_variable(regexp::LAST_MATCH, &data)?;

                let offset = pos + patlen;
                let string = string.get(offset..).unwrap_or_default();
                for pos in string.find_iter(&pattern_bytes) {
                    let mut data = matchdata.clone();
                    data.set_region(offset + pos..offset + pos + patlen);
                    let data = MatchData::alloc_value(data, interp)?;
                    interp.set_global_variable(regexp::LAST_MATCH, &data)?;

                    let block_arg = interp.try_convert_mut(pattern_bytes.as_slice())?;
                    block.yield_arg(interp, &block_arg)?;

                    interp.set_global_variable(regexp::LAST_MATCH, &data)?;
                }
            } else {
                interp.unset_global_variable(regexp::LAST_MATCH)?;
            }
            return Ok(value);
        }
        let (matches, last_pos) = string
            .find_iter(&pattern_bytes)
            .enumerate()
            .last()
            .map(|(m, p)| (m + 1, p))
            .unwrap_or_default();
        let mut result = Vec::with_capacity(matches);
        for _ in 0..matches {
            result.push(interp.try_convert_mut(pattern_bytes.as_slice())?);
        }
        if matches > 0 {
            let regex = Regexp::try_from(pattern_bytes.clone())?;
            let matchdata = MatchData::new(string.to_vec(), regex, last_pos..last_pos + pattern_bytes.len());
            let data = MatchData::alloc_value(matchdata, interp)?;
            interp.set_global_variable(regexp::LAST_MATCH, &data)?;
        } else {
            interp.unset_global_variable(regexp::LAST_MATCH)?;
        }
        return interp.try_convert_mut(result);
    }
    #[cfg(not(feature = "core-regexp"))]
    // Safety:
    //
    // Convert `pattern_bytes` to an owned byte vec to ensure the underlying
    // `RString` is not garbage collected when yielding matches.
    if let Ok(pattern_bytes) = unsafe { implicitly_convert_to_string(interp, &mut pattern) } {
        let pattern_bytes = pattern_bytes.to_vec();

        let string = value.try_convert_into_mut::<&[u8]>(interp)?;
        if let Some(ref block) = block {
            let patlen = pattern_bytes.len();
            if let Some(pos) = string.find(&pattern_bytes) {
                let block_arg = interp.try_convert_mut(pattern_bytes.as_slice())?;
                block.yield_arg(interp, &block_arg)?;

                let offset = pos + patlen;
                let string = string.get(offset..).unwrap_or_default();
                for _ in string.find_iter(&pattern_bytes) {
                    let block_arg = interp.try_convert_mut(pattern_bytes.as_slice())?;
                    block.yield_arg(interp, &block_arg)?;
                }
            }
            return Ok(value);
        }
        let matches = string
            .find_iter(&pattern_bytes)
            .enumerate()
            .last()
            .map(|(m, _)| m + 1)
            .unwrap_or_default();
        let mut result = Vec::with_capacity(matches);
        for _ in 0..matches {
            result.push(interp.try_convert_mut(pattern_bytes.as_slice())?);
        }
        return interp.try_convert_mut(result);
    }
    let mut message = String::from("wrong argument type ");
    message.push_str(interp.inspect_type_name_for_value(pattern));
    message.push_str(" (expected Regexp)");
    Err(TypeError::from(message).into())
}

pub fn setbyte(interp: &mut Artichoke, mut value: Value, index: Value, byte: Value) -> Result<Value, Error> {
    let index = implicitly_convert_to_int(interp, index)?;
    let i64_byte = implicitly_convert_to_int(interp, byte)?;

    if value.is_frozen(interp) {
        let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
        let message = "can't modify frozen String: "
            .chars()
            .chain(s.inspect())
            .collect::<super::String>();
        return Err(FrozenError::from(message.into_vec()).into());
    }

    let mut s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let index = if let Ok(index) = usize::try_from(index) {
        index
    } else {
        let idx = index
            .checked_neg()
            .ok_or_else(|| RangeError::with_message("bignum too big to convert into `long'"))?;
        let idx = usize::try_from(idx).ok().and_then(|index| s.len().checked_sub(index));
        if let Some(idx) = idx {
            idx
        } else {
            let mut message = String::from("index ");
            // Suppress error because `String`'s `fmt::Write` impl is infallible.
            // (It will abort on OOM).
            let _ignored = write!(&mut message, "{} out of string", index);
            return Err(IndexError::from(message).into());
        }
    };
    // Wrapping when negative is intentional
    //
    // ```
    // [3.0.2] > s = "abc"
    // => "abc"
    // [3.0.2] > s.setbyte(-3, 99)
    // => 99
    // [3.0.2] > s
    // => "cbc"
    // [3.0.2] > s.setbyte(-3, 255)
    // => 255
    // [3.0.2] > s
    // => "\xFFbc"
    // [3.0.2] > s.setbyte(-3, 256)
    // => 256
    // [3.0.2] > s
    // => "\u0000bc"
    // [3.0.2] > s.setbyte(-3, 257)
    // => 257
    // [3.0.2] > s
    // => "\u0001bc"
    // [3.0.2] > s.setbyte(-3, -1)
    // => -1
    // [3.0.2] > s
    // => "\xFFbc"
    // ```
    let u8_byte = (i64_byte % 256)
        .try_into()
        .expect("taking mod 256 guarantees the resulting i64 is in range for u8");
    // Safety:
    //
    // No need to repack, this is an in-place mutation.
    unsafe {
        let string_mut = s.as_inner_mut();
        let cell = string_mut.get_mut(index).ok_or_else(|| {
            let mut message = String::from("index ");
            // Suppress error because `String`'s `fmt::Write` impl is infallible.
            // (It will abort on OOM).
            let _ignored = write!(&mut message, "{} out of string", index);
            IndexError::from(message)
        })?;
        *cell = u8_byte;
    }

    // Return the original byte argument.
    Ok(byte)
}

pub fn slice_bang(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let _s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    Err(NotImplementedError::new().into())
}

pub fn split(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let _s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    Err(NotImplementedError::new().into())
}

pub fn to_f(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let _s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    Err(NotImplementedError::new().into())
}

pub fn to_i(interp: &mut Artichoke, mut value: Value, base: Option<Value>) -> Result<Value, Error> {
    fn try_parse(slice: &[u8], base: u32) -> Option<i64> {
        let s = str::from_utf8(slice).ok()?;
        i64::from_str_radix(s, base).ok()
    }

    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let base = if let Some(base) = base {
        let base = implicitly_convert_to_int(interp, base)?;
        let base = u32::try_from(base).map_err(|_| ArgumentError::from(format!("invalid radix {base}")))?;
        match base {
            0 => 10,
            1 => return Err(ArgumentError::with_message("invalid radix 1").into()),
            x if x > 36 => return Err(ArgumentError::from(format!("invalid radix {x}")).into()),
            x => x,
        }
    } else {
        10_u32
    };
    let mut slice = s.as_slice();
    let mut squeezed = false;
    // squeeze preceding zeros.
    while let Some(&b'0') = slice.get(0) {
        slice = &slice[1..];
        squeezed = true;
    }
    // Trim leading literal specifier but only if there was a leading 0.
    if squeezed {
        #[allow(clippy::match_same_arms)]
        match (base, slice.get(0).copied()) {
            (2, Some(b'b' | b'B')) => slice = &slice[1..],
            (8, Some(b'o' | b'O')) => slice = &slice[1..],
            (10, Some(b'd' | b'D')) => slice = &slice[1..],
            (16, Some(b'x' | b'X')) => slice = &slice[1..],
            _ => {}
        }
    }

    if slice.is_empty() {
        return Ok(interp.convert(0));
    }
    loop {
        // Try to greedily parse the whole string as an int.
        if let Some(int) = try_parse(slice, base) {
            return Ok(interp.convert(int));
        }
        // if parsing failed, start discarding from the end one byte at a time.
        if let Some((_, head)) = slice.split_last() {
            slice = head;
        } else {
            return Ok(interp.convert(0));
        }
    }
}

pub fn to_s(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let _s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    Ok(value)
}

pub fn upcase(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    let mut dup = s.clone();
    dup.make_uppercase();
    super::String::alloc_value(dup, interp)
}

pub fn upcase_bang(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let mut s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    // Safety:
    //
    // The string is reboxed before any intervening operations on the
    // interpreter.
    // The string is reboxed without any intervening mruby allocations.
    unsafe {
        let string_mut = s.as_inner_mut();
        // `make_uppercase` might reallocate the string and invalidate the
        // boxed pointer, capacity, length triple.
        string_mut.make_uppercase();

        let s = s.take();
        super::String::box_into_value(s, value, interp)
    }
}

pub fn is_valid_encoding(interp: &mut Artichoke, mut value: Value) -> Result<Value, Error> {
    let s = unsafe { super::String::unbox_from_value(&mut value, interp)? };
    Ok(interp.convert(s.is_valid_encoding()))
}