spinoso_string/lib.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 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 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![cfg_attr(test, allow(clippy::non_ascii_literal))]
#![allow(unknown_lints)]
#![allow(clippy::manual_let_else)]
#![allow(clippy::module_name_repetitions)]
// TODO: warn on missing docs once crate is API-complete.
// #![warn(missing_docs)]
#![warn(missing_debug_implementations)]
#![warn(missing_copy_implementations)]
#![warn(rust_2018_idioms)]
#![warn(rust_2021_compatibility)]
#![warn(trivial_casts, trivial_numeric_casts)]
#![warn(unused_qualifications)]
#![warn(variant_size_differences)]
// Enable feature callouts in generated documentation:
// https://doc.rust-lang.org/beta/unstable-book/language-features/doc-cfg.html
//
// This approach is borrowed from tokio.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, feature(doc_alias))]
//! A String object holds and manipulates an arbitrary sequence of bytes,
//! typically representing characters.
#![no_std]
// Ensure code blocks in `README.md` compile
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme {}
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
use alloc::boxed::Box;
use alloc::collections::TryReserveError;
use alloc::vec::Vec;
#[cfg(feature = "casecmp")]
use core::cmp::Ordering;
use core::fmt;
use core::ops::Range;
use core::slice::SliceIndex;
use core::str;
use bstr::ByteSlice;
#[doc(inline)]
#[cfg(feature = "casecmp")]
#[cfg_attr(docsrs, doc(cfg(feature = "casecmp")))]
pub use focaccia::CaseFold;
use scolapasta_strbuf::Buf;
#[doc(inline)]
pub use scolapasta_strbuf::RawParts;
mod center;
mod chars;
mod codepoints;
mod enc;
mod encoding;
mod eq;
mod impls;
mod inspect;
mod iter;
mod ord;
pub use center::{Center, CenterError};
pub use chars::Chars;
pub use codepoints::{Codepoints, CodepointsError, InvalidCodepointError};
use enc::EncodedString;
pub use encoding::{Encoding, InvalidEncodingError};
pub use inspect::Inspect;
pub use iter::{Bytes, IntoIter, Iter, IterMut};
pub use ord::OrdError;
#[derive(Default, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct String {
inner: EncodedString,
}
impl fmt::Debug for String {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("String")
.field("buf", &self.inner.as_slice().as_bstr())
.field("encoding", &self.inner.encoding())
.finish()
}
}
// Constructors
impl String {
/// Constructs a new, empty `String`.
///
/// The `String` is [conventionally UTF-8].
///
/// The string will not allocate until bytes are pushed onto it.
///
/// # Examples
///
/// ```
/// use spinoso_string::{Encoding, String};
///
/// let s = String::new();
/// assert_eq!(s.encoding(), Encoding::Utf8);
/// ```
///
/// [conventionally UTF-8]: crate::Encoding::Utf8
#[inline]
#[must_use]
pub fn new() -> Self {
let buf = Buf::new();
let inner = EncodedString::utf8(buf);
Self { inner }
}
/// Constructs a new, empty `String` with the specified capacity.
///
/// The `String` is [conventionally UTF-8].
///
/// The string will be able to hold at least `capacity` bytes without
/// reallocating. If `capacity` is 0, the string will not allocate.
///
/// It is important to note that although the returned string has the
/// capacity specified, the string will have a zero length. For an
/// explanation of the difference between length and capacity, see
/// *[Capacity and reallocation]*.
///
/// # Examples
///
/// Encoding, capacity, and length:
///
/// ```
/// use spinoso_string::{Encoding, String};
///
/// let s = String::with_capacity(10);
/// assert_eq!(s.encoding(), Encoding::Utf8);
/// assert!(s.capacity() >= 10);
/// assert_eq!(s.len(), 0);
/// ```
///
/// Allocation:
///
/// ```
/// use spinoso_string::{Encoding, String};
///
/// let mut s = String::with_capacity(10);
///
/// for ch in 'a'..='j' {
/// s.push_byte(ch as u8);
/// }
/// // 10 elements have been inserted without reallocating.
/// assert!(s.capacity() >= 10);
/// assert_eq!(s.len(), 10);
/// ```
///
/// [conventionally UTF-8]: crate::Encoding::Utf8
/// [Capacity and reallocation]: https://doc.rust-lang.org/std/vec/struct.Vec.html#capacity-and-reallocation
#[inline]
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
let buf = Buf::with_capacity(capacity);
let inner = EncodedString::utf8(buf);
Self { inner }
}
/// Constructs a new, empty `String` with the specified capacity and
/// encoding.
///
/// The string will be able to hold at least `capacity` bytes without
/// reallocating. If `capacity` is 0, the string will not allocate.
///
/// It is important to note that although the returned string has the
/// capacity specified, the string will have a zero length. For an
/// explanation of the difference between length and capacity, see
/// *[Capacity and reallocation]*.
///
/// # Examples
///
/// Encoding, capacity, and length:
///
/// ```
/// use spinoso_string::{Encoding, String};
///
/// let s = String::with_capacity(10);
/// assert_eq!(s.encoding(), Encoding::Utf8);
/// assert!(s.capacity() >= 10);
/// assert_eq!(s.len(), 0);
/// ```
///
/// Allocation:
///
/// ```
/// use spinoso_string::{Encoding, String};
///
/// let mut s = String::with_capacity_and_encoding(10, Encoding::Binary);
/// assert_eq!(s.encoding(), Encoding::Binary);
///
/// for ch in 'a'..='j' {
/// s.push_byte(ch as u8);
/// }
/// // 10 elements have been inserted without reallocating.
/// assert!(s.capacity() >= 10);
/// assert_eq!(s.len(), 10);
/// ```
///
/// [Capacity and reallocation]: https://doc.rust-lang.org/std/vec/struct.Vec.html#capacity-and-reallocation
#[inline]
#[must_use]
pub fn with_capacity_and_encoding(capacity: usize, encoding: Encoding) -> Self {
let buf = Buf::with_capacity(capacity);
let inner = EncodedString::new(buf, encoding);
Self { inner }
}
#[inline]
#[must_use]
pub fn with_bytes_and_encoding(buf: Vec<u8>, encoding: Encoding) -> Self {
let inner = EncodedString::new(buf.into(), encoding);
Self { inner }
}
#[inline]
#[must_use]
pub fn utf8(buf: Vec<u8>) -> Self {
let inner = EncodedString::utf8(buf.into());
Self { inner }
}
#[inline]
#[must_use]
pub fn ascii(buf: Vec<u8>) -> Self {
let inner = EncodedString::ascii(buf.into());
Self { inner }
}
#[inline]
#[must_use]
pub fn binary(buf: Vec<u8>) -> Self {
let inner = EncodedString::binary(buf.into());
Self { inner }
}
}
// Core data structure manipulation
impl String {
/// Returns the [`Encoding`] of this `String`.
///
/// # Examples
///
/// ```
/// use spinoso_string::{Encoding, String};
///
/// let s = String::utf8(b"xyz".to_vec());
/// assert_eq!(s.encoding(), Encoding::Utf8);
/// ```
#[inline]
#[must_use]
pub fn encoding(&self) -> Encoding {
self.inner.encoding()
}
/// Set the [`Encoding`] of this `String`.
///
/// # Examples
///
/// ```
/// use spinoso_string::{Encoding, String};
///
/// let mut s = String::utf8(b"xyz".to_vec());
/// assert_eq!(s.encoding(), Encoding::Utf8);
/// s.set_encoding(Encoding::Binary);
/// assert_eq!(s.encoding(), Encoding::Binary);
/// ```
#[inline]
pub fn set_encoding(&mut self, encoding: Encoding) {
self.inner.set_encoding(encoding);
}
/// Shortens the string, keeping the first `len` bytes and dropping the
/// rest.
///
/// If `len` is greater than the string's current length, this has no
/// effect.
///
/// Note that this method has no effect on the allocated capacity
/// of the string.
///
/// # Examples
///
/// Truncating a five byte to two elements:
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::from("12345");
/// s.truncate(2);
/// assert_eq!(*s, *b"12");
/// ```
///
/// No truncation occurs when `len` is greater than the string's current
/// length:
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::from("12345");
/// s.truncate(10);
/// assert_eq!(*s, *b"12345");
/// ```
///
/// Truncating when `len == 0` is equivalent to calling the [`clear`]
/// method.
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::from("12345");
/// s.truncate(0);
/// assert_eq!(*s, *b"");
/// ```
///
/// [`clear`]: Self::clear
#[inline]
pub fn truncate(&mut self, len: usize) {
self.inner.truncate(len);
}
/// Extracts a slice containing the entire byte string.
///
/// Equivalent to `&s[..]`.
#[inline]
#[must_use]
pub fn as_slice(&self) -> &[u8] {
self.inner.as_slice()
}
/// Extracts a mutable slice containing the entire byte string.
///
/// Equivalent to `&mut s[..]`.
#[inline]
#[must_use]
pub fn as_mut_slice(&mut self) -> &mut [u8] {
self.inner.as_mut_slice()
}
/// Returns a raw pointer to the string's buffer.
///
/// The caller must ensure that the string outlives the pointer this
/// function returns, or else it will end up pointing to garbage. Modifying
/// the string may cause its buffer to be reallocated, which would also make
/// any pointers to it invalid.
///
/// The caller must also ensure that the memory the pointer
/// (non-transitively) points to is never written to (except inside an
/// `UnsafeCell`) using this pointer or any pointer derived from it. If you
/// need to mutate the contents of the slice, use [`as_mut_ptr`].
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::utf8(b"xyz".to_vec());
/// let s_ptr = s.as_ptr();
///
/// unsafe {
/// for i in 0..s.len() {
/// assert_eq!(*s_ptr.add(i), b'x' + (i as u8));
/// }
/// }
/// ```
///
/// [`as_mut_ptr`]: Self::as_mut_ptr
#[inline]
#[must_use]
pub fn as_ptr(&self) -> *const u8 {
self.inner.as_ptr()
}
/// Returns an unsafe mutable pointer to the string's buffer.
///
/// The caller must ensure that the string outlives the pointer this
/// function returns, or else it will end up pointing to garbage. Modifying
/// the string may cause its buffer to be reallocated, which would also make
/// any pointers to it invalid.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// // Allocate string big enough for 3 bytes.
/// let size = 3;
/// let mut s = String::with_capacity(size);
/// let s_ptr = s.as_mut_ptr();
///
/// // Initialize elements via raw pointer writes, then set length.
/// unsafe {
/// for i in 0..size {
/// *s_ptr.add(i) = b'x' + (i as u8);
/// }
/// s.set_len(size);
/// }
/// assert_eq!(&*s, b"xyz");
/// ```
#[inline]
#[must_use]
pub fn as_mut_ptr(&mut self) -> *mut u8 {
self.inner.as_mut_ptr()
}
/// Forces the length of the string to `new_len`.
///
/// This is a low-level operation that maintains none of the normal
/// invariants of the type. Normally changing the length of a string is done
/// using one of the safe operations instead, such as [`truncate`],
/// [`extend`], or [`clear`].
///
/// This function can change the return value of [`String::is_valid_encoding`].
///
/// # Safety
///
/// - `new_len` must be less than or equal to [`capacity()`].
/// - The elements at `old_len..new_len` must be initialized.
///
/// [`truncate`]: Self::truncate
/// [`extend`]: Extend::extend
/// [`clear`]: Self::clear
/// [`capacity()`]: Self::capacity
#[inline]
pub unsafe fn set_len(&mut self, new_len: usize) {
self.inner.set_len(new_len);
}
/// Creates a `String` directly from the raw components of another string.
///
/// # Safety
///
/// This is highly unsafe, due to the number of invariants that aren't
/// checked:
///
/// - `ptr` needs to have been previously allocated via `String` (at least,
/// it's highly likely to be incorrect if it wasn't).
/// - `length` needs to be less than or equal to `capacity`.
/// - `capacity` needs to be the `capacity` that the pointer was allocated
/// with.
///
/// Violating these may cause problems like corrupting the allocator's
/// internal data structures.
///
/// The ownership of `ptr` is effectively transferred to the `String` which
/// may then deallocate, reallocate or change the contents of memory pointed
/// to by the pointer at will. Ensure that nothing else uses the pointer
/// after calling this function.
#[must_use]
pub unsafe fn from_raw_parts(raw_parts: RawParts<u8>) -> Self {
Self::utf8(raw_parts.into_vec())
}
/// Creates a `String` directly from the raw components of another string
/// with the specified encoding.
///
/// # Safety
///
/// This is highly unsafe, due to the number of invariants that aren't
/// checked:
///
/// - `ptr` needs to have been previously allocated via `String` (at least,
/// it's highly likely to be incorrect if it wasn't).
/// - `length` needs to be less than or equal to `capacity`.
/// - `capacity` needs to be the `capacity` that the pointer was allocated
/// with.
///
/// Violating these may cause problems like corrupting the allocator's
/// internal data structures.
///
/// The ownership of `ptr` is effectively transferred to the `String` which
/// may then deallocate, reallocate or change the contents of memory pointed
/// to by the pointer at will. Ensure that nothing else uses the pointer
/// after calling this function.
#[must_use]
pub unsafe fn from_raw_parts_with_encoding(raw_parts: RawParts<u8>, encoding: Encoding) -> Self {
Self::with_bytes_and_encoding(raw_parts.into_vec(), encoding)
}
/// Decomposes a `String` into its raw components.
///
/// Returns the raw pointer to the underlying data, the length of the string
/// (in bytes), and the allocated capacity of the data (in bytes). These
/// are the same arguments in the same order as the arguments to
/// [`from_raw_parts`].
///
/// After calling this function, the caller is responsible for the memory
/// previously managed by the `String`. The only way to do this is to
/// convert the raw pointer, length, and capacity back into a `String` with
/// the [`from_raw_parts`] function, allowing the destructor to perform the
/// cleanup.
///
/// [`from_raw_parts`]: String::from_raw_parts
#[must_use]
pub fn into_raw_parts(self) -> RawParts<u8> {
self.inner.into_buf().into_raw_parts()
}
/// Converts self into a vector without clones or allocation.
///
/// This method consumes this `String` and returns its inner [`Vec<u8>`]
/// buffer.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::from("hello");
/// let buf = s.into_vec();
/// // `s` cannot be used anymore because it has been converted into `buf`.
///
/// assert_eq!(buf, b"hello".to_vec());
/// ```
/// [`Vec<u8>`]: alloc::vec::Vec
#[inline]
#[must_use]
pub fn into_vec(self) -> Vec<u8> {
self.inner.into_buf().into_inner()
}
/// Converts the vector into `Box<[u8]>`.
///
/// Note that this will drop any excess capacity.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::from("abc");
/// let slice = s.into_boxed_slice();
/// ```
///
/// Any excess capacity is removed:
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::with_capacity(10);
/// s.extend_from_slice(&[b'a', b'b', b'c']);
///
/// assert!(s.capacity() >= 10);
/// let slice = s.into_boxed_slice();
/// assert_eq!(slice.into_vec().capacity(), 3);
/// ```
///
/// [`Box<u8>`]: alloc::boxed::Box
#[inline]
#[must_use]
pub fn into_boxed_slice(self) -> Box<[u8]> {
self.inner.into_buf().into_boxed_slice()
}
/// Returns the number of bytes the string can hold without reallocating.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::with_capacity(10);
/// assert!(s.capacity() >= 10);
/// ```
#[inline]
#[must_use]
pub fn capacity(&self) -> usize {
self.inner.capacity()
}
/// Clears the string, removing all bytes.
///
/// Note that this method has no effect on the allocated capacity or the
/// encoding of the string.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::from("abc");
/// s.clear();
/// assert!(s.is_empty());
/// ```
#[inline]
pub fn clear(&mut self) {
self.inner.clear();
}
/// Returns true if the vector contains no bytes.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::new();
/// assert!(s.is_empty());
///
/// s.push_char('x');
/// assert!(!s.is_empty());
/// ```
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
/// Returns the number of bytes in the string, also referred to as its
/// "length" or "bytesize".
///
/// See also [`bytesize`].
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::from("xyz");
/// assert_eq!(s.len(), 3);
/// ```
///
/// [`bytesize`]: Self::bytesize
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.inner.len()
}
}
// Core iterators
impl String {
/// Returns an iterator over this string's underlying byte slice.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::from("abc");
/// let mut iterator = s.iter();
///
/// assert_eq!(iterator.next(), Some(&b'a'));
/// assert_eq!(iterator.next(), Some(&b'b'));
/// assert_eq!(iterator.next(), Some(&b'c'));
/// assert_eq!(iterator.next(), None);
/// ```
#[inline]
#[must_use]
pub fn iter(&self) -> Iter<'_> {
self.inner.iter()
}
/// Returns an iterator that allows modifying this string's underlying byte
/// slice.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::from("abc");
///
/// for byte in s.iter_mut() {
/// *byte = b'x';
/// }
///
/// assert_eq!(s, "xxx");
/// ```
#[inline]
#[must_use]
pub fn iter_mut(&mut self) -> IterMut<'_> {
self.inner.iter_mut()
}
/// Returns an iterator over the bytes in this byte string.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::utf8(b"foobar".to_vec());
/// let bytes: Vec<u8> = s.bytes().collect();
/// assert_eq!(bytes, s);
/// ```
#[inline]
#[must_use]
pub fn bytes(&self) -> Bytes<'_> {
self.inner.bytes()
}
}
// Additional `IntoIterator` iterator
impl IntoIterator for String {
type Item = u8;
type IntoIter = IntoIter;
/// Returns an iterator that moves over the bytes of this string.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::from("abc");
///
/// let mut iterator = s.into_iter();
///
/// assert_eq!(iterator.next(), Some(b'a'));
/// assert_eq!(iterator.next(), Some(b'b'));
/// assert_eq!(iterator.next(), Some(b'c'));
/// assert_eq!(iterator.next(), None);
/// ```
#[inline]
#[must_use]
fn into_iter(self) -> Self::IntoIter {
self.inner.into_iter()
}
}
impl<'a> IntoIterator for &'a String {
type Item = &'a u8;
type IntoIter = Iter<'a>;
/// Returns a borrowing iterator that moves over the bytes of this string.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::from("abc");
///
/// for &b in &s {
/// assert_eq!(b, b'a');
/// break;
/// }
/// ```
#[inline]
#[must_use]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a> IntoIterator for &'a mut String {
type Item = &'a mut u8;
type IntoIter = IterMut<'a>;
/// Returns a borrowing iterator that mutably moves over the bytes of this
/// string.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::from("abc");
///
/// for b in &mut s {
/// *b = b'1';
/// }
///
/// assert_eq!(s, b"111");
/// ```
#[inline]
#[must_use]
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
// Memory management
impl String {
/// Reserves capacity for at least `additional` more bytes to be inserted in
/// the given `String`. The string may reserve more space to avoid frequent
/// reallocations. After calling `reserve`, capacity will be greater than or
/// equal to `self.len() + additional`. Does nothing if capacity is already
/// sufficient.
///
/// # Panics
///
/// Panics if the new capacity exceeds [`isize::MAX`] bytes.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::from("x");
/// s.reserve(10);
/// assert!(s.capacity() >= 11);
/// ```
#[inline]
pub fn reserve(&mut self, additional: usize) {
self.inner.reserve(additional);
}
/// Tries to reserve capacity for at least `additional` more elements to be
/// inserted in the `String`. The collection may reserve more space to avoid
/// frequent reallocations. After calling `try_reserve`, capacity will be
/// greater than or equal to `self.len() + additional`. Does nothing if
/// capacity is already sufficient.
///
/// # Errors
///
/// If the capacity overflows, or the allocator reports a failure, then an
/// error is returned.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
/// let mut str = String::from("x");
/// str.try_reserve(10).expect("why is this OOMing?");
/// assert!(str.capacity() >= 11);
/// ```
#[inline]
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.inner.try_reserve(additional)
}
/// Reserves the minimum capacity for exactly `additional` more bytes to be
/// inserted in the given `String`. After calling `reserve_exact`, capacity
/// will be greater than or equal to `self.len() + additional`. Does nothing
/// if the capacity is already sufficient.
///
/// Note that the allocator may give the string more space than it requests.
/// Therefore, capacity can not be relied upon to be precisely minimal.
/// Prefer [`reserve`] if future insertions are expected.
///
/// # Panics
///
/// Panics if the new capacity exceeds [`isize::MAX`] bytes.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::from("x");
/// s.reserve_exact(10);
/// assert!(s.capacity() >= 11);
/// ```
///
/// [`reserve`]: Self::reserve
#[inline]
pub fn reserve_exact(&mut self, additional: usize) {
self.inner.reserve_exact(additional);
}
/// Tries to reserve the minimum capacity for exactly `additional`
/// elements to be inserted in the `String`. After calling
/// `try_reserve_exact`, capacity will be greater than or equal to
/// `self.len() + additional` if it returns `Ok(())`. Does nothing if the
/// capacity is already sufficient.
///
/// Note that the allocator may give the collection more space than
/// it requests. Therefore, capacity can not be relied upon to be
/// precisely minimal. Prefer [`try_reserve`] if future insertions are
/// expected.
///
/// # Errors
///
/// If the capacity overflows, or the allocator reports a failure, then an
/// error is returned.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
/// let mut str = String::from("x");
/// str.try_reserve_exact(10).expect("why is this OOMing?");
/// assert!(str.capacity() >= 11);
/// ```
///
/// [`try_reserve`]: Self::try_reserve
#[inline]
pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.inner.try_reserve_exact(additional)
}
/// Shrinks the capacity of the vector as much as possible.
///
/// It will drop down as close as possible to the length but the allocator
/// may still inform the string that there is space for a few more bytes.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::with_capacity(10);
/// s.extend_from_slice(b"abc");
/// assert!(s.capacity() >= 10);
/// s.shrink_to_fit();
/// assert!(s.capacity() >= 3);
/// ```
#[inline]
pub fn shrink_to_fit(&mut self) {
self.inner.shrink_to_fit();
}
/// Shrinks the capacity of the vector with a lower bound.
///
/// The capacity will remain at least as large as both the length and the
/// supplied value.
///
/// If the current capacity is less than the lower limit, this is a no-op.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::with_capacity(10);
/// s.extend_from_slice(b"abc");
/// assert!(s.capacity() >= 10);
/// s.shrink_to(5);
/// assert!(s.capacity() >= 5);
/// ```
#[inline]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.inner.shrink_to(min_capacity);
}
}
// Indexing
impl String {
/// Returns a reference to a byte or sub-byteslice depending on the type of
/// index.
///
/// - If given a position, returns a reference to the byte at that position
/// or [`None`] if out of bounds.
/// - If given a range, returns the subslice corresponding to that range, or
/// [`None`] if out of bounds.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::from("abc");
/// assert_eq!(s.get(1), Some(&b'b'));
/// assert_eq!(s.get(0..2), Some(&b"ab"[..]));
/// assert_eq!(s.get(3), None);
/// assert_eq!(s.get(0..4), None);
/// ```
#[inline]
#[must_use]
pub fn get<I>(&self, index: I) -> Option<&I::Output>
where
I: SliceIndex<[u8]>,
{
self.inner.get(index)
}
/// Returns a mutable reference to a byte or sub-byteslice depending on the
/// type of index (see [`get`]) or [`None`] if the index is out of bounds.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::from("abc");
///
/// if let Some(byte) = s.get_mut(1) {
/// *byte = b'x';
/// }
/// assert_eq!(s, "axc");
/// ```
///
/// [`get`]: Self::get
#[inline]
#[must_use]
pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
where
I: SliceIndex<[u8]>,
{
self.inner.get_mut(index)
}
/// Returns a reference to a byte or sub-byteslice, without doing bounds
/// checking.
///
/// For a safe alternative see [`get`].
///
/// # Safety
///
/// Calling this method with an out-of-bounds index is *[undefined
/// behavior]* even if the resulting reference is not used.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::from("abc");
///
/// unsafe {
/// assert_eq!(s.get_unchecked(1), &b'b');
/// }
/// ```
///
/// [`get`]: Self::get
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
#[inline]
#[must_use]
pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
where
I: SliceIndex<[u8]>,
{
self.inner.get_unchecked(index)
}
/// Returns a mutable reference to a byte or sub-byteslice, without doing
/// bounds checking.
///
/// For a safe alternative see [`get_mut`].
///
/// # Safety
///
/// Calling this method with an out-of-bounds index is *[undefined
/// behavior]* even if the resulting reference is not used.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::from("abc");
///
/// unsafe {
/// let byte = s.get_unchecked_mut(1);
/// *byte = b'x';
/// }
/// assert_eq!(s, "axc");
/// ```
///
/// [`get_mut`]: Self::get_mut
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
#[inline]
#[must_use]
pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
where
I: SliceIndex<[u8]>,
{
self.inner.get_unchecked_mut(index)
}
}
// Pushing and popping bytes, codepoints, and strings.
impl String {
/// Appends a given byte onto the end of this `String`.
///
/// The given byte is not required to be a valid byte given this `String`'s
/// [encoding] because encodings are only conventional.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::utf8(b"UTF-8?".to_vec());
/// s.push_byte(0xFF);
/// assert_eq!(s, b"UTF-8?\xFF");
/// ```
///
/// [encoding]: crate::Encoding
#[inline]
pub fn push_byte(&mut self, byte: u8) {
self.inner.push_byte(byte);
}
/// Try to append a given Unicode codepoint onto the end of this `String`.
///
/// This API is encoding-aware. For [UTF-8] strings, the given integer is
/// converted to a [`char`] before appending to this `String` using
/// [`push_char`]. For [ASCII] and [binary] strings, the given integer is
/// converted to a byte before appending to this `String` using
/// [`push_byte`].
///
/// This function can be used to implement the Ruby method [`String#<<`] for
/// [`Integer`][ruby-integer] arguments.
///
/// # Errors
///
/// If this `String` is [conventionally UTF-8] and the given codepoint is
/// not a valid [`char`], an error is returned.
///
/// If this `String` has [ASCII] or [binary] encoding and the given
/// codepoint is not a valid byte, an error is returned.
///
/// # Examples
///
/// For [UTF-8] strings, the given codepoint is converted to a Unicode scalar
/// value before appending:
///
/// ```
/// use spinoso_string::String;
///
/// # fn example() -> Result<(), spinoso_string::InvalidCodepointError> {
/// let mut s = String::utf8(b"".to_vec());
/// s.try_push_codepoint(b'a' as i64)?;
/// assert_eq!(s, "a");
/// assert!(s.try_push_codepoint(0xD83F).is_err());
/// assert!(s.try_push_codepoint(-1).is_err());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// For [ASCII] and [binary] strings, the given codepoint must be a valid
/// byte:
///
/// ```
/// use spinoso_string::String;
///
/// # fn example() -> Result<(), spinoso_string::InvalidCodepointError> {
/// let mut s = String::binary(b"".to_vec());
/// s.try_push_codepoint(b'a' as i64)?;
/// assert_eq!(s, "a");
/// assert!(s.try_push_codepoint(1024).is_err());
/// assert!(s.try_push_codepoint(-1).is_err());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// [UTF-8]: crate::Encoding::Utf8
/// [ASCII]: crate::Encoding::Ascii
/// [binary]: crate::Encoding::Binary
/// [`push_char`]: Self::push_char
/// [`push_byte`]: Self::push_byte
/// [`String#<<`]: https://ruby-doc.org/core-3.1.2/String.html#method-i-3C-3C
/// [ruby-integer]: https://ruby-doc.org/core-3.1.2/Integer.html
/// [conventionally UTF-8]: crate::Encoding::Utf8
#[inline]
pub fn try_push_codepoint(&mut self, codepoint: i64) -> Result<(), InvalidCodepointError> {
self.inner.try_push_codepoint(codepoint)
}
/// A more permissive version of [`try_push_codepoint`] which can alter the
/// receiver's encoding to accommodate the given byte.
///
/// # Errors
///
/// If this `String` is [conventionally UTF-8] and the given codepoint is
/// not a valid [`char`], an error is returned.
///
/// If this `String` has [ASCII] or [binary] encoding and the given
/// codepoint is not a valid byte, an error is returned.
///
/// # Examples
///
/// For [UTF-8] and [binary] strings, this function behaves identically to
/// [`try_push_codepoint`].
///
/// ```
/// use spinoso_string::String;
///
/// # fn example() -> Result<(), spinoso_string::InvalidCodepointError> {
/// let mut s = String::utf8(b"".to_vec());
/// s.try_push_int(b'a' as i64)?;
/// assert_eq!(s, "a");
/// assert!(s.try_push_int(0xD83F).is_err());
/// assert!(s.try_push_int(-1).is_err());
///
/// let mut s = String::binary(b"".to_vec());
/// s.try_push_int(b'a' as i64)?;
/// assert_eq!(s, "a");
/// assert!(s.try_push_int(1024).is_err());
/// assert!(s.try_push_int(-1).is_err());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// For [ASCII] strings, the given integer must be a valid byte. If the
/// given integer is outside of the ASCII range, the string's encoding is
/// changed to [`Encoding::Binary`].
///
/// ```
/// use spinoso_string::{Encoding, String};
///
/// # fn example() -> Result<(), spinoso_string::InvalidCodepointError> {
/// let mut s = String::ascii(b"".to_vec());
/// s.try_push_int(b'a' as i64)?;
/// assert_eq!(s, "a");
/// assert_eq!(s.encoding(), Encoding::Ascii);
/// assert!(s.try_push_int(1024).is_err());
/// assert!(s.try_push_int(-1).is_err());
///
/// s.try_push_int(b'\xFF' as i64)?;
/// assert_eq!(s, b"a\xFF");
/// assert_eq!(s.encoding(), Encoding::Binary);
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// [`try_push_codepoint`]: Self::try_push_codepoint
/// [UTF-8]: crate::Encoding::Utf8
/// [ASCII]: crate::Encoding::Ascii
/// [binary]: crate::Encoding::Binary
/// [conventionally UTF-8]: crate::Encoding::Utf8
#[inline]
pub fn try_push_int(&mut self, int: i64) -> Result<(), InvalidCodepointError> {
self.inner.try_push_int(int)
}
/// Appends a given [`char`] onto the end of this `String`.
///
/// The given char is UTF-8 encoded and the UTF-8 bytes are appended to the
/// end of this `String`.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::from("<3");
/// s.push_char('π');
/// assert_eq!(s, b"<3\xF0\x9F\x92\x8E"); // "<3π"
/// ```
#[inline]
pub fn push_char(&mut self, ch: char) {
self.inner.push_char(ch);
}
/// Appends a given string slice onto the end of this `String`.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::utf8(b"spinoso".to_vec());
/// s.push_str("-string");
/// assert_eq!(s, "spinoso-string");
/// ```
#[inline]
pub fn push_str(&mut self, s: &str) {
self.inner.push_str(s);
}
/// Copies and appends all bytes in a slice to the `String`.
///
/// Iterates over the slice `other`, copies each element, and then appends
/// it to this `String`. The other byte slice is traversed in-order.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::from("a");
/// s.extend_from_slice(&b"bc"[..]);
/// assert_eq!(s, "abc");
/// ```
#[inline]
pub fn extend_from_slice(&mut self, other: &[u8]) {
self.inner.extend_from_slice(other);
}
}
// Ruby APIs
impl String {
/// Appends the given bytes to this `String`.
///
/// See also [`Extend`].
///
/// This function can be used to implement the Ruby method [`String#<<`] for
/// [`String`][ruby-string] arguments.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::ascii(b"abc".to_vec());
/// s.concat(", easy as 123");
/// assert_eq!(s, "abc, easy as 123");
/// ```
///
/// [`String#<<`]: https://ruby-doc.org/core-3.1.2/String.html#method-i-3C-3C
/// [ruby-string]: https://ruby-doc.org/core-3.1.2/String.html
#[inline]
pub fn concat<T: AsRef<[u8]>>(&mut self, other: T) {
let other = other.as_ref();
self.inner.extend_from_slice(other);
}
/// Returns true for a string which has only ASCII characters.
///
/// ASCII is an encoding that defines 128 codepoints. A byte corresponds to
/// an ASCII codepoint if and only if it is in the inclusive range
/// `[0, 127]`.
///
/// This function ignores this `String`'s [encoding].
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::utf8("abc".as_bytes().to_vec());
/// assert!(s.is_ascii_only());
/// let s = String::utf8("abc\u{6666}".as_bytes().to_vec());
/// assert!(!s.is_ascii_only());
/// ```
///
/// [encoding]: crate::Encoding
#[inline]
#[must_use]
pub fn is_ascii_only(&self) -> bool {
self.inner.is_ascii_only()
}
/// Return a newly encoded `String` with [`Encoding::Binary`] encoding.
///
/// This function can be used to implement the Ruby method [`String#b`].
///
/// # Examples
///
/// ```
/// use spinoso_string::{Encoding, String};
///
/// let s = String::utf8(b"xyz".to_vec());
/// assert_eq!(s.encoding(), Encoding::Utf8);
/// let b = s.to_binary();
/// assert_eq!(b.encoding(), Encoding::Binary);
/// assert_eq!(s.as_slice(), b.as_slice());
/// ```
///
/// [`String#b`]: https://ruby-doc.org/core-3.1.2/String.html#method-i-b
#[inline]
#[must_use]
pub fn to_binary(&self) -> Self {
String::binary(self.inner.as_slice().to_vec())
}
/// Returns the length of this `String` in bytes.
///
/// `bytesize` is an [`Encoding`]-oblivious API and is equivalent to
/// [`String::len`].
///
/// This function can be used to implement the Ruby method
/// [`String#bytesize`].
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::utf8("π".as_bytes().to_vec());
/// assert_eq!(s.bytesize(), 4);
/// assert_eq!(s.bytesize(), s.len());
/// ```
///
/// [`String#bytesize`]: https://ruby-doc.org/core-3.1.2/String.html#method-i-bytesize
#[inline]
#[must_use]
pub fn bytesize(&self) -> usize {
self.len()
}
/// Modify this `String` to have the first character converted to uppercase
/// and the remainder to lowercase.
#[inline]
pub fn make_capitalized(&mut self) {
self.inner.make_capitalized();
}
/// Modify this `String` to have all characters converted to lowercase.
#[inline]
pub fn make_lowercase(&mut self) {
self.inner.make_lowercase();
}
/// Modify this `String` to have the all characters converted to uppercase.
#[inline]
pub fn make_uppercase(&mut self) {
self.inner.make_uppercase();
}
#[inline]
#[must_use]
#[cfg(feature = "casecmp")]
#[cfg_attr(docsrs, doc(cfg(feature = "casecmp")))]
pub fn ascii_casecmp(&self, other: &[u8]) -> Ordering {
focaccia::ascii_casecmp(self.as_slice(), other)
}
#[inline]
#[must_use]
#[cfg(feature = "casecmp")]
#[cfg_attr(docsrs, doc(cfg(feature = "casecmp")))]
pub fn unicode_casecmp(&self, other: &String, options: CaseFold) -> Option<bool> {
let left = self.as_slice();
let right = other.as_slice();
// If both `String`s are conventionally UTF-8, they must be case
// compared using the given case folding strategy. This requires the
// `String`s be well-formed UTF-8.
if let (Encoding::Utf8, Encoding::Utf8) = (self.encoding(), other.encoding()) {
if let (Ok(left), Ok(right)) = (str::from_utf8(left), str::from_utf8(right)) {
// Both slices are UTF-8, compare with the given Unicode case
// folding scheme.
Some(options.case_eq(left, right))
} else {
// At least one `String` contains invalid UTF-8 bytes.
None
}
} else {
// At least one slice is not conventionally UTF-8, so fallback to
// ASCII comparator.
Some(focaccia::ascii_case_eq(left, right))
}
}
/// Centers this `String` in width with the given padding.
///
/// This function returns an iterator that yields [`u8`].
///
/// If width is greater than the length of this `String`, the returned
/// iterator yields a byte sequence of length `width` with the byte content
/// of this `String` centered and padded with the given padding; otherwise,
/// yields the original bytes.
///
/// If the given padding is [`None`], the `String` is padded with an ASCII
/// space.
///
/// # Errors
///
/// If given an empty padding byte string, this function returns an error.
/// This error is returned regardless of whether the `String` would be
/// centered with the given
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
/// # fn example() -> Result<(), spinoso_string::CenterError> {
/// let s = String::from("hello");
///
/// assert_eq!(s.center(4, None)?.collect::<Vec<_>>(), b"hello");
/// assert_eq!(
/// s.center(20, None)?.collect::<Vec<_>>(),
/// b" hello "
/// );
/// assert_eq!(
/// s.center(20, Some(&b"123"[..]))?.collect::<Vec<_>>(),
/// b"1231231hello12312312"
/// );
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// This iterator is [encoding-aware]. [Conventionally UTF-8] strings are
/// iterated by UTF-8 byte sequences.
///
/// ```
/// use spinoso_string::String;
/// # fn example() -> Result<(), spinoso_string::CenterError> {
/// let s = String::from("π");
///
/// assert_eq!(s.center(3, None)?.collect::<Vec<_>>(), " π ".as_bytes());
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// [`center`]: crate::String::center
/// [encoding-aware]: crate::Encoding
/// [Conventionally UTF-8]: crate::Encoding::Utf8
#[inline]
pub fn center<'a, 'b>(&'a self, width: usize, padding: Option<&'b [u8]>) -> Result<Center<'a, 'b>, CenterError> {
let padding = match padding {
None => b" ",
Some([]) => return Err(CenterError::ZeroWidthPadding),
Some(p) => p,
};
let padding_width = width.saturating_sub(self.char_len());
Ok(Center::with_chars_width_and_padding(
self.chars(),
padding_width,
padding,
))
}
/// Modifies this `String` in-place with the given record separator removed
/// from the end of `str` (if given).
///
/// If `separator` is [`None`] (i.e. `separator` has not been changed from
/// the default Ruby record separator), then `chomp` also removes carriage
/// return characters (that is it will remove `\n`, `\r`, and `\r\n`). If
/// `separator` is an empty string, it will remove all trailing newlines
/// from the string.
///
/// A [`None`] separator does not mean that `chomp` is passed a `nil`
/// separator. For `str.chomp nil`, MRI returns `str.dup`. For
/// `str.chomp! nil`, MRI makes no changes to the receiver and returns
/// `nil`.
///
/// This function returns `true` if self is modified, `false` otherwise.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::utf8(b"This is a paragraph.\r\n\n\n".to_vec());
/// let modified = s.chomp(None::<&[u8]>);
/// assert!(modified);
/// assert_eq!(s, "This is a paragraph.\r\n\n");
///
/// let mut s = String::utf8(b"This is a paragraph.\r\n\n\n".to_vec());
/// let modified = s.chomp(Some(""));
/// assert!(modified);
/// assert_eq!(s, "This is a paragraph.");
///
/// let mut s = String::utf8(b"hello\r\n\r\r\n".to_vec());
/// let modified = s.chomp(None::<&[u8]>);
/// assert!(modified);
/// assert_eq!(s, "hello\r\n\r");
///
/// let mut s = String::utf8(b"hello\r\n\r\r\n".to_vec());
/// let modified = s.chomp(Some(""));
/// assert!(modified);
/// assert_eq!(s, "hello\r\n\r");
///
/// let mut s = String::utf8(b"This is a paragraph.".to_vec());
/// let modified = s.chomp(Some("."));
/// assert!(modified);
/// assert_eq!(s, "This is a paragraph");
///
/// let mut s = String::utf8(b"This is a paragraph.".to_vec());
/// let modified = s.chomp(Some("abc"));
/// assert!(!modified);
/// assert_eq!(s, "This is a paragraph.");
/// ```
#[inline]
#[must_use]
pub fn chomp<T: AsRef<[u8]>>(&mut self, separator: Option<T>) -> bool {
// convert to a concrete type and delegate to a single `chomp` impl
// to minimize code duplication when monomorphizing.
if let Some(sep) = separator {
chomp(self, Some(sep.as_ref()))
} else {
chomp(self, None)
}
}
/// Modifies this `String` in-place and removes the last character.
///
/// This method returns a [`bool`] that indicates if this string was modified.
///
/// If the string ends with `\r\n`, both characters are removed. When
/// applying `chop` to an empty string, the string remains empty.
///
/// [`String::chomp`] is often a safer alternative, as it leaves the string
/// unchanged if it doesn't end in a record separator.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::utf8(b"This is a paragraph.\r\n".to_vec());
/// let modified = s.chop();
/// assert!(modified);
/// assert_eq!(s, "This is a paragraph.");
///
/// let mut s = String::utf8(b"This is a paragraph.".to_vec());
/// let modified = s.chop();
/// assert!(modified);
/// assert_eq!(s, "This is a paragraph");
///
/// let mut s = String::utf8(b"".to_vec());
/// let modified = s.chop();
/// assert!(!modified);
/// assert_eq!(s, "");
///
/// let mut s = String::utf8(b"x".to_vec());
/// let modified = s.chop();
/// assert!(modified);
/// assert_eq!(s, "");
/// ```
#[inline]
#[must_use]
pub fn chop(&mut self) -> bool {
if self.is_empty() {
return false;
}
let bytes_to_remove = if self.inner.ends_with(b"\r\n") {
2
} else if let Encoding::Utf8 = self.encoding() {
let (ch, size) = bstr::decode_last_utf8(self.as_slice());
if ch.is_some() {
size
} else {
1
}
} else {
// `buf` is checked to be non-empty above.
1
};
// This subtraction is guaranteed to not panic because we have validated
// that we're removing a subslice of `buf`.
self.truncate(self.len() - bytes_to_remove);
true
}
/// Returns a one-character string at the beginning of the string.
///
/// # Examples
///
/// [Conventionally UTF-8] `String`s perform a partial UTF-8 decode to
/// compute the first character.
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::utf8(b"abcde".to_vec());
/// assert_eq!(s.chr(), &b"a"[..]);
///
/// let s = String::utf8(b"".to_vec());
/// assert_eq!(s.chr(), &[]);
///
/// let s = String::utf8("π¦spinosoπ".as_bytes().to_vec());
/// assert_eq!(s.chr(), &b"\xF0\x9F\xA6\x80"[..]);
///
/// let s = String::utf8(b"\xFFspinoso".to_vec());
/// assert_eq!(s.chr(), &b"\xFF"[..]);
/// ```
///
/// For [ASCII] and [binary] `String`s this function returns a slice of the
/// first byte or the empty slice if the `String` is empty.
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::binary(b"abcde".to_vec());
/// assert_eq!(s.chr(), &b"a"[..]);
///
/// let s = String::binary(b"".to_vec());
/// assert_eq!(s.chr(), &[]);
///
/// let s = String::binary("π¦spinosoπ".as_bytes().to_vec());
/// assert_eq!(s.chr(), &b"\xF0"[..]);
///
/// let s = String::binary(b"\xFFspinoso".to_vec());
/// assert_eq!(s.chr(), &b"\xFF"[..]);
/// ```
///
/// [Conventionally UTF-8]: Encoding::Utf8
/// [ASCII]: crate::Encoding::Ascii
/// [binary]: crate::Encoding::Binary
#[inline]
#[must_use]
pub fn chr(&self) -> &[u8] {
self.inner.chr()
}
/// Returns the char-based index of the first occurrence of the given
/// substring in this `String`.
///
/// Returns [`None`] if not found. If the second parameter is present, it
/// specifies the character position in the string to begin the search.
///
/// This function can be used to implement [`String#index`].
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::utf8("via π v3.2.0".as_bytes().to_vec());
/// assert_eq!(s.index("a", None), Some(2));
/// assert_eq!(s.index("a", Some(2)), Some(2));
/// assert_eq!(s.index("a", Some(3)), None);
/// assert_eq!(s.index("π", None), Some(4));
/// assert_eq!(s.index(".", None), Some(8));
/// assert_eq!(s.index("v", Some(6)), Some(6));
/// assert_eq!(s.index("v", Some(7)), None);
/// assert_eq!(s.index("X", None), None);
/// ```
///
/// [`String#index`]: https://ruby-doc.org/core-3.1.2/String.html#method-i-index
#[inline]
#[must_use]
pub fn index<T: AsRef<[u8]>>(&self, needle: T, offset: Option<usize>) -> Option<usize> {
let offset = offset.unwrap_or(0);
self.inner.index(needle.as_ref(), offset)
}
/// Returns the char-based index of the last occurrence of the given
/// substring in this `String`.
///
/// Returns [`None`] if not found. If the second parameter is present, it
/// specifies the character position in the string to begin the search.
///
/// This function can be used to implement [`String#rindex`].
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::utf8("via π v3.2.0".as_bytes().to_vec());
/// assert_eq!(s.rindex("v", None), Some(6));
/// assert_eq!(s.rindex("v", Some(5)), Some(0));
/// assert_eq!(s.rindex("v", Some(6)), Some(6));
/// assert_eq!(s.rindex("a", None), Some(2));
/// ```
///
/// [`String#rindex`]: https://ruby-doc.org/core-3.1.2/String.html#method-i-rindex
#[inline]
#[must_use]
pub fn rindex<T: AsRef<[u8]>>(&self, needle: T, offset: Option<usize>) -> Option<usize> {
let offset = offset.unwrap_or_else(|| self.inner.char_len().checked_sub(1).unwrap_or_default());
self.inner.rindex(needle.as_ref(), offset)
}
/// Returns the byte-based index of the first occurrence of the given
/// substring in this `String`.
///
/// Returns [`None`] if not found. If the second parameter is present, it
/// specifies the byte position in the string to begin the search.
///
/// This function can be used to implement [`String#byteindex`].
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::utf8("via π v3.2.0".as_bytes().to_vec());
/// assert_eq!(s.byteindex("a", None), Some(2));
/// assert_eq!(s.byteindex("a", Some(2)), Some(2));
/// assert_eq!(s.byteindex("a", Some(3)), None);
/// assert_eq!(s.byteindex("π", None), Some(4));
/// assert_eq!(s.byteindex(".", None), Some(11));
/// assert_eq!(s.byteindex("X", None), None);
/// ```
///
/// [`String#byteindex`]: https://ruby-doc.org/3.2.0/String.html#method-i-byteindex
#[inline]
#[must_use]
pub fn byteindex<T: AsRef<[u8]>>(&self, needle: T, offset: Option<usize>) -> Option<usize> {
fn inner(buf: &[u8], needle: &[u8], offset: Option<usize>) -> Option<usize> {
if let Some(offset) = offset {
let buf = buf.get(offset..)?;
let index = buf.find(needle)?;
// This addition is guaranteed not to overflow because the result is
// a valid index of the underlying `Vec`.
//
// `self.buf.len() < isize::MAX` because `self.buf` is a `Vec` and
// `Vec` documents `isize::MAX` as its maximum allocation size.
Some(index + offset)
} else {
buf.find(needle)
}
}
// convert to a concrete type and delegate to a single `index` impl
// to minimize code duplication when monomorphizing.
let needle = needle.as_ref();
inner(self.inner.as_slice(), needle, offset)
}
/// Returns the byte-based index of the last occurrence of the given
/// substring in this `String`.
///
/// Returns [`None`] if not found. If the second parameter is present, it
/// specifies the byte position in the string to begin the search.
///
/// This function can be used to implement [`String#rindex`].
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::utf8("via π v3.2.0".as_bytes().to_vec());
/// assert_eq!(s.byterindex("v", None), Some(9));
/// assert_eq!(s.byterindex("a", None), Some(2));
/// ```
///
/// [`String#byterindex`]: https://ruby-doc.org/3.2.0/String.html#method-i-byterindex
#[inline]
#[must_use]
pub fn byterindex<T: AsRef<[u8]>>(&self, needle: T, offset: Option<usize>) -> Option<usize> {
fn inner(buf: &[u8], needle: &[u8], offset: Option<usize>) -> Option<usize> {
if let Some(offset) = offset {
let end = buf.len().checked_sub(offset).unwrap_or_default();
let buf = buf.get(..end)?;
buf.rfind(needle)
} else {
buf.rfind(needle)
}
}
// convert to a concrete type and delegate to a single `rindex` impl
// to minimize code duplication when monomorphizing.
let needle = needle.as_ref();
inner(self.inner.as_slice(), needle, offset)
}
/// Returns an iterator that yields a debug representation of the `String`.
///
/// This iterator produces [`char`] sequences like `"spinoso"` and
/// `"invalid-\xFF-utf8"`.
///
/// This function can be used to implement the Ruby method
/// [`String#inspect`].
///
/// This iterator is encoding-aware. This iterator may yield different
/// `char`s for the same underlying byte contents depending on the string's
/// encoding.
///
/// [`String#inspect`]: https://ruby-doc.org/core-3.1.2/String.html#method-i-inspect:
#[inline]
pub fn inspect(&self) -> Inspect<'_> {
Inspect::new(self.inner.inspect())
}
/// Returns the Integer ordinal of a one-character string.
///
/// # Errors
///
/// If this `String` is empty, an error is returned.
///
/// If this `String` is [conventionally UTF-8] and the string contents begin
/// with an invalid UTF-8 byte sequence, an error is returned.
///
/// [conventionally UTF-8]: crate::Encoding::Utf8
#[inline]
pub fn ord(&self) -> Result<u32, OrdError> {
self.inner.ord()
}
}
// Encoding-aware APIs.
impl String {
/// Returns an iterator over the chars of a `String`.
///
/// This function is encoding-aware. `String`s with [UTF-8 encoding] are
/// only [conventionally UTF-8]. This iterator yields `&[u8]` byte slices
/// that correspond to either a valid UTF-8 byte sequence or a single
/// invalid UTF-8 byte. For [ASCII encoded] and [binary encoded] strings,
/// this iterator yields slices of single bytes.
///
/// For UTF-8 encoded strings, the yielded byte slices can be parsed into
/// [`char`]s with [`str::from_utf8`] and [`str::chars`].
///
/// # Examples
///
/// Iterating over the characters of a conventionally UTF-8 string:
///
/// ```
/// use core::str;
///
/// use spinoso_string::String;
///
/// let s = String::utf8(b"ab\xF0\x9F\x92\x8E\xFF".to_vec());
/// let mut chars = s.chars();
/// assert_eq!(chars.next(), Some(&b"a"[..]));
/// assert_eq!(chars.next().map(str::from_utf8), Some(Ok("b")));
/// assert_eq!(chars.next(), Some(&[0xF0, 0x9F, 0x92, 0x8E][..]));
/// assert_eq!(chars.next(), Some(&b"\xFF"[..]));
/// assert_eq!(chars.next(), None);
/// ```
///
/// Iterating over the characters of a binary string:
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::binary("π".as_bytes().to_vec());
/// let mut chars = s.chars();
/// assert_eq!(chars.next(), Some(&[0xF0][..]));
/// assert_eq!(chars.next(), Some(&[0x9F][..]));
/// assert_eq!(chars.next(), Some(&[0x92][..]));
/// assert_eq!(chars.next(), Some(&[0x8E][..]));
/// assert_eq!(chars.next(), None);
/// ```
///
/// [UTF-8 encoding]: crate::Encoding::Utf8
/// [conventionally UTF-8]: crate::Encoding::Utf8
/// [ASCII encoded]: crate::Encoding::Ascii
/// [binary encoded]: crate::Encoding::Binary
/// [`str::from_utf8`]: core::str::from_utf8
#[inline]
#[must_use]
pub fn chars(&self) -> Chars<'_> {
Chars::from(self)
}
/// Returns an iterator over the `u32` codepoints of a `String`.
///
/// This function is encoding-aware. `String`s with [UTF-8 encoding] are
/// only [conventionally UTF-8]. This function only returns `Ok` for
/// `String`s with UTF-8 encoding if the underlying bytes in the `String`
/// are valid UTF-8. For UTF-8 `String`s, this iterator yields the `u32`
/// values of the [`char`]s in the byte string. For [ASCII encoded] and
/// [binary encoded] strings, this iterator yields slices of single bytes.
///
/// For UTF-8 encoded strings, the yielded byte slices can be parsed into
/// [`char`]s with `.into()`.
///
/// # Errors
///
/// This function requires the `String` contents to be well-formed with
/// respect to its encoding. This function will return an error if the
/// `String` has UTF-8 encoding and contains invalid UTF-8 byte sequences.
///
/// # Examples
///
/// Iterating over the codepoints of a conventionally UTF-8 string:
///
/// ```
/// use spinoso_string::{CodepointsError, String};
///
/// # fn example() -> Result<(), spinoso_string::CodepointsError> {
/// let s = String::utf8(b"ab\xF0\x9F\x92\x8E\xFF".to_vec());
/// assert!(matches!(
/// s.codepoints(),
/// Err(CodepointsError::InvalidUtf8Codepoint)
/// ));
///
/// let s = String::utf8("π".as_bytes().to_vec());
/// let mut codepoints = s.codepoints()?;
/// assert_eq!(codepoints.next(), Some(u32::from('π')));
/// assert_eq!(codepoints.next(), None);
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// Iterating over the codepoints of a binary string:
///
/// ```
/// use spinoso_string::String;
///
/// # fn example() -> Result<(), spinoso_string::CodepointsError> {
/// let s = String::binary("π".as_bytes().to_vec());
/// let mut codepoints = s.codepoints()?;
/// assert_eq!(codepoints.next(), Some(0xF0));
/// assert_eq!(codepoints.next(), Some(0x9F));
/// assert_eq!(codepoints.next(), Some(0x92));
/// assert_eq!(codepoints.next(), Some(0x8E));
/// assert_eq!(codepoints.next(), None);
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// [UTF-8 encoding]: crate::Encoding::Utf8
/// [conventionally UTF-8]: crate::Encoding::Utf8
/// [ASCII encoded]: crate::Encoding::Ascii
/// [binary encoded]: crate::Encoding::Binary
/// [`str::from_utf8`]: core::str::from_utf8
#[inline]
pub fn codepoints(&self) -> Result<Codepoints<'_>, CodepointsError> {
Codepoints::try_from(self)
}
/// Returns the character length of this `String`.
///
/// This function is encoding-aware. For `String`s with [UTF-8 encoding],
/// multi-byte Unicode characters are length 1 and invalid UTF-8 bytes are
/// length 1. For `String`s with [ASCII encoding] or [binary encoding],
/// this function is equivalent to [`len`] and [`bytesize`].
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::utf8(b"abc\xF0\x9F\x92\x8E\xFF".to_vec()); // "abcπ\xFF"
/// assert_eq!(s.char_len(), 5);
///
/// let b = String::binary(b"abc\xF0\x9F\x92\x8E\xFF".to_vec()); // "abcπ\xFF"
/// assert_eq!(b.char_len(), 8);
/// ```
///
/// [UTF-8 encoding]: crate::Encoding::Utf8
/// [ASCII encoding]: crate::Encoding::Ascii
/// [binary encoding]: crate::Encoding::Binary
/// [`len`]: Self::len
/// [`bytesize`]: Self::bytesize
#[inline]
#[must_use]
pub fn char_len(&self) -> usize {
self.inner.char_len()
}
/// Returns the `index`'th character in the string.
///
/// This function is encoding-aware. For `String`s with [UTF-8 encoding],
/// multi-byte Unicode characters are length 1 and invalid UTF-8 bytes are
/// length 1. For `String`s with [ASCII encoding] or [binary encoding],
/// this function is equivalent to [`get`] with a range of length 1.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::utf8(b"abc\xF0\x9F\x92\x8E\xFF".to_vec()); // "abcπ\xFF"
/// assert_eq!(s.get_char(0), Some(&b"a"[..]));
/// assert_eq!(s.get_char(1), Some(&b"b"[..]));
/// assert_eq!(s.get_char(2), Some(&b"c"[..]));
/// assert_eq!(s.get_char(3), Some("π".as_bytes()));
/// assert_eq!(s.get_char(4), Some(&b"\xFF"[..]));
/// assert_eq!(s.get_char(5), None);
///
/// let b = String::binary(b"abc\xF0\x9F\x92\x8E\xFF".to_vec()); // "abcπ\xFF"
/// assert_eq!(b.get_char(0), Some(&b"a"[..]));
/// assert_eq!(b.get_char(1), Some(&b"b"[..]));
/// assert_eq!(b.get_char(2), Some(&b"c"[..]));
/// assert_eq!(b.get_char(3), Some(&b"\xF0"[..]));
/// assert_eq!(b.get_char(4), Some(&b"\x9F"[..]));
/// assert_eq!(b.get_char(5), Some(&b"\x92"[..]));
/// assert_eq!(b.get_char(6), Some(&b"\x8E"[..]));
/// assert_eq!(b.get_char(7), Some(&b"\xFF"[..]));
/// assert_eq!(b.get_char(8), None);
/// ```
///
/// [UTF-8 encoding]: crate::Encoding::Utf8
/// [ASCII encoding]: crate::Encoding::Ascii
/// [binary encoding]: crate::Encoding::Binary
/// [`get`]: Self::get
#[inline]
#[must_use]
pub fn get_char(&self, index: usize) -> Option<&'_ [u8]> {
// `Vec` has a max allocation size of `isize::MAX`. For a `Vec<u8>` like
// the one in `String` where the `size_of::<u8>() == 1`, the max length
// is `isize::MAX`. This checked add short circuits with `None` if we
// are given `usize::MAX` as an index, which we could never slice.
index.checked_add(1)?;
self.inner.get_char(index)
}
/// Returns a substring of characters in the string.
///
/// This function is encoding-aware. For `String`s with [UTF-8 encoding],
/// multi-byte Unicode characters are length 1 and invalid UTF-8 bytes are
/// length 1. For `String`s with [ASCII encoding] or [binary encoding],
/// this function is equivalent to [`get`] with a range.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let s = String::ascii(b"abc".to_vec());
/// assert_eq!(s.get_char_slice(1..3), Some("bc".as_bytes()));
/// assert_eq!(s.get_char_slice(10..15), None);
///
/// let s = String::utf8(b"abc\xF0\x9F\x92\x8E\xFF".to_vec()); // "abcπ\xFF"
/// assert_eq!(s.get_char_slice(1..4), Some("bcπ".as_bytes()));
/// assert_eq!(s.get_char_slice(4..1), Some("".as_bytes()));
/// ```
///
/// [UTF-8 encoding]: crate::Encoding::Utf8
/// [ASCII encoding]: crate::Encoding::Ascii
/// [binary encoding]: crate::Encoding::Binary
/// [`get`]: Self::get
#[inline]
#[must_use]
pub fn get_char_slice(&self, range: Range<usize>) -> Option<&'_ [u8]> {
self.inner.get_char_slice(range)
}
/// Returns true for a `String` which is encoded correctly.
///
/// For this method to return true, `String`s with [conventionally UTF-8]
/// must be well-formed UTF-8; [ASCII]-encoded `String`s must only contain
/// bytes in the range `0..=127`; [binary]-encoded `String`s may contain any
/// byte sequence.
///
/// This method is suitable for implementing the Ruby method
/// [`String#valid_encoding?`].
///
/// # Examples
///
/// ```
/// use spinoso_string::{Encoding, String};
///
/// let s = String::utf8(b"xyz".to_vec());
/// assert!(s.is_valid_encoding());
/// let s = String::utf8("π".to_string().into_bytes());
/// assert!(s.is_valid_encoding());
/// let s = String::utf8(b"abc\xFF\xFExyz".to_vec());
/// assert!(!s.is_valid_encoding());
///
/// let s = String::ascii(b"xyz".to_vec());
/// assert!(s.is_valid_encoding());
/// let s = String::ascii("π".to_string().into_bytes());
/// assert!(!s.is_valid_encoding());
/// let s = String::ascii(b"abc\xFF\xFExyz".to_vec());
/// assert!(!s.is_valid_encoding());
///
/// let s = String::binary(b"xyz".to_vec());
/// assert!(s.is_valid_encoding());
/// let s = String::binary("π".to_string().into_bytes());
/// assert!(s.is_valid_encoding());
/// let s = String::binary(b"abc\xFF\xFExyz".to_vec());
/// assert!(s.is_valid_encoding());
/// ```
///
/// [conventionally UTF-8]: crate::Encoding::Utf8
/// [ASCII]: crate::Encoding::Ascii
/// [binary]: crate::Encoding::Binary
/// [`String#valid_encoding?`]: https://ruby-doc.org/core-3.1.2/String.html#method-i-valid_encoding-3F
#[inline]
#[must_use]
pub fn is_valid_encoding(&self) -> bool {
self.inner.is_valid_encoding()
}
/// Reverse the characters in the string.
///
/// This function is encoding-aware. For `String`s with [UTF-8 encoding],
/// multi-byte Unicode characters are reversed treated as one element.
/// For `String`s with [ASCII encoding] or [binary encoding], this
/// function is equivalent to reversing the underlying byte slice.
///
/// # Examples
///
/// ```
/// use spinoso_string::String;
///
/// let mut s = String::utf8("εθ§".as_bytes().to_vec());
/// s.reverse();
/// assert_eq!(s, "θ§ε");
/// ```
///
/// [UTF-8 encoding]: crate::Encoding::Utf8
/// [ASCII encoding]: crate::Encoding::Ascii
/// [binary encoding]: crate::Encoding::Binary
#[inline]
pub fn reverse(&mut self) {
self.inner.reverse();
}
}
#[must_use]
fn chomp(string: &mut String, separator: Option<&[u8]>) -> bool {
if string.is_empty() {
return false;
}
match separator {
Some([]) => {
let original_len = string.len();
let mut iter = string.bytes().rev().peekable();
while let Some(&b'\n') = iter.peek() {
iter.next();
if let Some(&b'\r') = iter.peek() {
iter.next();
}
}
let truncate_to = iter.count();
string.inner.truncate(truncate_to);
truncate_to != original_len
}
Some(separator) if string.inner.ends_with(separator) => {
let original_len = string.len();
// This subtraction is guaranteed not to panic because
// `separator` is a substring of `buf`.
let truncate_to_len = original_len - separator.len();
string.inner.truncate(truncate_to_len);
// Separator is non-empty and we are always truncating, so this
// branch always modifies the buffer.
true
}
Some(_) => false,
None => {
let original_len = string.len();
let mut iter = string.bytes().rev().peekable();
match iter.peek() {
Some(&b'\n') => {
iter.next();
if let Some(&b'\r') = iter.peek() {
iter.next();
}
}
Some(b'\r') => {
iter.next();
}
Some(_) | None => {}
};
let truncate_to_len = iter.count();
string.inner.truncate(truncate_to_len);
truncate_to_len != original_len
}
}
}
#[cfg(test)]
mod tests {
use alloc::string::ToString;
use crate::center::CenterError;
use crate::String;
#[test]
fn center_returns_error_with_empty_padding() {
let s = String::utf8(b"jumbo".to_vec());
let center = s.center(10, Some(b""));
assert!(matches!(center, Err(CenterError::ZeroWidthPadding)));
let center = s.center(9, Some(b""));
assert!(matches!(center, Err(CenterError::ZeroWidthPadding)));
let center = s.center(1, Some(b""));
assert!(matches!(center, Err(CenterError::ZeroWidthPadding)));
let center = s.center(5, Some(b""));
assert!(matches!(center, Err(CenterError::ZeroWidthPadding)));
}
#[test]
fn strings_equality_is_reflexive() {
// ASCII only, all encodings valid
let utf8 = String::utf8(b"abc".to_vec());
let ascii = String::ascii(b"abc".to_vec());
let binary = String::binary(b"abc".to_vec());
assert_eq!(&utf8, &utf8);
assert_eq!(&ascii, &ascii);
assert_eq!(&binary, &binary);
// Invalid UTF-8
let utf8 = String::utf8(b"abc\xFE\xFF".to_vec());
let ascii = String::ascii(b"abc\xFE\xFF".to_vec());
let binary = String::binary(b"abc\xFE\xFF".to_vec());
assert_eq!(&utf8, &utf8);
assert_eq!(&ascii, &ascii);
assert_eq!(&binary, &binary);
// Multibyte UTF-8
let utf8 = String::utf8("εΎε°".to_string().into_bytes());
let ascii = String::ascii("εΎε°".to_string().into_bytes());
let binary = String::binary("εΎε°".to_string().into_bytes());
assert_eq!(&utf8, &utf8);
assert_eq!(&ascii, &ascii);
assert_eq!(&binary, &binary);
}
#[test]
fn strings_compare_equal_only_based_on_byte_content_with_valid_encoding() {
// ASCII only
let utf8 = String::utf8(b"abc".to_vec());
let ascii = String::ascii(b"abc".to_vec());
let binary = String::binary(b"abc".to_vec());
assert_eq!(utf8, ascii);
assert_eq!(ascii, utf8);
assert_eq!(utf8, binary);
assert_eq!(binary, utf8);
assert_eq!(binary, ascii);
assert_eq!(ascii, binary);
}
#[test]
fn strings_with_multibyte_utf8_content_require_compatible_encoding_to_compare_equal() {
let utf8 = String::utf8("εΎε°".to_string().into_bytes());
let ascii = String::ascii("εΎε°".to_string().into_bytes());
let binary = String::binary("εΎε°".to_string().into_bytes());
assert_ne!(utf8, ascii);
assert_ne!(ascii, utf8);
assert_ne!(utf8, binary);
assert_ne!(binary, utf8);
assert_ne!(binary, ascii);
assert_ne!(ascii, binary);
}
#[test]
fn strings_compare_unequal_with_equal_byte_content_without_valid_encoding() {
// ```
// [3.2.2] > utf8 = "abc\xFE\xFF"
// => "abc\xFE\xFF"
// [3.2.2] > utf8.encoding
// => #<Encoding:UTF-8>
// [3.2.2] > ascii = "abc\xFE\xFF"
// => "abc\xFE\xFF"
// [3.2.2] > ascii.force_encoding(Encoding::ASCII)
// => "abc\xFE\xFF"
// [3.2.2] > ascii.encoding
// => #<Encoding:US-ASCII>
// [3.2.2] > binary = "abc\xFE\xFF".b
// => "abc\xFE\xFF"
// [3.2.2] > binary.encoding
// => #<Encoding:ASCII-8BIT>
// [3.2.2] > utf8.ascii_only?
// => false
// [3.2.2] > ascii.ascii_only?
// => false
// [3.2.2] > binary.ascii_only?
// => false
// [3.2.2] > utf8 == ascii
// => false
// [3.2.2] > ascii == utf8
// => false
// [3.2.2] > utf8 == binary
// => false
// [3.2.2] > binary == utf8
// => false
// [3.2.2] > binary == ascii
// => false
// [3.2.2] > ascii == binary
// => false
// ```
let utf8 = String::utf8(b"abc\xFE\xFF".to_vec());
let ascii = String::ascii(b"abc\xFE\xFF".to_vec());
let binary = String::binary(b"abc\xFE\xFF".to_vec());
assert_ne!(utf8, ascii);
assert_ne!(ascii, utf8);
assert_ne!(utf8, binary);
assert_ne!(binary, utf8);
assert_ne!(binary, ascii);
assert_ne!(ascii, binary);
}
#[test]
fn byteindex_supports_needle_and_haystack_of_different_encodings() {
// all encodings for the receiver
let utf8 = String::utf8("abcππ»".as_bytes().to_vec());
let ascii = String::ascii(b"abc\xFE\xFF".to_vec());
let binary = String::binary(b"abc\xFE\xFF".to_vec());
// Empty string as needle
assert_eq!(utf8.byteindex([], None), Some(0));
assert_eq!(ascii.byteindex([], None), Some(0));
assert_eq!(binary.byteindex([], None), Some(0));
// ASCII needles
let ascii_needle = String::ascii(b"b".to_vec());
assert_eq!(utf8.byteindex(&ascii_needle, None), Some(1));
assert_eq!(ascii.byteindex(&ascii_needle, None), Some(1));
assert_eq!(binary.byteindex(&ascii_needle, None), Some(1));
// Binary needles
let binray_needle = String::binary(b"b".to_vec());
assert_eq!(utf8.byteindex(&binray_needle, None), Some(1));
assert_eq!(ascii.byteindex(&binray_needle, None), Some(1));
assert_eq!(binary.byteindex(&binray_needle, None), Some(1));
// UTF-8 needles with multibyte chars
let utf8_needle = String::utf8("ππ»".as_bytes().to_vec());
assert_eq!(utf8.byteindex(&utf8_needle, None), Some(3));
assert_eq!(ascii.byteindex(&utf8_needle, None), None);
assert_eq!(binary.byteindex(&utf8_needle, None), None);
// UTF-8 encoded strings that have binary contents.
let utf8_needle = String::utf8([b'b', b'c'].to_vec());
assert_eq!(utf8.byteindex(&utf8_needle, None), Some(1));
assert_eq!(ascii.byteindex(&utf8_needle, None), Some(1));
assert_eq!(binary.byteindex(&utf8_needle, None), Some(1));
}
#[test]
fn byteindex_support_specifiying_byte_position_to_start_search() {
let utf8 = String::utf8("a π has 4 bytes".as_bytes().to_vec());
// Empty string as needle
let needle = String::utf8("a".as_bytes().to_vec());
assert_eq!(utf8.byteindex(&needle, None), Some(0));
assert_eq!(utf8.byteindex(&needle, Some(0)), Some(0));
assert_eq!(utf8.byteindex(&needle, Some(1)), Some(8));
// In the middle of π
assert_eq!(utf8.byteindex(&needle, Some(3)), Some(8));
assert_eq!(utf8.byteindex(&needle, Some(8)), Some(8));
assert_eq!(utf8.byteindex(&needle, Some(9)), None);
}
#[test]
fn rindex_support_empty_string_and_empty_needle() {
// Empty needle
assert_eq!(String::ascii(b"foo".to_vec()).rindex("", None), Some(3));
// Empty haystack
assert_eq!(String::ascii(b"".to_vec()).rindex("foo", None), None);
// Empty haystack and needle
assert_eq!(String::ascii(b"".to_vec()).rindex("", None), Some(0));
}
}