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
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
//! Types for working with Ruby’s String class.

use std::{
    borrow::Cow,
    cmp::Ordering,
    ffi::CString,
    fmt, io,
    iter::Iterator,
    mem::transmute,
    os::raw::{c_char, c_long},
    path::{Path, PathBuf},
    ptr::{self},
    slice, str,
};

#[cfg(ruby_gte_3_0)]
use rb_sys::rb_str_to_interned_str;
use rb_sys::{
    self, rb_enc_str_coderange, rb_enc_str_new, rb_str_buf_append, rb_str_buf_new, rb_str_capacity,
    rb_str_cat, rb_str_cmp, rb_str_comparable, rb_str_conv_enc, rb_str_drop_bytes, rb_str_dump,
    rb_str_ellipsize, rb_str_new, rb_str_new_frozen, rb_str_new_shared, rb_str_offset, rb_str_plus,
    rb_str_replace, rb_str_scrub, rb_str_shared_replace, rb_str_split, rb_str_strlen, rb_str_times,
    rb_str_to_str, rb_str_update, rb_utf8_str_new, rb_utf8_str_new_static, ruby_coderange_type,
    ruby_rstring_flags, ruby_value_type, RSTRING_LEN, RSTRING_PTR, VALUE,
};

use crate::{
    encoding::{Coderange, EncodingCapable, RbEncoding},
    error::{protect, Error},
    into_value::{IntoValue, IntoValueFromNative},
    object::Object,
    r_array::RArray,
    try_convert::TryConvert,
    value::{
        private::{self, ReprValue as _},
        NonZeroValue, ReprValue, Value,
    },
    Ruby,
};

/// # `RString`
///
/// Functions that can be used to create Ruby `String`s.
///
/// See also the [`RString`] type.
impl Ruby {
    /// Create a new Ruby string from the Rust string `s`.
    ///
    /// The encoding of the Ruby string will be UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let val = ruby.str_new("example");
    ///     rb_assert!(ruby, r#"val == "example""#, val);
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn str_new(&self, s: &str) -> RString {
        let len = s.len();
        let ptr = s.as_ptr();
        unsafe {
            RString::from_rb_value_unchecked(rb_utf8_str_new(ptr as *const c_char, len as c_long))
        }
    }

    /// Implementation detail of [`r_string`].
    #[doc(hidden)]
    #[inline]
    pub unsafe fn str_new_lit(&self, ptr: *const c_char, len: c_long) -> RString {
        RString::from_rb_value_unchecked(rb_utf8_str_new_static(ptr, len))
    }

    /// Create a new Ruby string with capacity `n`.
    ///
    /// The encoding will be set to ASCII-8BIT (aka BINARY). See also
    /// [`with_capacity`](RString::with_capacity).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let buf = ruby.str_buf_new(4096);
    ///     buf.cat(&[13, 14, 10, 13, 11, 14, 14, 15]);
    ///     rb_assert!(ruby, r#"buf == "\r\x0E\n\r\v\x0E\x0E\x0F""#, buf);
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn str_buf_new(&self, n: usize) -> RString {
        unsafe { RString::from_rb_value_unchecked(rb_str_buf_new(n as c_long)) }
    }

    /// Create a new Ruby string with capacity `n`.
    ///
    /// The encoding will be set to UTF-8. See also
    /// [`buf_new`](RString::buf_new).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let s = ruby.str_with_capacity(9);
    ///     s.cat("foo");
    ///     s.cat("bar");
    ///     s.cat("baz");
    ///     rb_assert!(ruby, r#"s == "foobarbaz""#, s);
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn str_with_capacity(&self, n: usize) -> RString {
        let s = self.str_buf_new(n);
        s.enc_associate(self.utf8_encindex()).unwrap();
        s
    }

    /// Create a new Ruby string from the Rust slice `s`.
    ///
    /// The encoding of the Ruby string will be set to ASCII-8BIT (aka BINARY).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let buf = ruby.str_from_slice(&[13, 14, 10, 13, 11, 14, 14, 15]);
    ///     rb_assert!(ruby, r#"buf == "\r\x0E\n\r\v\x0E\x0E\x0F""#, buf);
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn str_from_slice(&self, s: &[u8]) -> RString {
        let len = s.len();
        let ptr = s.as_ptr();
        unsafe { RString::from_rb_value_unchecked(rb_str_new(ptr as *const c_char, len as c_long)) }
    }

    /// Create a new Ruby string from the value `s` with the encoding `enc`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let val = ruby.enc_str_new("example", ruby.usascii_encoding());
    ///     rb_assert!(ruby, r#"val == "example""#, val);
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let val = ruby.enc_str_new([255, 128, 128], ruby.ascii8bit_encoding());
    ///     rb_assert!(
    ///         ruby,
    ///         r#"val == "\xFF\x80\x80".force_encoding("BINARY")"#,
    ///         val
    ///     );
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn enc_str_new<T, E>(&self, s: T, enc: E) -> RString
    where
        T: AsRef<[u8]>,
        E: Into<RbEncoding>,
    {
        let s = s.as_ref();
        let len = s.len();
        let ptr = s.as_ptr();
        unsafe {
            RString::from_rb_value_unchecked(rb_enc_str_new(
                ptr as *const c_char,
                len as c_long,
                enc.into().as_ptr(),
            ))
        }
    }

    /// Create a new Ruby string from the Rust char `c`.
    ///
    /// The encoding of the Ruby string will be UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let c = ruby.str_from_char('a');
    ///     rb_assert!(ruby, r#"c == "a""#, c);
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let c = ruby.str_from_char('🦀');
    ///     rb_assert!(ruby, r#"c == "🦀""#, c);
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn str_from_char(&self, c: char) -> RString {
        let mut buf = [0; 4];
        self.str_new(c.encode_utf8(&mut buf[..]))
    }

    /// Create a new Ruby string containing the codepoint `code` in the
    /// encoding `enc`.
    ///
    /// The encoding of the Ruby string will be the passed encoding `enc`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let c = ruby.chr(97, ruby.usascii_encoding())?;
    ///     rb_assert!(ruby, r#"c == "a""#, c);
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    ///
    /// ```
    /// use magnus::{rb_assert, Error, Ruby};
    ///
    /// fn example(ruby: &Ruby) -> Result<(), Error> {
    ///     let c = ruby.chr(129408, ruby.utf8_encoding())?;
    ///     rb_assert!(ruby, r#"c == "🦀""#, c);
    ///
    ///     Ok(())
    /// }
    /// # Ruby::init(example).unwrap()
    /// ```
    pub fn chr<T>(&self, code: u32, enc: T) -> Result<RString, Error>
    where
        T: Into<RbEncoding>,
    {
        enc.into().chr(code)
    }
}

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

impl RString {
    /// Return `Some(RString)` if `val` is a `RString`, `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert!(RString::from_value(eval(r#""example""#).unwrap()).is_some());
    /// assert!(RString::from_value(eval(":example").unwrap()).is_none());
    /// ```
    #[inline]
    pub fn from_value(val: Value) -> Option<Self> {
        unsafe {
            (val.rb_type() == ruby_value_type::RUBY_T_STRING)
                .then(|| Self(NonZeroValue::new_unchecked(val)))
        }
    }

    pub(crate) fn ref_from_value(val: &Value) -> Option<&Self> {
        unsafe {
            (val.rb_type() == ruby_value_type::RUBY_T_STRING)
                .then(|| &*(val as *const _ as *const RString))
        }
    }

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

    /// Create a new Ruby string from the Rust string `s`.
    ///
    /// The encoding of the Ruby string will be UTF-8.
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::str_new`] for the
    /// non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let val = RString::new("example");
    /// rb_assert!(r#"val == "example""#, val);
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::str_new` instead")
    )]
    #[inline]
    pub fn new(s: &str) -> Self {
        get_ruby!().str_new(s)
    }

    /// Implementation detail of [`r_string`].
    #[doc(hidden)]
    #[inline]
    pub unsafe fn new_lit(ptr: *const c_char, len: c_long) -> Self {
        get_ruby!().str_new_lit(ptr, len)
    }

    /// Create a new Ruby string with capacity `n`.
    ///
    /// The encoding will be set to ASCII-8BIT (aka BINARY). See also
    /// [`with_capacity`](RString::with_capacity).
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::str_buf_new`] for
    /// the non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let buf = RString::buf_new(4096);
    /// buf.cat(&[13, 14, 10, 13, 11, 14, 14, 15]);
    /// rb_assert!(r#"buf == "\r\x0E\n\r\v\x0E\x0E\x0F""#, buf);
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::str_buf_new` instead")
    )]
    #[inline]
    pub fn buf_new(n: usize) -> Self {
        get_ruby!().str_buf_new(n)
    }

    /// Create a new Ruby string with capacity `n`.
    ///
    /// The encoding will be set to UTF-8. See also
    /// [`buf_new`](RString::buf_new).
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See
    /// [`Ruby::str_with_capacity`] for the non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::with_capacity(9);
    /// s.cat("foo");
    /// s.cat("bar");
    /// s.cat("baz");
    /// rb_assert!(r#"s == "foobarbaz""#, s);
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::str_with_capacity` instead")
    )]
    #[inline]
    pub fn with_capacity(n: usize) -> Self {
        get_ruby!().str_with_capacity(n)
    }

    /// Create a new Ruby string from the Rust slice `s`.
    ///
    /// The encoding of the Ruby string will be set to ASCII-8BIT (aka BINARY).
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::str_from_slice`]
    /// for the non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let buf = RString::from_slice(&[13, 14, 10, 13, 11, 14, 14, 15]);
    /// rb_assert!(r#"buf == "\r\x0E\n\r\v\x0E\x0E\x0F""#, buf);
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::str_from_slice` instead")
    )]
    #[inline]
    pub fn from_slice(s: &[u8]) -> Self {
        get_ruby!().str_from_slice(s)
    }

    /// Create a new Ruby string from the value `s` with the encoding `enc`.
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::enc_str_new`] for
    /// the non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{encoding::RbEncoding, rb_assert, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let val = RString::enc_new("example", RbEncoding::usascii());
    /// rb_assert!(r#"val == "example""#, val);
    /// ```
    ///
    /// ```
    /// use magnus::{encoding::RbEncoding, rb_assert, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let val = RString::enc_new([255, 128, 128], RbEncoding::ascii8bit());
    /// rb_assert!(r#"val == "\xFF\x80\x80".force_encoding("BINARY")"#, val);
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::enc_str_new` instead")
    )]
    #[inline]
    pub fn enc_new<T, E>(s: T, enc: E) -> Self
    where
        T: AsRef<[u8]>,
        E: Into<RbEncoding>,
    {
        get_ruby!().enc_str_new(s, enc)
    }

    /// Create a new Ruby string from the Rust char `c`.
    ///
    /// The encoding of the Ruby string will be UTF-8.
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::str_from_char`]
    /// for the non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let c = RString::from_char('a');
    /// rb_assert!(r#"c == "a""#, c);
    /// ```
    ///
    /// ```
    /// use magnus::{rb_assert, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let c = RString::from_char('🦀');
    /// rb_assert!(r#"c == "🦀""#, c);
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::str_from_char` instead")
    )]
    #[inline]
    pub fn from_char(c: char) -> Self {
        get_ruby!().str_from_char(c)
    }

    /// Create a new Ruby string containing the codepoint `code` in the
    /// encoding `enc`.
    ///
    /// The encoding of the Ruby string will be the passed encoding `enc`.
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See [`Ruby::chr`] for the
    /// non-panicking version.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{encoding::RbEncoding, rb_assert, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let c = RString::chr(97, RbEncoding::usascii()).unwrap();
    /// rb_assert!(r#"c == "a""#, c);
    /// ```
    ///
    /// ```
    /// use magnus::{encoding::RbEncoding, rb_assert, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let c = RString::chr(129408, RbEncoding::utf8()).unwrap();
    /// rb_assert!(r#"c == "🦀""#, c);
    /// ```
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `Ruby::chr` instead")
    )]
    #[inline]
    pub fn chr<T>(code: u32, enc: T) -> Result<Self, Error>
    where
        T: Into<RbEncoding>,
    {
        get_ruby!().chr(code, enc)
    }

    /// Create a new Ruby string that shares the same backing data as `s`.
    ///
    /// Both string objects will point at the same underlying data until one is
    /// modified, and only then will the data be duplicated. This operation is
    /// cheep, and useful for cases where you may need to modify a string, but
    /// don't want to mutate a value passed to your function.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("example");
    /// let dup = RString::new_shared(s);
    /// rb_assert!("s == dup", s, dup);
    /// // mutating one doesn't mutate both
    /// dup.cat("foo");
    /// rb_assert!("s != dup", s, dup);
    /// ```
    pub fn new_shared(s: Self) -> Self {
        unsafe { Self::from_rb_value_unchecked(rb_str_new_shared(s.as_rb_value())) }
    }

    /// Create a new Ruby string that is a frozen copy of `s`.
    ///
    /// This can be used to get a copy of a string that is guranteed not to be
    /// modified while you are referencing it.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{rb_assert, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let orig = RString::new("example");
    /// let frozen = RString::new_frozen(orig);
    /// rb_assert!(r#"frozen == "example""#, frozen);
    /// // mutating original doesn't impact the frozen copy
    /// orig.cat("foo");
    /// rb_assert!(r#"frozen == "example""#, frozen);
    /// ```
    pub fn new_frozen(s: Self) -> Self {
        unsafe { Self::from_rb_value_unchecked(rb_str_new_frozen(s.as_rb_value())) }
    }

    /// Return `self` as a slice of bytes.
    ///
    /// # Safety
    ///
    /// This is directly viewing memory owned and managed by Ruby. Ruby may
    /// modify or free the memory backing the returned slice, the caller must
    /// ensure this does not happen.
    ///
    /// Ruby must not be allowed to garbage collect or modify `self` while a
    /// refrence to the slice is held.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("example");
    /// // safe as we don't give Ruby the chance to mess with the string while
    /// // we hold a refrence to the slice.
    /// unsafe { assert_eq!(s.as_slice(), [101, 120, 97, 109, 112, 108, 101]) };
    /// ```
    pub unsafe fn as_slice(&self) -> &[u8] {
        self.as_slice_unconstrained()
    }

    unsafe fn as_slice_unconstrained<'a>(self) -> &'a [u8] {
        debug_assert_value!(self);
        slice::from_raw_parts(
            RSTRING_PTR(self.as_rb_value()) as *const u8,
            RSTRING_LEN(self.as_rb_value()) as _,
        )
    }

    /// Return an iterator over `self`'s codepoints.
    ///
    /// # Safety
    ///
    /// The returned iterator references memory owned and managed by Ruby. Ruby
    /// may modify or free that memory, the caller must ensure this does not
    /// happen at any time while still holding a reference to the iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{Error, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("🦀 café");
    ///
    /// let codepoints = unsafe {
    ///     // ensure string isn't mutated during iteration by creating a
    ///     // frozen copy and iterating over that
    ///     let f = RString::new_frozen(s);
    ///     f.codepoints().collect::<Result<Vec<_>, Error>>().unwrap()
    /// };
    ///
    /// assert_eq!(codepoints, [129408, 32, 99, 97, 102, 233]);
    /// ```
    pub unsafe fn codepoints(&self) -> Codepoints {
        Codepoints {
            slice: self.as_slice(),
            encoding: self.enc_get().into(),
        }
    }

    /// Return an iterator over `self`'s chars as slices of bytes.
    ///
    /// # Safety
    ///
    /// The returned iterator references memory owned and managed by Ruby. Ruby
    /// may modify or free that memory, the caller must ensure this does not
    /// happen at any time while still holding a reference to the iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("🦀 café");
    ///
    /// // ensure string isn't mutated during iteration by creating a frozen
    /// // copy and iterating over that
    /// let f = RString::new_frozen(s);
    /// let codepoints = unsafe { f.char_bytes().collect::<Vec<_>>() };
    ///
    /// assert_eq!(
    ///     codepoints,
    ///     [
    ///         &[240, 159, 166, 128][..],
    ///         &[32],
    ///         &[99],
    ///         &[97],
    ///         &[102],
    ///         &[195, 169]
    ///     ]
    /// );
    /// ```
    pub unsafe fn char_bytes(&self) -> CharBytes {
        CharBytes {
            slice: self.as_slice(),
            encoding: self.enc_get().into(),
        }
    }

    /// Converts a character offset to a byte offset.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("🌊🦀🏝️");
    /// assert_eq!(s.offset(1), 4);
    /// assert_eq!(s.offset(2), 8);
    /// ```
    pub fn offset(self, pos: usize) -> usize {
        unsafe { rb_str_offset(self.as_rb_value(), pos as c_long) as usize }
    }

    /// Returns true if the encoding for this string is UTF-8 or US-ASCII,
    /// false otherwise.
    ///
    /// The encoding on a Ruby String is just a label, it provides no guarantee
    /// that the String really is valid UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s: RString = eval!(r#""café""#).unwrap();
    /// assert!(s.is_utf8_compatible_encoding());
    /// ```
    ///
    /// ```
    /// use magnus::{eval, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s: RString = eval!(r#""café".encode("ISO-8859-1")"#).unwrap();
    /// assert!(!s.is_utf8_compatible_encoding());
    /// ```
    pub fn is_utf8_compatible_encoding(self) -> bool {
        let handle = Ruby::get_with(self);
        let encindex = self.enc_get();
        // us-ascii is a 100% compatible subset of utf8
        encindex == handle.utf8_encindex() || encindex == handle.usascii_encindex()
    }

    /// Returns a new string by reencoding `self` from its current encoding to
    /// the given `enc`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{encoding::RbEncoding, eval, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s: RString = eval!(r#""café".encode("ISO-8859-1")"#).unwrap();
    /// // safe as we don't give Ruby the chance to mess with the string while
    /// // we hold a refrence to the slice.
    /// unsafe { assert_eq!(s.as_slice(), &[99, 97, 102, 233]) };
    /// let e = s.conv_enc(RbEncoding::utf8()).unwrap();
    /// unsafe { assert_eq!(e.as_slice(), &[99, 97, 102, 195, 169]) };
    /// ```
    pub fn conv_enc<T>(self, enc: T) -> Result<Self, Error>
    where
        T: Into<RbEncoding>,
    {
        protect(|| unsafe {
            Self::from_rb_value_unchecked(rb_str_conv_enc(
                self.as_rb_value(),
                ptr::null_mut(),
                enc.into().as_ptr(),
            ))
        })
    }

    /// Returns a string omitting 'broken' parts of the string according to its
    /// encoding.
    ///
    /// If `replacement` is `Some(RString)` and 'broken' portion will be
    /// replaced with that string. When `replacement` is `None` an encoding
    /// specific default will be used.
    ///
    /// If `self` is not 'broken' and no replacement was made, returns
    /// `Ok(None)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{encoding::RbEncoding, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// // 156 is invalid for utf-8
    /// let s = RString::enc_new([156, 57, 57], RbEncoding::utf8());
    /// assert_eq!(s.scrub(None).unwrap().unwrap().to_string().unwrap(), "�99");
    /// assert_eq!(s.scrub(Some(RString::new("?"))).unwrap().unwrap().to_string().unwrap(), "?99");
    /// assert_eq!(s.scrub(Some(RString::new(""))).unwrap().unwrap().to_string().unwrap(), "99");
    pub fn scrub(self, replacement: Option<Self>) -> Result<Option<Self>, Error> {
        let val = protect(|| unsafe {
            Value::new(rb_str_scrub(
                self.as_rb_value(),
                replacement
                    .map(|r| r.as_rb_value())
                    .unwrap_or_else(|| Ruby::get_with(self).qnil().as_rb_value()),
            ))
        })?;
        if val.is_nil() {
            Ok(None)
        } else {
            unsafe { Ok(Some(Self(NonZeroValue::new_unchecked(val)))) }
        }
    }

    /// Returns the cached coderange value that describes how `self` relates to
    /// its encoding.
    ///
    /// See also [`enc_coderange_scan`](RString::enc_coderange_scan).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{encoding::Coderange, prelude::*, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// // Coderange is unknown on creation.
    /// let s = RString::new("test");
    /// assert_eq!(s.enc_coderange(), Coderange::Unknown);
    ///
    /// // Methods that operate on the string using the encoding will set the
    /// // coderange as a side effect.
    /// let _: usize = s.funcall("length", ()).unwrap();
    /// assert_eq!(s.enc_coderange(), Coderange::SevenBit);
    ///
    /// // Operations with two strings with known coderanges will set it
    /// // appropriately.
    /// let t = RString::new("🦀");
    /// let _: usize = t.funcall("length", ()).unwrap();
    /// assert_eq!(t.enc_coderange(), Coderange::Valid);
    /// s.buf_append(t).unwrap();
    /// assert_eq!(s.enc_coderange(), Coderange::Valid);
    ///
    /// // Operations that modify the string with an unknown coderange will
    /// // set the coderange back to unknown.
    /// s.cat([128]);
    /// assert_eq!(s.enc_coderange(), Coderange::Unknown);
    ///
    /// // Which may leave the string with a broken encoding.
    /// let _: usize = s.funcall("length", ()).unwrap();
    /// assert_eq!(s.enc_coderange(), Coderange::Broken);
    /// ```
    pub fn enc_coderange(self) -> Coderange {
        unsafe {
            transmute(
                (self.r_basic_unchecked().as_ref().flags
                    & ruby_coderange_type::RUBY_ENC_CODERANGE_MASK as VALUE) as u32,
            )
        }
    }

    /// Scans `self` to establish its coderange.
    ///
    /// If the coderange is already known, simply returns the known value.
    /// See also [`enc_coderange`](RString::enc_coderange).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{encoding::Coderange, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("test");
    /// assert_eq!(s.enc_coderange_scan(), Coderange::SevenBit);
    /// ```
    pub fn enc_coderange_scan(self) -> Coderange {
        unsafe { transmute(rb_enc_str_coderange(self.as_rb_value()) as u32) }
    }

    /// Clear `self`'s cached coderange, setting it to `Unknown`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{encoding::Coderange, prelude::*, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("🦀");
    /// // trigger setting coderange
    /// let _: usize = s.funcall("length", ()).unwrap();
    /// assert_eq!(s.enc_coderange(), Coderange::Valid);
    ///
    /// s.enc_coderange_clear();
    /// assert_eq!(s.enc_coderange(), Coderange::Unknown);
    /// ```
    pub fn enc_coderange_clear(self) {
        unsafe {
            self.r_basic_unchecked().as_mut().flags &=
                !(ruby_coderange_type::RUBY_ENC_CODERANGE_MASK as VALUE)
        }
    }

    /// Sets `self`'s cached coderange.
    ///
    /// Rather than using the method it is recommended to set the coderange to
    /// `Unknown` with [`enc_coderange_clear`](RString::enc_coderange_clear)
    /// and let Ruby determine the coderange lazily when needed.
    ///
    /// # Safety
    ///
    /// This must be set correctly. `SevenBit` if all codepoints are within
    /// 0..=127, `Valid` if the string is valid for its encoding, or `Broken`
    /// if it is not. `Unknown` can be set safely with
    /// [`enc_coderange_clear`](RString::enc_coderange_clear).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{
    ///     encoding::{self, Coderange},
    ///     exception,
    ///     prelude::*,
    ///     Error, RString,
    /// };
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// fn crabbify(s: RString) -> Result<(), Error> {
    ///     if s.enc_get() != encoding::Index::utf8() {
    ///         return Err(Error::new(exception::encoding_error(), "expected utf-8"));
    ///     }
    ///     let original = s.enc_coderange();
    ///     // ::cat() will clear the coderange
    ///     s.cat("🦀");
    ///     // we added a multibyte char, so if we started with `SevenBit` it
    ///     // should be upgraded to `Valid`, and if it was `Valid` it is still
    ///     // `Valid`.
    ///     if original == Coderange::SevenBit || original == Coderange::Valid {
    ///         unsafe {
    ///             s.enc_coderange_set(Coderange::Valid);
    ///         }
    ///     }
    ///     Ok(())
    /// }
    ///
    /// let s = RString::new("test");
    /// // trigger setting coderange
    /// let _: usize = s.funcall("length", ()).unwrap();
    ///
    /// crabbify(s).unwrap();
    /// assert_eq!(s.enc_coderange(), Coderange::Valid);
    /// ```
    pub unsafe fn enc_coderange_set(self, cr: Coderange) {
        self.enc_coderange_clear();
        self.r_basic_unchecked().as_mut().flags |= cr as VALUE;
    }

    /// Returns a Rust `&str` reference to the value of `self`.
    ///
    /// Returns `None` if `self`'s encoding is not UTF-8 (or US-ASCII), or if
    /// the string is not valid UTF-8.
    ///
    /// # Safety
    ///
    /// This is directly viewing memory owned and managed by Ruby. Ruby may
    /// modify or free the memory backing the returned str, the caller must
    /// ensure this does not happen.
    ///
    /// Ruby must not be allowed to garbage collect or modify `self` while a
    /// refrence to the str is held.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("example");
    /// // safe as we don't give Ruby the chance to mess with the string while
    /// // we hold a refrence to the slice.
    /// unsafe { assert_eq!(s.test_as_str().unwrap(), "example") };
    /// ```
    pub unsafe fn test_as_str(&self) -> Option<&str> {
        self.test_as_str_unconstrained()
    }

    /// Returns a Rust `&str` reference to the value of `self`.
    ///
    /// Errors if `self`'s encoding is not UTF-8 (or US-ASCII), or if the
    /// string is not valid UTF-8.
    ///
    /// # Safety
    ///
    /// This is directly viewing memory owned and managed by Ruby. Ruby may
    /// modify or free the memory backing the returned str, the caller must
    /// ensure this does not happen.
    ///
    /// Ruby must not be allowed to garbage collect or modify `self` while a
    /// refrence to the str is held.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("example");
    /// // safe as we don't give Ruby the chance to mess with the string while
    /// // we hold a refrence to the slice.
    /// unsafe { assert_eq!(s.as_str().unwrap(), "example") };
    /// ```
    pub unsafe fn as_str(&self) -> Result<&str, Error> {
        self.as_str_unconstrained()
    }

    unsafe fn test_as_str_unconstrained<'a>(self) -> Option<&'a str> {
        let handle = Ruby::get_with(self);
        let enc = self.enc_get();
        let cr = self.enc_coderange_scan();
        ((self.is_utf8_compatible_encoding()
            && (cr == Coderange::SevenBit || cr == Coderange::Valid))
            || (enc == handle.ascii8bit_encindex() && cr == Coderange::SevenBit))
            .then(|| str::from_utf8_unchecked(self.as_slice_unconstrained()))
    }

    unsafe fn as_str_unconstrained<'a>(self) -> Result<&'a str, Error> {
        self.test_as_str_unconstrained().ok_or_else(|| {
            let msg: Cow<'static, str> = if self.is_utf8_compatible_encoding() {
                format!(
                    "expected utf-8, got {}",
                    RbEncoding::from(self.enc_get()).name()
                )
                .into()
            } else {
                "invalid byte sequence in UTF-8".into()
            };
            Error::new(Ruby::get_with(self).exception_encoding_error(), msg)
        })
    }

    /// Returns `self` as a Rust string, ignoring the Ruby encoding and
    /// dropping any non-UTF-8 characters. If `self` is valid UTF-8 this will
    /// return a `&str` reference.
    ///
    /// # Safety
    ///
    /// This may return a direct view of memory owned and managed by Ruby. Ruby
    /// may modify or free the memory backing the returned str, the caller must
    /// ensure this does not happen.
    ///
    /// Ruby must not be allowed to garbage collect or modify `self` while a
    /// refrence to the str is held.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("example");
    /// // safe as we don't give Ruby the chance to mess with the string while
    /// // we hold a refrence to the slice.
    /// unsafe { assert_eq!(s.to_string_lossy(), "example") };
    /// ```
    #[allow(clippy::wrong_self_convention)]
    pub unsafe fn to_string_lossy(&self) -> Cow<'_, str> {
        String::from_utf8_lossy(self.as_slice())
    }

    /// Returns `self` as an owned Rust `String`. The Ruby string will be
    /// reencoded as UTF-8 if required. Errors if the string can not be encoded
    /// as UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("example");
    /// assert_eq!(s.to_string().unwrap(), "example");
    /// ```
    pub fn to_string(self) -> Result<String, Error> {
        let handle = Ruby::get_with(self);
        let utf8 = if self.is_utf8_compatible_encoding() {
            self
        } else {
            self.conv_enc(handle.utf8_encoding())?
        };
        str::from_utf8(unsafe { utf8.as_slice() })
            .map(ToOwned::to_owned)
            .map_err(|e| Error::new(handle.exception_encoding_error(), format!("{}", e)))
    }

    /// Returns `self` as an owned Rust `Bytes`.
    ///
    /// # Examples
    ///
    /// ```
    /// use bytes::Bytes;
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("example");
    /// assert_eq!(s.to_bytes(), Bytes::from("example"));
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "bytes")))]
    #[cfg(feature = "bytes")]
    pub fn to_bytes(self) -> bytes::Bytes {
        let vec = unsafe { self.as_slice().to_vec() };
        vec.into()
    }

    /// Converts `self` to a [`char`]. Errors if the string is more than one
    /// character or can not be encoded as UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("a");
    /// assert_eq!(s.to_char().unwrap(), 'a');
    /// ```
    pub fn to_char(self) -> Result<char, Error> {
        let handle = Ruby::get_with(self);
        let utf8 = if self.is_utf8_compatible_encoding() {
            self
        } else {
            self.conv_enc(handle.utf8_encoding())?
        };
        unsafe {
            str::from_utf8(utf8.as_slice())
                .map_err(|e| Error::new(handle.exception_encoding_error(), format!("{}", e)))?
                .parse()
                .map_err(|e| {
                    Error::new(
                        handle.exception_type_error(),
                        format!("could not convert string to char, {}", e),
                    )
                })
        }
    }

    /// Returns a quoted version of the `self`.
    ///
    /// This can be thought of as the opposite of `eval`. A string returned
    /// from `dump` can be safely passed to `eval` and will result in a string
    /// with the exact same contents as the original.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("🦀 café");
    /// assert_eq!(
    ///     s.dump().unwrap().to_string().unwrap(),
    ///     r#""\u{1F980} caf\u00E9""#
    /// );
    /// ```
    pub fn dump(self) -> Result<Self, Error> {
        protect(|| unsafe { RString::from_rb_value_unchecked(rb_str_dump(self.as_rb_value())) })
    }

    /// Returns whether `self` is a frozen interned string. Interned strings
    /// are usually string literals with the in files with the
    /// `# frozen_string_literal: true` 'magic comment'.
    ///
    /// Interned strings won't be garbage collected or modified, so should be
    /// safe to store on the heap or hold a `&str` refrence to. See
    /// [`as_interned_str`](RString::as_interned_str).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s: RString = eval!(
    ///     r#"
    ///       ## frozen_string_literal: true
    ///
    ///       "example"
    ///     "#
    /// )
    /// .unwrap();
    /// assert!(s.is_interned());
    /// ```
    ///
    /// ```
    /// use magnus::{eval, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s: RString = eval!(r#""example""#).unwrap();
    /// assert!(!s.is_interned());
    /// ```
    pub fn is_interned(self) -> bool {
        unsafe {
            self.r_basic_unchecked().as_ref().flags & ruby_rstring_flags::RSTRING_FSTR as VALUE != 0
        }
    }

    /// Returns `Some(FString)` if self is interned, `None` otherwise.
    ///
    /// Interned strings won't be garbage collected or modified, so should be
    /// safe to store on the heap or hold a `&str` refrence to. The `FString`
    /// type returned by this function provides a way to encode this property
    /// into the type system, and provides safe methods to access the string
    /// as a `&str` or slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s: RString = eval!(
    ///     r#"
    ///       ## frozen_string_literal: true
    ///
    ///       "example"
    ///     "#
    /// )
    /// .unwrap();
    /// assert!(s.as_interned_str().is_some());
    /// ```
    ///
    /// ```
    /// use magnus::{eval, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s: RString = eval!(r#""example""#).unwrap();
    /// assert!(s.as_interned_str().is_none());
    /// ```
    pub fn as_interned_str(self) -> Option<FString> {
        self.is_interned().then(|| FString(self))
    }

    /// Interns self and returns a [`FString`]. Be aware that once interned a
    /// string will never be garbage collected.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let fstring = RString::new("example").to_interned_str();
    /// assert_eq!(fstring.as_str().unwrap(), "example");
    /// ```
    #[cfg(any(ruby_gte_3_0, docsrs))]
    #[cfg_attr(docsrs, doc(cfg(ruby_gte_3_0)))]
    pub fn to_interned_str(self) -> FString {
        unsafe {
            FString(RString::from_rb_value_unchecked(rb_str_to_interned_str(
                self.as_rb_value(),
            )))
        }
    }

    /// Mutate `self`, adding `other` to the end. Errors if `self` and
    /// `other`'s encodings are not compatible.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let a = RString::new("foo");
    /// let b = RString::new("bar");
    /// a.buf_append(b).unwrap();
    /// assert_eq!(a.to_string().unwrap(), "foobar");
    /// ```
    pub fn buf_append(self, other: Self) -> Result<(), Error> {
        protect(|| unsafe {
            Value::new(rb_str_buf_append(self.as_rb_value(), other.as_rb_value()))
        })?;
        Ok(())
    }

    /// Mutate `self`, adding `buf` to the end.
    ///
    /// Note: This ignore's `self`'s encoding, and may result in `self`
    /// containing invalid bytes for its encoding. It's assumed this will more
    /// often be used with ASCII-8BIT (aka BINARY) encoded strings. See
    /// [`buf_new`](RString::buf_new) and [`from_slice`](RString::from_slice).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let buf = RString::buf_new(4096);
    /// buf.cat(&[102, 111, 111]);
    /// buf.cat("bar");
    /// assert_eq!(buf.to_string().unwrap(), "foobar");
    /// ```
    pub fn cat<T: AsRef<[u8]>>(self, buf: T) {
        let buf = buf.as_ref();
        let len = buf.len();
        let ptr = buf.as_ptr();
        unsafe {
            rb_str_cat(self.as_rb_value(), ptr as *const c_char, len as c_long);
        }
    }

    /// Replace the contents and encoding of `self` with those of `other`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let a = RString::new("foo");
    /// let b = RString::new("bar");
    /// a.replace(b).unwrap();
    /// assert_eq!(a.to_string().unwrap(), "bar");
    /// ```
    pub fn replace(self, other: Self) -> Result<(), Error> {
        protect(|| {
            unsafe { rb_str_replace(self.as_rb_value(), other.as_rb_value()) };
            Ruby::get_with(self).qnil()
        })?;
        Ok(())
    }

    /// Modify `self` to share the same backing data as `other`.
    ///
    /// Both string objects will point at the same underlying data until one is
    /// modified, and only then will the data be duplicated.
    ///
    /// See also [`replace`](RString::replace) and
    /// [`new_shared`](RString::new_shared).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let a = RString::new("foo");
    /// let b = RString::new("bar");
    /// a.shared_replace(b).unwrap();
    /// assert_eq!(a.to_string().unwrap(), "bar");
    /// // mutating one doesn't mutate both
    /// b.cat("foo");
    /// assert_eq!(a.to_string().unwrap(), "bar");
    /// ```
    pub fn shared_replace(self, other: Self) -> Result<(), Error> {
        protect(|| {
            unsafe { rb_str_shared_replace(self.as_rb_value(), other.as_rb_value()) };
            Ruby::get_with(self).qnil()
        })?;
        Ok(())
    }

    /// Replace a portion of `self` with `other`.
    ///
    /// `beg` is the offset of the portion of `self` to replace. Negative
    /// values offset from the end of the string.
    /// `len` is the length of the portion of `self` to replace. It does not
    /// need to match the length of `other`, `self` will be expanded or
    /// contracted as needed to accomdate `other`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("foo");
    /// s.update(-1, 1, RString::new("x")).unwrap();
    /// assert_eq!(s.to_string().unwrap(), "fox");
    ///
    /// let s = RString::new("splat");
    /// s.update(0, 3, RString::new("b")).unwrap();
    /// assert_eq!(s.to_string().unwrap(), "bat");
    ///
    /// let s = RString::new("corncob");
    /// s.update(1, 5, RString::new("ra")).unwrap();
    /// assert_eq!(s.to_string().unwrap(), "crab");
    /// ```
    pub fn update(self, beg: isize, len: usize, other: Self) -> Result<(), Error> {
        protect(|| {
            unsafe {
                rb_str_update(
                    self.as_rb_value(),
                    beg as c_long,
                    len as c_long,
                    other.as_rb_value(),
                )
            };
            Ruby::get_with(self).qnil()
        })?;
        Ok(())
    }

    /// Create a new string by appending `other` to `self`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let a = RString::new("foo");
    /// let b = RString::new("bar");
    /// assert_eq!(a.plus(b).unwrap().to_string().unwrap(), "foobar");
    /// assert_eq!(a.to_string().unwrap(), "foo");
    /// assert_eq!(b.to_string().unwrap(), "bar");
    /// ```
    pub fn plus(self, other: Self) -> Result<Self, Error> {
        protect(|| unsafe {
            Self::from_rb_value_unchecked(rb_str_plus(self.as_rb_value(), other.as_rb_value()))
        })
    }

    /// Create a new string by repeating `self` `num` times.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// assert_eq!(
    ///     RString::new("foo").times(3).to_string().unwrap(),
    ///     "foofoofoo"
    /// );
    /// ```
    pub fn times(self, num: usize) -> Self {
        let num = Ruby::get_with(self).into_value(num);
        unsafe {
            Self::from_rb_value_unchecked(rb_str_times(self.as_rb_value(), num.as_rb_value()))
        }
    }

    /// Shrink `self` by `len` bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("foobar");
    /// s.drop_bytes(3).unwrap();
    /// assert_eq!(s.to_string().unwrap(), "bar");
    /// ```
    pub fn drop_bytes(self, len: usize) -> Result<(), Error> {
        protect(|| {
            unsafe { rb_str_drop_bytes(self.as_rb_value(), len as c_long) };
            Ruby::get_with(self).qnil()
        })?;
        Ok(())
    }

    /// Returns the number of bytes in `self`.
    ///
    /// See also [`length`](RString::length).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("🦀 Hello, Ferris");
    /// assert_eq!(s.len(), 18);
    /// ```
    pub fn len(self) -> usize {
        debug_assert_value!(self);
        unsafe { RSTRING_LEN(self.as_rb_value()) as usize }
    }

    /// Returns the number of characters in `self`.
    ///
    /// See also [`len`](RString::len).
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("🦀 Hello, Ferris");
    /// assert_eq!(s.length(), 15);
    /// ```
    pub fn length(self) -> usize {
        unsafe { rb_str_strlen(self.as_rb_value()) as usize }
    }

    /// Returns the capacity of `self`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::with_capacity(9);
    /// s.cat("foo");
    /// assert_eq!(3, s.len());
    /// assert!(s.capacity() >= 9);
    /// ```
    pub fn capacity(self) -> usize {
        unsafe { rb_str_capacity(self.as_rb_value()) as usize }
    }

    /// Return whether self contains any characters or not.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("");
    /// assert!(s.is_empty());
    /// ```
    pub fn is_empty(self) -> bool {
        self.len() == 0
    }

    /// Compares `self` with `other` to establish an ordering.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::cmp::Ordering;
    ///
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let a = RString::new("a");
    /// let b = RString::new("b");
    /// assert_eq!(Ordering::Less, a.cmp(b));
    /// ```
    ///
    /// Note that `std::cmp::Ordering` can be cast to `i{8,16,32,64,size}` to
    /// get the Ruby standard `-1`/`0`/`+1` for comparison results.
    ///
    /// ```
    /// assert_eq!(std::cmp::Ordering::Less as i64, -1);
    /// assert_eq!(std::cmp::Ordering::Equal as i64, 0);
    /// assert_eq!(std::cmp::Ordering::Greater as i64, 1);
    /// ```
    #[allow(clippy::should_implement_trait)]
    pub fn cmp(self, other: Self) -> Ordering {
        unsafe { rb_str_cmp(self.as_rb_value(), other.as_rb_value()) }.cmp(&0)
    }

    /// Returns whether there is a total order of strings in the encodings of
    /// `self` and `other`.
    ///
    /// If this function returns `true` for `self` and `other` then the
    /// ordering returned from [`cmp`](RString::cmp) for those strings is
    /// 'correct'. If `false`, while stable, the ordering may not follow
    /// established rules.
    pub fn comparable(self, other: Self) -> bool {
        unsafe { rb_str_comparable(self.as_rb_value(), other.as_rb_value()) != 0 }
    }

    /// Shorten `self` to `len`, adding "...".
    ///
    /// If `self` is shorter than `len` the returned value will be `self`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::RString;
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new("foobarbaz");
    /// assert_eq!(s.ellipsize(6).to_string().unwrap(), "foo...");
    /// ```
    pub fn ellipsize(self, len: usize) -> Self {
        unsafe {
            RString::from_rb_value_unchecked(rb_str_ellipsize(self.as_rb_value(), len as c_long))
        }
    }

    /// Split `self` around the given delimiter.
    ///
    /// If `delim` is an empty string then `self` is split into characters.
    /// If `delim` is solely whitespace then `self` is split around whitespace,
    /// with leading, trailing, and runs of contiguous whitespace ignored.
    /// Otherwise, `self` is split around `delim`.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{prelude::*, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s = RString::new(" foo  bar  baz ");
    /// assert_eq!(
    ///     Vec::<String>::try_convert(s.split("").as_value()).unwrap(),
    ///     vec![" ", "f", "o", "o", " ", " ", "b", "a", "r", " ", " ", "b", "a", "z", " "]
    /// );
    /// assert_eq!(
    ///     Vec::<String>::try_convert(s.split(" ").as_value()).unwrap(),
    ///     vec!["foo", "bar", "baz"]
    /// );
    /// assert_eq!(
    ///     Vec::<String>::try_convert(s.split(" bar ").as_value()).unwrap(),
    ///     vec![" foo ", " baz "]
    /// );
    /// ```
    pub fn split(self, delim: &str) -> RArray {
        let delim = CString::new(delim).unwrap();
        unsafe { RArray::from_rb_value_unchecked(rb_str_split(self.as_rb_value(), delim.as_ptr())) }
    }
}

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

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

impl EncodingCapable for RString {}

impl io::Write for RString {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let len = buf.len();
        self.cat(buf);
        Ok(len)
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

/// Conversions from Rust types into [`RString`].
pub trait IntoRString: Sized {
    /// Convert `self` into [`RString`].
    ///
    /// # Panics
    ///
    /// Panics if called from a non-Ruby thread. See
    /// [`IntoRString::into_r_string_with`] for the non-panicking version.
    #[cfg_attr(
        not(feature = "friendly-api"),
        deprecated(note = "please use `IntoRString::into_r_string_with` instead")
    )]
    #[inline]
    fn into_r_string(self) -> RString {
        self.into_r_string_with(&get_ruby!())
    }

    /// Convert `self` into [`RString`].
    ///
    /// # Safety
    ///
    /// This method should only be called from a Ruby thread.
    unsafe fn into_r_string_unchecked(self) -> RString {
        self.into_r_string_with(&Ruby::get_unchecked())
    }

    /// Convert `self` into [`RString`].
    fn into_r_string_with(self, handle: &Ruby) -> RString;
}

impl IntoRString for RString {
    fn into_r_string_with(self, _: &Ruby) -> RString {
        self
    }
}

impl IntoRString for &str {
    fn into_r_string_with(self, handle: &Ruby) -> RString {
        handle.str_new(self)
    }
}

impl IntoRString for String {
    fn into_r_string_with(self, handle: &Ruby) -> RString {
        handle.str_new(&self)
    }
}

#[cfg(unix)]
impl IntoRString for &Path {
    fn into_r_string_with(self, handle: &Ruby) -> RString {
        use std::os::unix::ffi::OsStrExt;
        handle.str_from_slice(self.as_os_str().as_bytes())
    }
}

#[cfg(windows)]
impl IntoRString for &Path {
    fn into_r_string_with(self, handle: &Ruby) -> RString {
        use std::os::windows::ffi::OsStrExt;
        if let Some(utf16) = handle.find_encoding("UTF-16LE") {
            let bytes: Vec<u8> = self
                .as_os_str()
                .encode_wide()
                .flat_map(|c| c.to_le_bytes())
                .collect();
            handle.enc_str_new(bytes, utf16)
        } else {
            handle.str_new(self.to_string_lossy().as_ref())
        }
    }
}

#[cfg(not(any(unix, windows)))]
impl IntoRString for &Path {
    fn into_r_string_with(self, handle: &Ruby) -> RString {
        handle.str_new(self.to_string_lossy().as_ref())
    }
}

impl IntoRString for PathBuf {
    fn into_r_string_with(self, handle: &Ruby) -> RString {
        self.as_path().into_r_string_with(handle)
    }
}

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

impl IntoValue for &str {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.str_new(self).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for &str {}

#[cfg(feature = "bytes")]
impl IntoValue for bytes::Bytes {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.str_from_slice(self.as_ref()).into_value_with(handle)
    }
}

impl IntoValue for String {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.str_new(self.as_str()).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for String {}

impl IntoValue for char {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        handle.str_from_char(self).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for char {}

impl IntoValue for &Path {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        self.into_r_string_with(handle).into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for &Path {}

impl IntoValue for PathBuf {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        self.as_path()
            .into_r_string_with(handle)
            .into_value_with(handle)
    }
}

unsafe impl IntoValueFromNative for PathBuf {}

impl Object for RString {}

unsafe impl private::ReprValue for RString {}

impl ReprValue for RString {}

impl TryConvert for RString {
    fn try_convert(val: Value) -> Result<Self, Error> {
        match Self::from_value(val) {
            Some(i) => Ok(i),
            None => protect(|| {
                debug_assert_value!(val);
                unsafe { Self::from_rb_value_unchecked(rb_str_to_str(val.as_rb_value())) }
            }),
        }
    }
}

/// FString contains an RString known to be interned.
///
/// Interned strings won't be garbage collected or modified, so should be
/// safe to store on the heap or hold a `&str` refrence to. `FString` provides
/// a way to encode this property into the type system, and provides safe
/// methods to access the string as a `&str` or slice.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct FString(RString);

impl FString {
    /// Returns the interned string as a [`RString`].
    pub fn as_r_string(self) -> RString {
        self.0
    }

    /// Returns the interned string as a slice of bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s: RString = eval!(
    ///     r#"
    ///       ## frozen_string_literal: true
    ///
    ///       "example"
    ///     "#
    /// )
    /// .unwrap();
    /// let fstring = s.as_interned_str().unwrap();
    /// assert_eq!(fstring.as_slice(), &[101, 120, 97, 109, 112, 108, 101]);
    /// ```
    pub fn as_slice(self) -> &'static [u8] {
        unsafe { self.as_r_string().as_slice_unconstrained() }
    }

    /// Returns the interned string as a `&str` or `None` string contains
    /// invliad UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s: RString = eval!(
    ///     r#"
    ///       ## frozen_string_literal: true
    ///
    ///       "example"
    ///     "#
    /// )
    /// .unwrap();
    /// let fstring = s.as_interned_str().unwrap();
    /// assert_eq!(fstring.test_as_str().unwrap(), "example");
    /// ```
    pub fn test_as_str(self) -> Option<&'static str> {
        unsafe { self.as_r_string().test_as_str_unconstrained() }
    }

    /// Returns the interned string as a `&str`. Errors if the string contains
    /// invliad UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s: RString = eval!(
    ///     r#"
    ///       ## frozen_string_literal: true
    ///
    ///       "example"
    ///     "#
    /// )
    /// .unwrap();
    /// let fstring = s.as_interned_str().unwrap();
    /// assert_eq!(fstring.as_str().unwrap(), "example");
    /// ```
    pub fn as_str(self) -> Result<&'static str, Error> {
        unsafe { self.as_r_string().as_str_unconstrained() }
    }

    /// Returns interned string as a Rust string, ignoring the Ruby encoding
    /// and dropping any non-UTF-8 characters. If the string is valid UTF-8
    /// this will return a `&str` reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use magnus::{eval, RString};
    /// # let _cleanup = unsafe { magnus::embed::init() };
    ///
    /// let s: RString = eval!(
    ///     r#"
    ///       ## frozen_string_literal: true
    ///
    ///       "example"
    ///     "#
    /// )
    /// .unwrap();
    /// let fstring = s.as_interned_str().unwrap();
    /// assert_eq!(fstring.to_string_lossy(), "example");
    /// ```
    pub fn to_string_lossy(self) -> Cow<'static, str> {
        String::from_utf8_lossy(self.as_slice())
    }
}

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

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

impl IntoValue for FString {
    #[inline]
    fn into_value_with(self, handle: &Ruby) -> Value {
        self.as_r_string().into_value_with(handle)
    }
}

unsafe impl private::ReprValue for FString {}

impl ReprValue for FString {}

/// An iterator over a Ruby string's codepoints.
pub struct Codepoints<'a> {
    slice: &'a [u8],
    encoding: RbEncoding,
}

impl<'a> Iterator for Codepoints<'a> {
    type Item = Result<u32, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.slice.is_empty() {
            return None;
        }
        match self.encoding.codepoint_len(self.slice) {
            Ok((codepoint, len)) => {
                self.slice = &self.slice[len..];
                Some(Ok(codepoint))
            }
            Err(e) => {
                self.slice = &self.slice[self.slice.len()..];
                Some(Err(e))
            }
        }
    }
}

/// An iterator over a Ruby string's chars as slices of bytes.
pub struct CharBytes<'a> {
    slice: &'a [u8],
    encoding: RbEncoding,
}

impl<'a> Iterator for CharBytes<'a> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<Self::Item> {
        if self.slice.is_empty() {
            return None;
        }
        let len = self.encoding.mbclen(self.slice);
        let bytes = &self.slice[..len];
        self.slice = &self.slice[len..];
        Some(bytes)
    }
}

/// Create a [`RString`] from a Rust str literal.
///
/// # Panics
///
/// Panics if called from a non-Ruby thread.
///
/// # Examples
///
/// ```
/// use magnus::{r_string, rb_assert};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let s = r_string!("Hello, world!");
/// rb_assert!(r#"s == "Hello, world!""#, s);
/// ```
#[macro_export]
macro_rules! r_string {
    ($lit:expr) => {{
        $crate::r_string!($crate::Ruby::get().unwrap(), $lit)
    }};
    ($ruby:expr, $lit:expr) => {{
        let s = concat!($lit, "\0");
        let len = s.len() - 1;
        unsafe { $ruby.str_new_lit(s.as_ptr() as *const _, len as _) }
    }};
}