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
//! 展示字符 {}
use crate::ascii;
use crate::slice;
use crate::str::from_utf8_unchecked_mut;
use crate::unicode::printable::is_printable;
use crate::unicode::{self, conversions};
use super::*;
impl char {
/// `char` 可以拥有所有权的最高有效代码点 `'\u{10FFFF}'`。
///
/// # Examples
///
/// ```
/// # fn something_which_returns_char() -> char { 'a' }
/// let c: char = something_which_returns_char();
/// assert!(c <= char::MAX);
///
/// let value_at_max = char::MAX as u32;
/// assert_eq!(char::from_u32(value_at_max), Some('\u{10FFFF}'));
/// assert_eq!(char::from_u32(value_at_max + 1), None);
/// ```
#[stable(feature = "assoc_char_consts", since = "1.52.0")]
pub const MAX: char = '\u{10ffff}';
/// `U+FFFD REPLACEMENT CHARACTER` () 在 Unicode 中用于表示解码错误。
///
/// 例如,当将格式错误的 UTF-8 字节提供给 [`String::from_utf8_lossy`](../std/string/struct.String.html#method.from_utf8_lossy) 时,就会发生这种情况。
///
///
#[stable(feature = "assoc_char_consts", since = "1.52.0")]
pub const REPLACEMENT_CHARACTER: char = '\u{FFFD}';
/// `char` 和 `str` 方法的 Unicode 部分所基于的 [Unicode](https://www.unicode.org/) 版本。
///
/// Unicode 的新版本会定期发布,随后会更新标准库中取决于 Unicode 的所有方法。
/// 因此,某些 `char` 和 `str` 方法的行为以及该常量的值会随时间变化。
/// 这不是一个突破性的改变。
///
/// 版本编号方案在 [Unicode 11.0 或更高版本,第 3.1 节 Unicode 标准版本](https://www.unicode.org/versions/Unicode11.0.0/ch03.pdf#page=4) 中进行了说明。
///
///
///
#[stable(feature = "assoc_char_consts", since = "1.52.0")]
pub const UNICODE_VERSION: (u8, u8, u8) = crate::unicode::UNICODE_VERSION;
/// 在 `iter` 中的 UTF-16 编码的代码点上创建一个迭代器,将不成对的代理返回为 `Err`s。
///
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// // 𝄞mus<invalid>ic<invalid>
/// let v = [
/// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
/// ];
///
/// assert_eq!(
/// char::decode_utf16(v)
/// .map(|r| r.map_err(|e| e.unpaired_surrogate()))
/// .collect::<Vec<_>>(),
/// vec![
/// Ok('𝄞'),
/// Ok('m'), Ok('u'), Ok('s'),
/// Err(0xDD1E),
/// Ok('i'), Ok('c'),
/// Err(0xD834)
/// ]
/// );
/// ```
///
/// 通过用替换字符替换 `Err` 结果,可以获得有损解码器:
///
/// ```
/// // 𝄞mus<invalid>ic<invalid>
/// let v = [
/// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
/// ];
///
/// assert_eq!(
/// char::decode_utf16(v)
/// .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
/// .collect::<String>(),
/// "𝄞mus�ic�"
/// );
/// ```
#[stable(feature = "assoc_char_funcs", since = "1.52.0")]
#[inline]
pub fn decode_utf16<I: IntoIterator<Item = u16>>(iter: I) -> DecodeUtf16<I::IntoIter> {
super::decode::decode_utf16(iter)
}
/// 将 `u32` 转换为 `char`。
///
/// 请注意,所有的 `char`s 都是有效的 [`u32`],并且可以使用以下命令将其强制转换为 1
/// [`as`](../std/keyword.as.html):
///
/// ```
/// let c = '💯';
/// let i = c as u32;
///
/// assert_eq!(128175, i);
/// ```
///
/// 但是,相反的情况并非如此:并非所有有效的 [u32] 都是有效的 char。
/// 如果输入不是 `char` 的有效值,`from_u32()` 将返回 `None`。
///
/// 有关忽略这些检查的该函数的不安全版本,请参见 [`from_u32_unchecked`]。
///
///
/// [`from_u32_unchecked`]: #method.from_u32_unchecked
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// let c = char::from_u32(0x2764);
///
/// assert_eq!(Some('❤'), c);
/// ```
///
/// 当输入不是有效的 `char` 时返回 `None`:
///
/// ```
/// let c = char::from_u32(0x110000);
///
/// assert_eq!(None, c);
/// ```
///
#[stable(feature = "assoc_char_funcs", since = "1.52.0")]
#[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
#[must_use]
#[inline]
pub const fn from_u32(i: u32) -> Option<char> {
super::convert::from_u32(i)
}
/// 将 `u32` 转换为 `char`,而忽略有效性。
///
/// 请注意,所有的 `char`s 都是有效的 [`u32`],并且可以使用以下命令将其强制转换为 1
/// `as`:
///
/// ```
/// let c = '💯';
/// let i = c as u32;
///
/// assert_eq!(128175, i);
/// ```
///
/// 但是,相反的情况并非如此:并非所有有效的 [u32] 都是有效的 char。
/// `from_u32_unchecked()` 将忽略这一点,并盲目地转换为 `char`,可能会创建一个无效的。
///
///
/// # Safety
///
/// 该函数是不安全的,因为它可能创建无效的 `char` 值。
///
/// 有关此函数的安全版本,请参见 [`from_u32`] 函数。
///
/// [`from_u32`]: #method.from_u32
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// let c = unsafe { char::from_u32_unchecked(0x2764) };
///
/// assert_eq!('❤', c);
/// ```
#[stable(feature = "assoc_char_funcs", since = "1.52.0")]
#[rustc_const_unstable(feature = "const_char_from_u32_unchecked", issue = "89259")]
#[must_use]
#[inline]
pub const unsafe fn from_u32_unchecked(i: u32) -> char {
// SAFETY: 调用者必须坚持安全保证。
unsafe { super::convert::from_u32_unchecked(i) }
}
/// 将给定基数中的数字转换为 `char`。
///
/// 这里的 'radix' 有时也称为 'base'。
/// 基数 2 表示二进制数,以十进制表示的十进制,以十六进制表示十六进制的基数,以给出一些公共值。
///
/// 支持任意基数。
///
/// 如果输入不是给定基数中的数字,`from_digit()` 将返回 `None`。
///
/// # Panics
///
/// 如果给定的基数大于 36,就会出现 panics。
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// let c = char::from_digit(4, 10);
///
/// assert_eq!(Some('4'), c);
///
/// // 十进制 11 是以 16 为底的一位数字
/// let c = char::from_digit(11, 16);
///
/// assert_eq!(Some('b'), c);
/// ```
///
/// 当输入不是数字时返回 `None`:
///
/// ```
/// let c = char::from_digit(20, 10);
///
/// assert_eq!(None, c);
/// ```
///
/// 传递较大的基数,导致 panic:
///
/// ```should_panic
/// // 这个 panics
/// let _c = char::from_digit(1, 37);
/// ```
///
#[stable(feature = "assoc_char_funcs", since = "1.52.0")]
#[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
#[must_use]
#[inline]
pub const fn from_digit(num: u32, radix: u32) -> Option<char> {
super::convert::from_digit(num, radix)
}
/// 检查 `char` 是否为给定基数中的数字。
///
/// 这里的 'radix' 有时也称为 'base'。
/// 基数 2 表示二进制数,以十进制表示的十进制,以十六进制表示十六进制的基数,以给出一些公共值。
///
/// 支持任意基数。
///
/// 与 [`is_numeric()`] 相比,此函数仅识别字符 `0-9`,`a-z` 和 `A-Z`。
///
/// 'Digit' 定义为仅以下字符:
///
/// * `0-9`
/// * `a-z`
/// * `A-Z`
///
/// 要更全面地了解 'digit',请参见 [`is_numeric()`]。
///
/// [`is_numeric()`]: #method.is_numeric
///
/// # Panics
///
/// 如果给定的基数大于 36,就会出现 panics。
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// assert!('1'.is_digit(10));
/// assert!('f'.is_digit(16));
/// assert!(!'f'.is_digit(10));
/// ```
///
/// 传递较大的基数,导致 panic:
///
/// ```should_panic
/// // 这个 panics
/// '1'.is_digit(37);
/// ```
///
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_digit(self, radix: u32) -> bool {
self.to_digit(radix).is_some()
}
/// 将 `char` 转换为给定基数的数字。
///
/// 这里的 'radix' 有时也称为 'base'。
/// 基数 2 表示二进制数,以十进制表示的十进制,以十六进制表示十六进制的基数,以给出一些公共值。
///
/// 支持任意基数。
///
/// 'Digit' 定义为仅以下字符:
///
/// * `0-9`
/// * `a-z`
/// * `A-Z`
///
/// # Errors
///
/// 如果 `char` 未引用给定基数中的数字,则返回 `None`。
///
/// # Panics
///
/// 如果给定的基数大于 36,就会出现 panics。
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// assert_eq!('1'.to_digit(10), Some(1));
/// assert_eq!('f'.to_digit(16), Some(15));
/// ```
///
/// 传递非数字会导致失败:
///
/// ```
/// assert_eq!('f'.to_digit(10), None);
/// assert_eq!('z'.to_digit(16), None);
/// ```
///
/// 传递较大的基数,导致 panic:
///
/// ```should_panic
/// // 这个 panics
/// let _ = '1'.to_digit(37);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_char_convert", since = "1.67.0")]
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_digit(self, radix: u32) -> Option<u32> {
// 如果不是数字,则将创建一个大于基数的数字。
let mut digit = (self as u32).wrapping_sub('0' as u32);
if radix > 10 {
assert!(radix <= 36, "to_digit: radix is too high (maximum 36)");
if digit < 10 {
return Some(digit);
}
// 强制设置第 6 位以确保 ascii 是小写的。
digit = (self as u32 | 0b10_0000).wrapping_sub('a' as u32).saturating_add(10);
}
// FIXME: 一旦 then_some 是 const fn,就在这里使用它
if digit < radix { Some(digit) } else { None }
}
/// 返回一个迭代器,该迭代器将字符的十六进制 Unicode 转义生成为 `char`s。
///
/// 这将使用 `\u{NNNNNN}` 格式的 Rust 语法对字符进行转义,其中 `NNNNNN` 是十六进制表示形式。
///
///
/// # Examples
///
/// 作为迭代器:
///
/// ```
/// for c in '❤'.escape_unicode() {
/// print!("{c}");
/// }
/// println!();
/// ```
///
/// 直接使用 `println!`:
///
/// ```
/// println!("{}", '❤'.escape_unicode());
/// ```
///
/// 两者都等同于:
///
/// ```
/// println!("\\u{{2764}}");
/// ```
///
/// 使用 [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
///
/// ```
/// assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
/// ```
///
#[must_use = "this returns the escaped char as an iterator, \
without modifying the original"]
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn escape_unicode(self) -> EscapeUnicode {
EscapeUnicode::new(self)
}
/// `escape_debug` 的扩展版本,可选择允许转义扩展字素代码点、单引号和双引号。
/// 这允许我们在字符串开头时更好地格式化像非空格标记这样的字符,并允许转义字符中的单引号和字符串中的双引号。
///
///
///
#[inline]
pub(crate) fn escape_debug_ext(self, args: EscapeDebugExtArgs) -> EscapeDebug {
match self {
'\0' => EscapeDebug::backslash(ascii::Char::Digit0),
'\t' => EscapeDebug::backslash(ascii::Char::SmallT),
'\r' => EscapeDebug::backslash(ascii::Char::SmallR),
'\n' => EscapeDebug::backslash(ascii::Char::SmallN),
'\\' => EscapeDebug::backslash(ascii::Char::ReverseSolidus),
'\"' if args.escape_double_quote => EscapeDebug::backslash(ascii::Char::QuotationMark),
'\'' if args.escape_single_quote => EscapeDebug::backslash(ascii::Char::Apostrophe),
_ if args.escape_grapheme_extended && self.is_grapheme_extended() => {
EscapeDebug::from_unicode(self.escape_unicode())
}
_ if is_printable(self) => EscapeDebug::printable(self),
_ => EscapeDebug::from_unicode(self.escape_unicode()),
}
}
/// 返回一个迭代器,该迭代器将字符的字面量转义码生成为 `char`s。
///
/// 这将转义类似于 `str` 或 `char` 的 [`Debug`](core::fmt::Debug) 实现的字符。
///
///
/// # Examples
///
/// 作为迭代器:
///
/// ```
/// for c in '\n'.escape_debug() {
/// print!("{c}");
/// }
/// println!();
/// ```
///
/// 直接使用 `println!`:
///
/// ```
/// println!("{}", '\n'.escape_debug());
/// ```
///
/// 两者都等同于:
///
/// ```
/// println!("\\n");
/// ```
///
/// 使用 [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
///
/// ```
/// assert_eq!('\n'.escape_debug().to_string(), "\\n");
/// ```
///
#[must_use = "this returns the escaped char as an iterator, \
without modifying the original"]
#[stable(feature = "char_escape_debug", since = "1.20.0")]
#[inline]
pub fn escape_debug(self) -> EscapeDebug {
self.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL)
}
/// 返回一个迭代器,该迭代器将字符的字面量转义码生成为 `char`s。
///
/// 选择默认值时会偏向于生成在多种语言 (包括 C++ 11 和类似的 C 系列语言) 中都合法的字面量。
/// 确切的规则是:
///
/// * 制表符被转义为 `\t`。
/// * 回车符被转义为 `\r`。
/// * 换行符转为 `\n`。
/// * 单引号转义为 `\'`。
/// * 双引号转义为 `\"`。
/// * 反斜杠转义为 `\\`。
/// * `可打印 ASCII` 范围 `0x20` .. 中的任何字符 `0x7e` (含 `0x7e`) 不会转义。
/// * 所有其他字符均使用十六进制 Unicode 转义; 请参见 [`escape_unicode`]。
///
/// [`escape_unicode`]: #method.escape_unicode
///
/// # Examples
///
/// 作为迭代器:
///
/// ```
/// for c in '"'.escape_default() {
/// print!("{c}");
/// }
/// println!();
/// ```
///
/// 直接使用 `println!`:
///
/// ```
/// println!("{}", '"'.escape_default());
/// ```
///
/// 两者都等同于:
///
/// ```
/// println!("\\\"");
/// ```
///
/// 使用 [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
///
/// ```
/// assert_eq!('"'.escape_default().to_string(), "\\\"");
/// ```
///
///
///
///
#[must_use = "this returns the escaped char as an iterator, \
without modifying the original"]
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn escape_default(self) -> EscapeDefault {
match self {
'\t' => EscapeDefault::backslash(ascii::Char::SmallT),
'\r' => EscapeDefault::backslash(ascii::Char::SmallR),
'\n' => EscapeDefault::backslash(ascii::Char::SmallN),
'\\' | '\'' | '"' => EscapeDefault::backslash(self.as_ascii().unwrap()),
'\x20'..='\x7e' => EscapeDefault::printable(self.as_ascii().unwrap()),
_ => EscapeDefault::from_unicode(self.escape_unicode()),
}
}
/// 返回以 UTF-8 编码时此 `char` 所需的字节数。
///
/// 该字节数始终在 1 到 4 之间 (含 1 和 4)。
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// let len = 'A'.len_utf8();
/// assert_eq!(len, 1);
///
/// let len = 'ß'.len_utf8();
/// assert_eq!(len, 2);
///
/// let len = 'ℝ'.len_utf8();
/// assert_eq!(len, 3);
///
/// let len = '💣'.len_utf8();
/// assert_eq!(len, 4);
/// ```
///
/// `&str` 类型保证其内容为 UTF-8,因此我们可以比较将每个代码点表示为 `char` 相对于 `&str` 本身所花费的长度:
///
///
/// ```
/// // 作为字符
/// let eastern = '東';
/// let capital = '京';
///
/// // 两者都可以表示为三个字节
/// assert_eq!(3, eastern.len_utf8());
/// assert_eq!(3, capital.len_utf8());
///
/// // 作为 &str,这两个编码为 UTF-8
/// let tokyo = "東京";
///
/// let len = eastern.len_utf8() + capital.len_utf8();
///
/// // 我们可以看到它们总共占用六个字节...
/// assert_eq!(6, tokyo.len());
///
/// // ... 就像 &str
/// assert_eq!(len, tokyo.len());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
#[inline]
pub const fn len_utf8(self) -> usize {
len_utf8(self as u32)
}
/// 返回以 UTF-16 编码时 `char` 所需的 16 位代码单元的数量。
///
/// 对于 [basic multilingual plane] 或 [supplementary planes] 中的 unicode 标量值,代码单元的数量始终为 1 或 2。
///
///
/// 有关此概念的更多说明,请参见 [`len_utf8()`] 的文档。该函数是一个镜像,但是用于 UTF-16 而不是 UTF-8。
///
/// [basic multilingual plane]: http://www.unicode.org/glossary/#basic_multilingual_plane
/// [supplementary planes]: http://www.unicode.org/glossary/#supplementary_planes
/// [`len_utf8()`]: #method.len_utf8
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// let n = 'ß'.len_utf16();
/// assert_eq!(n, 1);
///
/// let len = '💣'.len_utf16();
/// assert_eq!(len, 2);
/// ```
///
///
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")]
#[inline]
pub const fn len_utf16(self) -> usize {
let ch = self as u32;
if (ch & 0xFFFF) == ch { 1 } else { 2 }
}
/// 将此字符编码为 UTF-8 到提供的字节缓冲区中,然后返回包含编码字符的缓冲区的子切片。
///
///
/// # Panics
///
/// 如果缓冲区不够大,就会出现 panics。
/// 长度为四的缓冲区足够大,可以对任何 `char` 进行编码。
///
/// # Examples
///
/// 在这两个示例中,'ß' 占用两个字节进行编码。
///
/// ```
/// let mut b = [0; 2];
///
/// let result = 'ß'.encode_utf8(&mut b);
///
/// assert_eq!(result, "ß");
///
/// assert_eq!(result.len(), 2);
/// ```
///
/// 缓冲区太小:
///
/// ```should_panic
/// let mut b = [0; 1];
///
/// // 这个 panics
/// 'ß'.encode_utf8(&mut b);
/// ```
#[stable(feature = "unicode_encode_char", since = "1.15.0")]
#[inline]
pub fn encode_utf8(self, dst: &mut [u8]) -> &mut str {
// SAFETY: `char` 不是代理,所以这是有效的 UTF-8。
unsafe { from_utf8_unchecked_mut(encode_utf8_raw(self as u32, dst)) }
}
/// 将此字符编码为 UTF-16 到提供的 `u16` 缓冲区中,然后返回包含编码字符的缓冲区的子切片。
///
///
/// # Panics
///
/// 如果缓冲区不够大,就会出现 panics。
/// 长度为 2 的缓冲区足够大,可以对任何 `char` 进行编码。
///
/// # Examples
///
/// 在这两个示例中,'𝕊' 都需要两个 u16 进行编码。
///
/// ```
/// let mut b = [0; 2];
///
/// let result = '𝕊'.encode_utf16(&mut b);
///
/// assert_eq!(result.len(), 2);
/// ```
///
/// 缓冲区太小:
///
/// ```should_panic
/// let mut b = [0; 1];
///
/// // 这个 panics
/// '𝕊'.encode_utf16(&mut b);
/// ```
#[stable(feature = "unicode_encode_char", since = "1.15.0")]
#[inline]
pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] {
encode_utf16_raw(self as u32, dst)
}
/// 如果此 `char` 具有 `Alphabetic` 属性,则返回 `true`。
///
/// `Alphabetic` 在 [Unicode 标准][Unicode Standard] 的第 4 章 (字符属性) 中描述并在 [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`] 中指定。
///
///
/// [Unicode Standard]: https://www.unicode.org/versions/latest/
/// [ucd]: https://www.unicode.org/reports/tr44/
/// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// assert!('a'.is_alphabetic());
/// assert!('京'.is_alphabetic());
///
/// let c = '💝';
/// // love 有很多东西,但它不是按字母顺序排列的
/// assert!(!c.is_alphabetic());
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_alphabetic(self) -> bool {
match self {
'a'..='z' | 'A'..='Z' => true,
c => c > '\x7f' && unicode::Alphabetic(c),
}
}
/// 如果此 `char` 具有 `Lowercase` 属性,则返回 `true`。
///
/// `Lowercase` 在 [Unicode 标准][Unicode Standard] 的第 4 章 (字符属性) 中描述并在 [Unicode 字符数据库][ucd] [`DerivedCoreProperties.txt`] 中指定。
///
///
/// [Unicode Standard]: https://www.unicode.org/versions/latest/
/// [ucd]: https://www.unicode.org/reports/tr44/
/// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// assert!('a'.is_lowercase());
/// assert!('δ'.is_lowercase());
/// assert!(!'A'.is_lowercase());
/// assert!(!'Δ'.is_lowercase());
///
/// // 各种中文脚本和标点符号没有大小写,因此:
/// assert!(!'中'.is_lowercase());
/// assert!(!' '.is_lowercase());
/// ```
///
/// 在 const 上下文中:
///
/// ```
/// #![feature(const_unicode_case_lookup)]
/// const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
/// assert!(!CAPITAL_DELTA_IS_LOWERCASE);
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_unicode_case_lookup", issue = "101400")]
#[inline]
pub const fn is_lowercase(self) -> bool {
match self {
'a'..='z' => true,
c => c > '\x7f' && unicode::Lowercase(c),
}
}
/// 如果此 `char` 具有 `Uppercase` 属性,则返回 `true`。
///
/// `Uppercase` 在 [Unicode 标准][Unicode Standard] 的第 4 章 (字符属性) 中描述并在 [Unicode 字符数据库][ucd] [`DerivedCoreProperties.txt`] 中指定。
///
///
/// [Unicode Standard]: https://www.unicode.org/versions/latest/
/// [ucd]: https://www.unicode.org/reports/tr44/
/// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// assert!(!'a'.is_uppercase());
/// assert!(!'δ'.is_uppercase());
/// assert!('A'.is_uppercase());
/// assert!('Δ'.is_uppercase());
///
/// // 各种中文脚本和标点符号没有大小写,因此:
/// assert!(!'中'.is_uppercase());
/// assert!(!' '.is_uppercase());
/// ```
///
/// 在 const 上下文中:
///
/// ```
/// #![feature(const_unicode_case_lookup)]
/// const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
/// assert!(CAPITAL_DELTA_IS_UPPERCASE);
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_unicode_case_lookup", issue = "101400")]
#[inline]
pub const fn is_uppercase(self) -> bool {
match self {
'A'..='Z' => true,
c => c > '\x7f' && unicode::Uppercase(c),
}
}
/// 如果此 `char` 具有 `White_Space` 属性,则返回 `true`。
///
/// `White_Space` 在 [Unicode 字符数据库][ucd] [`PropList.txt`] 中指定。
///
/// [ucd]: https://www.unicode.org/reports/tr44/
/// [`PropList.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// assert!(' '.is_whitespace());
///
/// // 行中断
/// assert!('\n'.is_whitespace());
///
/// // 一个不间断空格
/// assert!('\u{A0}'.is_whitespace());
///
/// assert!(!'越'.is_whitespace());
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_whitespace(self) -> bool {
match self {
' ' | '\x09'..='\x0d' => true,
c => c > '\x7f' && unicode::White_Space(c),
}
}
/// 如果此 `char` 满足 [`is_alphabetic()`] 或 [`is_numeric()`],则返回 `true`。
///
/// [`is_alphabetic()`]: #method.is_alphabetic
/// [`is_numeric()`]: #method.is_numeric
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// assert!('٣'.is_alphanumeric());
/// assert!('7'.is_alphanumeric());
/// assert!('৬'.is_alphanumeric());
/// assert!('¾'.is_alphanumeric());
/// assert!('①'.is_alphanumeric());
/// assert!('K'.is_alphanumeric());
/// assert!('و'.is_alphanumeric());
/// assert!('藏'.is_alphanumeric());
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_alphanumeric(self) -> bool {
self.is_alphabetic() || self.is_numeric()
}
/// 如果此 `char` 具有控制代码的常规类别,则返回 `true`。
///
/// [Unicode 标准] 的第 4 章 (字符属性) 中描述了控制代码 (具有 `Cc` 的常规类别的代码点),并在 [Unicode 字符数据库][ucd] [`UnicodeData.txt`] 中进行了指定。
///
///
/// [Unicode Standard]: https://www.unicode.org/versions/latest/
/// [ucd]: https://www.unicode.org/reports/tr44/
/// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// // U+009C,字符串终止符
/// assert!(''.is_control());
/// assert!(!'q'.is_control());
/// ```
///
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_control(self) -> bool {
unicode::Cc(self)
}
/// 如果此 `char` 具有 `Grapheme_Extend` 属性,则返回 `true`。
///
/// `Grapheme_Extend` 在 [Unicode 标准附件 #29 (Unicode 文本分割)][uax29] 中描述并在 [Unicode 字符数据库][ucd] [`DerivedCoreProperties.txt`] 中指定。
///
///
/// [uax29]: https://www.unicode.org/reports/tr29/
/// [ucd]: https://www.unicode.org/reports/tr44/
/// [`DerivedCoreProperties.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt
///
#[must_use]
#[inline]
pub(crate) fn is_grapheme_extended(self) -> bool {
unicode::Grapheme_Extend(self)
}
/// 如果此 `char` 具有数字的常规类别之一,则返回 `true`。
///
/// 在 [Unicode 字符数据库][ucd] [`UnicodeData.txt`] 中指定了数字的常规类别 (`Nd` 表示十进制数字,`Nl` 表示类似字母的数字字符,`No` 表示其他数字字符)。
///
/// This method doesn't cover everything that could be considered a number, e.g. ideographic numbers like '三'.
/// 如果您想要包括具有重叠目的的字符在内的所有内容,那么您可能需要使用 unicode 或语言处理库来公开适当的字符属性,而不是查看 unicode 类别。
///
///
/// 如果要解析 ASCII 十进制数字 (0-9) 或 ASCII base-N,请改用 `is_ascii_digit` 或 `is_digit`。
///
/// [Unicode Standard]: https://www.unicode.org/versions/latest/
/// [ucd]: https://www.unicode.org/reports/tr44/
/// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
///
/// # Examples
///
/// 基本用法:
///
/// ```
/// assert!('٣'.is_numeric());
/// assert!('7'.is_numeric());
/// assert!('৬'.is_numeric());
/// assert!('¾'.is_numeric());
/// assert!('①'.is_numeric());
/// assert!(!'K'.is_numeric());
/// assert!(!'و'.is_numeric());
/// assert!(!'藏'.is_numeric());
/// assert!(!'三'.is_numeric());
/// ```
///
///
///
///
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_numeric(self) -> bool {
match self {
'0'..='9' => true,
c => c > '\x7f' && unicode::N(c),
}
}
/// 返回一个迭代器,该迭代器将这个 `char` 的小写字母映射为一个或多个
/// `char`s.
///
/// 如果此 `char` 没有小写映射,则迭代器将产生相同的 `char`。
///
/// 如果此 `char` 具有 [Unicode 字符数据库][ucd] [`UnicodeData.txt`] 给出的一对一小写映射,则迭代器将产生该 `char`。
///
/// [ucd]: https://www.unicode.org/reports/tr44/
/// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
///
/// 如果此 `char` 需要特殊考虑 (例如,多个 char),则迭代器将产生 [`SpecialCasing.txt`] 给定的 char。
///
/// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
///
/// 此操作无需裁剪即可执行无条件映射。即,转换独立于上下文和语言。
///
/// 在 [Unicode 标准][Unicode Standard] 中,第 4 章 (字符属性) 通常讨论大小写映射,而第 3 章 (一致性) 讨论大小写转换的默认算法。
///
///
/// [Unicode Standard]: https://www.unicode.org/versions/latest/
///
/// # Examples
///
/// 作为迭代器:
///
/// ```
/// for c in 'İ'.to_lowercase() {
/// print!("{c}");
/// }
/// println!();
/// ```
///
/// 直接使用 `println!`:
///
/// ```
/// println!("{}", 'İ'.to_lowercase());
/// ```
///
/// 两者都等同于:
///
/// ```
/// println!("i\u{307}");
/// ```
///
/// 使用 [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
///
/// ```
/// assert_eq!('C'.to_lowercase().to_string(), "c");
///
/// // 有时结果是多个字符:
/// assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");
///
/// // 同时没有大写和小写字母的字符会转换成自己。
/////
/// assert_eq!('山'.to_lowercase().to_string(), "山");
/// ```
///
///
///
#[must_use = "this returns the lowercase character as a new iterator, \
without modifying the original"]
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_lowercase(self) -> ToLowercase {
ToLowercase(CaseMappingIter::new(conversions::to_lower(self)))
}
/// 返回一个迭代器,该迭代器将这个 `char` 的大写映射生成为一个或多个
/// `char`s.
///
/// 如果此 `char` 没有大写映射,则迭代器生成相同的 `char`。
///
/// 如果此 `char` 具有 [Unicode 字符数据库][ucd] [`UnicodeData.txt`] 给出的一对一大写映射,则迭代器将产生该 `char`。
///
/// [ucd]: https://www.unicode.org/reports/tr44/
/// [`UnicodeData.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
///
/// 如果此 `char` 需要特殊考虑 (例如,多个 char),则迭代器将产生 [`SpecialCasing.txt`] 给定的 char。
///
/// [`SpecialCasing.txt`]: https://www.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
///
/// 此操作无需裁剪即可执行无条件映射。即,转换独立于上下文和语言。
///
/// 在 [Unicode 标准][Unicode Standard] 中,第 4 章 (字符属性) 通常讨论大小写映射,而第 3 章 (一致性) 讨论大小写转换的默认算法。
///
///
/// [Unicode Standard]: https://www.unicode.org/versions/latest/
///
/// # Examples
///
/// 作为迭代器:
///
/// ```
/// for c in 'ß'.to_uppercase() {
/// print!("{c}");
/// }
/// println!();
/// ```
///
/// 直接使用 `println!`:
///
/// ```
/// println!("{}", 'ß'.to_uppercase());
/// ```
///
/// 两者都等同于:
///
/// ```
/// println!("SS");
/// ```
///
/// 使用 [`to_string`](../std/string/trait.ToString.html#tymethod.to_string):
///
/// ```
/// assert_eq!('c'.to_uppercase().to_string(), "C");
///
/// // 有时结果是多个字符:
/// assert_eq!('ß'.to_uppercase().to_string(), "SS");
///
/// // 同时没有大写和小写字母的字符会转换成自己。
/////
/// assert_eq!('山'.to_uppercase().to_string(), "山");
/// ```
///
/// # 关于语言环境说明
///
/// 在土耳其语中,相当于 'i' 的拉丁语具有 5 种形式,而不是 2 种形式:
///
/// * 'Dotless': I/ı,有时写成 ï
/// * 'Dotted': İ / i
///
/// 注意,小写的点缀 'i' 与拉丁字母相同。Therefore:
///
/// ```
/// let upper_i = 'i'.to_uppercase().to_string();
/// ```
///
/// `upper_i` 的值在此取决于文本的语言:如果我们在 `en-US` 中,则应为 `"I"`,但如果我们在 `tr_TR` 中,则应为 `"İ"`。
/// `to_uppercase()` 没有考虑到这一点,因此:
///
/// ```
/// let upper_i = 'i'.to_uppercase().to_string();
///
/// assert_eq!(upper_i, "I");
/// ```
///
/// 适用于多种语言。
///
///
///
///
#[must_use = "this returns the uppercase character as a new iterator, \
without modifying the original"]
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn to_uppercase(self) -> ToUppercase {
ToUppercase(CaseMappingIter::new(conversions::to_upper(self)))
}
/// 检查该值是否在 ASCII 范围内。
///
/// # Examples
///
/// ```
/// let ascii = 'a';
/// let non_ascii = '❤';
///
/// assert!(ascii.is_ascii());
/// assert!(!non_ascii.is_ascii());
/// ```
#[must_use]
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")]
#[inline]
pub const fn is_ascii(&self) -> bool {
*self as u32 <= 0x7F
}
/// 如果值在 ASCII 范围内,则返回 `Some`,否则返回 `None`。
///
/// 当您将值传递给可以采用 [`ascii::Char`] 的其他东西时,这比 [`Self::is_ascii`] 更受欢迎,而不是需要再次检查其自身是否为 ASCII 值。
///
///
///
#[must_use]
#[unstable(feature = "ascii_char", issue = "110998")]
#[inline]
pub const fn as_ascii(&self) -> Option<ascii::Char> {
if self.is_ascii() {
// SAFETY: 刚刚检查过这是 ASCII。
Some(unsafe { ascii::Char::from_u8_unchecked(*self as u8) })
} else {
None
}
}
/// 使值的副本等效于其 ASCII 大写字母。
///
/// ASCII 字母 'a' 到 'z' 映射到 'A' 到 'Z',但是非 ASCII 字母不变。
///
/// 要就地将值大写,请使用 [`make_ascii_uppercase()`]。
///
/// 要除非 ASCII 字符外还使用大写 ASCII 字符,请使用 [`to_uppercase()`]。
///
///
/// # Examples
///
/// ```
/// let ascii = 'a';
/// let non_ascii = '❤';
///
/// assert_eq!('A', ascii.to_ascii_uppercase());
/// assert_eq!('❤', non_ascii.to_ascii_uppercase());
/// ```
///
/// [`make_ascii_uppercase()`]: #method.make_ascii_uppercase
/// [`to_uppercase()`]: #method.to_uppercase
///
#[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
#[inline]
pub const fn to_ascii_uppercase(&self) -> char {
if self.is_ascii_lowercase() {
(*self as u8).ascii_change_case_unchecked() as char
} else {
*self
}
}
/// 以等效的 ASCII 小写形式复制值。
///
/// ASCII 字母 'A' 到 'Z' 映射到 'a' 到 'z',但是非 ASCII 字母不变。
///
/// 要就地小写该值,请使用 [`make_ascii_lowercase()`]。
///
/// 要除非 ASCII 字符外还使用小写 ASCII 字符,请使用 [`to_lowercase()`]。
///
///
/// # Examples
///
/// ```
/// let ascii = 'A';
/// let non_ascii = '❤';
///
/// assert_eq!('a', ascii.to_ascii_lowercase());
/// assert_eq!('❤', non_ascii.to_ascii_lowercase());
/// ```
///
/// [`make_ascii_lowercase()`]: #method.make_ascii_lowercase
/// [`to_lowercase()`]: #method.to_lowercase
///
#[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
#[inline]
pub const fn to_ascii_lowercase(&self) -> char {
if self.is_ascii_uppercase() {
(*self as u8).ascii_change_case_unchecked() as char
} else {
*self
}
}
/// 检查两个值是否为 ASCII 不区分大小写的匹配。
///
/// 相当于 <code>[to_ascii_lowercase]\(a) == [to_ascii_lowercase]\(b)</code>。
///
/// # Examples
///
/// ```
/// let upper_a = 'A';
/// let lower_a = 'a';
/// let lower_z = 'z';
///
/// assert!(upper_a.eq_ignore_ascii_case(&lower_a));
/// assert!(upper_a.eq_ignore_ascii_case(&upper_a));
/// assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
/// ```
///
/// [to_ascii_lowercase]: #method.to_ascii_lowercase
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
#[inline]
pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool {
self.to_ascii_lowercase() == other.to_ascii_lowercase()
}
/// 将此类型就地转换为其 ASCII 大写等效项。
///
/// ASCII 字母 'a' 到 'z' 映射到 'A' 到 'Z',但是非 ASCII 字母不变。
///
/// 要返回新的大写值而不修改现有值,请使用 [`to_ascii_uppercase()`]。
///
///
/// # Examples
///
/// ```
/// let mut ascii = 'a';
///
/// ascii.make_ascii_uppercase();
///
/// assert_eq!('A', ascii);
/// ```
///
/// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
///
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn make_ascii_uppercase(&mut self) {
*self = self.to_ascii_uppercase();
}
/// 将此类型就地转换为其 ASCII 小写等效项。
///
/// ASCII 字母 'A' 到 'Z' 映射到 'a' 到 'z',但是非 ASCII 字母不变。
///
/// 要返回新的小写值而不修改现有值,请使用 [`to_ascii_lowercase()`]。
///
///
/// # Examples
///
/// ```
/// let mut ascii = 'A';
///
/// ascii.make_ascii_lowercase();
///
/// assert_eq!('a', ascii);
/// ```
///
/// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
///
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn make_ascii_lowercase(&mut self) {
*self = self.to_ascii_lowercase();
}
/// 检查值是否为 ASCII 字母字符:
///
/// - U+0041 'A' ..= U+005A 'Z', or
/// - U+0061 'a' ..= U+007A 'z'.
///
/// # Examples
///
/// ```
/// let uppercase_a = 'A';
/// let uppercase_g = 'G';
/// let a = 'a';
/// let g = 'g';
/// let zero = '0';
/// let percent = '%';
/// let space = ' ';
/// let lf = '\n';
/// let esc = '\x1b';
///
/// assert!(uppercase_a.is_ascii_alphabetic());
/// assert!(uppercase_g.is_ascii_alphabetic());
/// assert!(a.is_ascii_alphabetic());
/// assert!(g.is_ascii_alphabetic());
/// assert!(!zero.is_ascii_alphabetic());
/// assert!(!percent.is_ascii_alphabetic());
/// assert!(!space.is_ascii_alphabetic());
/// assert!(!lf.is_ascii_alphabetic());
/// assert!(!esc.is_ascii_alphabetic());
/// ```
#[must_use]
#[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
#[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
#[inline]
pub const fn is_ascii_alphabetic(&self) -> bool {
matches!(*self, 'A'..='Z' | 'a'..='z')
}
/// 检查值是否为 ASCII 大写字符:
/// U+0041 'A' ..= U+005A 'Z'.
///
/// # Examples
///
/// ```
/// let uppercase_a = 'A';
/// let uppercase_g = 'G';
/// let a = 'a';
/// let g = 'g';
/// let zero = '0';
/// let percent = '%';
/// let space = ' ';
/// let lf = '\n';
/// let esc = '\x1b';
///
/// assert!(uppercase_a.is_ascii_uppercase());
/// assert!(uppercase_g.is_ascii_uppercase());
/// assert!(!a.is_ascii_uppercase());
/// assert!(!g.is_ascii_uppercase());
/// assert!(!zero.is_ascii_uppercase());
/// assert!(!percent.is_ascii_uppercase());
/// assert!(!space.is_ascii_uppercase());
/// assert!(!lf.is_ascii_uppercase());
/// assert!(!esc.is_ascii_uppercase());
/// ```
#[must_use]
#[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
#[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
#[inline]
pub const fn is_ascii_uppercase(&self) -> bool {
matches!(*self, 'A'..='Z')
}
/// 检查值是否为 ASCII 小写字符:
/// U+0061 'a' ..= U+007A 'z'.
///
/// # Examples
///
/// ```
/// let uppercase_a = 'A';
/// let uppercase_g = 'G';
/// let a = 'a';
/// let g = 'g';
/// let zero = '0';
/// let percent = '%';
/// let space = ' ';
/// let lf = '\n';
/// let esc = '\x1b';
///
/// assert!(!uppercase_a.is_ascii_lowercase());
/// assert!(!uppercase_g.is_ascii_lowercase());
/// assert!(a.is_ascii_lowercase());
/// assert!(g.is_ascii_lowercase());
/// assert!(!zero.is_ascii_lowercase());
/// assert!(!percent.is_ascii_lowercase());
/// assert!(!space.is_ascii_lowercase());
/// assert!(!lf.is_ascii_lowercase());
/// assert!(!esc.is_ascii_lowercase());
/// ```
#[must_use]
#[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
#[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
#[inline]
pub const fn is_ascii_lowercase(&self) -> bool {
matches!(*self, 'a'..='z')
}
/// 检查值是否为 ASCII 字母数字字符:
///
/// - U+0041 'A' ..= U+005A 'Z', or
/// - U+0061 'a' ..= U+007A 'z', or
/// - U+0030 '0' ..= U+0039 '9'.
///
/// # Examples
///
/// ```
/// let uppercase_a = 'A';
/// let uppercase_g = 'G';
/// let a = 'a';
/// let g = 'g';
/// let zero = '0';
/// let percent = '%';
/// let space = ' ';
/// let lf = '\n';
/// let esc = '\x1b';
///
/// assert!(uppercase_a.is_ascii_alphanumeric());
/// assert!(uppercase_g.is_ascii_alphanumeric());
/// assert!(a.is_ascii_alphanumeric());
/// assert!(g.is_ascii_alphanumeric());
/// assert!(zero.is_ascii_alphanumeric());
/// assert!(!percent.is_ascii_alphanumeric());
/// assert!(!space.is_ascii_alphanumeric());
/// assert!(!lf.is_ascii_alphanumeric());
/// assert!(!esc.is_ascii_alphanumeric());
/// ```
#[must_use]
#[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
#[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
#[inline]
pub const fn is_ascii_alphanumeric(&self) -> bool {
matches!(*self, '0'..='9' | 'A'..='Z' | 'a'..='z')
}
/// 检查值是否为 ASCII 十进制数字:
/// U+0030 '0' ..= U+0039 '9'.
///
/// # Examples
///
/// ```
/// let uppercase_a = 'A';
/// let uppercase_g = 'G';
/// let a = 'a';
/// let g = 'g';
/// let zero = '0';
/// let percent = '%';
/// let space = ' ';
/// let lf = '\n';
/// let esc = '\x1b';
///
/// assert!(!uppercase_a.is_ascii_digit());
/// assert!(!uppercase_g.is_ascii_digit());
/// assert!(!a.is_ascii_digit());
/// assert!(!g.is_ascii_digit());
/// assert!(zero.is_ascii_digit());
/// assert!(!percent.is_ascii_digit());
/// assert!(!space.is_ascii_digit());
/// assert!(!lf.is_ascii_digit());
/// assert!(!esc.is_ascii_digit());
/// ```
#[must_use]
#[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
#[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
#[inline]
pub const fn is_ascii_digit(&self) -> bool {
matches!(*self, '0'..='9')
}
/// 检查值是否为 ASCII 八进制数字:
/// U+0030 '0' ..= U+0037 '7'.
///
/// # Examples
///
/// ```
/// #![feature(is_ascii_octdigit)]
///
/// let uppercase_a = 'A';
/// let a = 'a';
/// let zero = '0';
/// let seven = '7';
/// let nine = '9';
/// let percent = '%';
/// let lf = '\n';
///
/// assert!(!uppercase_a.is_ascii_octdigit());
/// assert!(!a.is_ascii_octdigit());
/// assert!(zero.is_ascii_octdigit());
/// assert!(seven.is_ascii_octdigit());
/// assert!(!nine.is_ascii_octdigit());
/// assert!(!percent.is_ascii_octdigit());
/// assert!(!lf.is_ascii_octdigit());
/// ```
#[must_use]
#[unstable(feature = "is_ascii_octdigit", issue = "101288")]
#[rustc_const_unstable(feature = "is_ascii_octdigit", issue = "101288")]
#[inline]
pub const fn is_ascii_octdigit(&self) -> bool {
matches!(*self, '0'..='7')
}
/// 检查值是否为 ASCII 十六进制数字:
///
/// - U+0030 '0' ..= U+0039 '9', or
/// - U+0041 'A' ..= U+0046 'F', or
/// - U+0061 'a' ..= U+0066 'f'.
///
/// # Examples
///
/// ```
/// let uppercase_a = 'A';
/// let uppercase_g = 'G';
/// let a = 'a';
/// let g = 'g';
/// let zero = '0';
/// let percent = '%';
/// let space = ' ';
/// let lf = '\n';
/// let esc = '\x1b';
///
/// assert!(uppercase_a.is_ascii_hexdigit());
/// assert!(!uppercase_g.is_ascii_hexdigit());
/// assert!(a.is_ascii_hexdigit());
/// assert!(!g.is_ascii_hexdigit());
/// assert!(zero.is_ascii_hexdigit());
/// assert!(!percent.is_ascii_hexdigit());
/// assert!(!space.is_ascii_hexdigit());
/// assert!(!lf.is_ascii_hexdigit());
/// assert!(!esc.is_ascii_hexdigit());
/// ```
#[must_use]
#[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
#[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
#[inline]
pub const fn is_ascii_hexdigit(&self) -> bool {
matches!(*self, '0'..='9' | 'A'..='F' | 'a'..='f')
}
/// 检查值是否为 ASCII 标点符号:
///
/// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
/// - U+003A ..= U+0040 `: ; < = > ? @`, or
/// - U+005B ..= U+0060 ``[ \ ] ^ _ ` ``, or
/// - U+007B ..= U+007E `{ | } ~`
///
/// # Examples
///
/// ```
/// let uppercase_a = 'A';
/// let uppercase_g = 'G';
/// let a = 'a';
/// let g = 'g';
/// let zero = '0';
/// let percent = '%';
/// let space = ' ';
/// let lf = '\n';
/// let esc = '\x1b';
///
/// assert!(!uppercase_a.is_ascii_punctuation());
/// assert!(!uppercase_g.is_ascii_punctuation());
/// assert!(!a.is_ascii_punctuation());
/// assert!(!g.is_ascii_punctuation());
/// assert!(!zero.is_ascii_punctuation());
/// assert!(percent.is_ascii_punctuation());
/// assert!(!space.is_ascii_punctuation());
/// assert!(!lf.is_ascii_punctuation());
/// assert!(!esc.is_ascii_punctuation());
/// ```
#[must_use]
#[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
#[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
#[inline]
pub const fn is_ascii_punctuation(&self) -> bool {
matches!(*self, '!'..='/' | ':'..='@' | '['..='`' | '{'..='~')
}
/// 检查值是否为 ASCII 图形字符:
/// U+0021 '!' ..= U+007E '~'.
///
/// # Examples
///
/// ```
/// let uppercase_a = 'A';
/// let uppercase_g = 'G';
/// let a = 'a';
/// let g = 'g';
/// let zero = '0';
/// let percent = '%';
/// let space = ' ';
/// let lf = '\n';
/// let esc = '\x1b';
///
/// assert!(uppercase_a.is_ascii_graphic());
/// assert!(uppercase_g.is_ascii_graphic());
/// assert!(a.is_ascii_graphic());
/// assert!(g.is_ascii_graphic());
/// assert!(zero.is_ascii_graphic());
/// assert!(percent.is_ascii_graphic());
/// assert!(!space.is_ascii_graphic());
/// assert!(!lf.is_ascii_graphic());
/// assert!(!esc.is_ascii_graphic());
/// ```
#[must_use]
#[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
#[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
#[inline]
pub const fn is_ascii_graphic(&self) -> bool {
matches!(*self, '!'..='~')
}
/// 检查值是否为 ASCII 空格字符:
/// U+0020 空格、U+0009 水平制表符、U+000A 换行、U+000C 换页或 U+000D 回车。
///
/// Rust 使用 WhatWG 基础标准的 [ASCII 空格的定义][infra-aw]。还有其他几种广泛使用的定义。
/// 例如,[POSIX 语言环境][pct] 包括 U+000B 垂直标签以及所有上述字符,但是 - 从相同的规格来看 -[Bourne shell 中 "field splitting" 的默认规则][bfs] 仅考虑空格,水平标签和 LINE FEED 作为空白。
///
///
/// 如果要编写将处理现有文件格式的程序,请在使用此函数之前检查该格式的空格定义。
///
/// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
/// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
/// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
///
/// # Examples
///
/// ```
/// let uppercase_a = 'A';
/// let uppercase_g = 'G';
/// let a = 'a';
/// let g = 'g';
/// let zero = '0';
/// let percent = '%';
/// let space = ' ';
/// let lf = '\n';
/// let esc = '\x1b';
///
/// assert!(!uppercase_a.is_ascii_whitespace());
/// assert!(!uppercase_g.is_ascii_whitespace());
/// assert!(!a.is_ascii_whitespace());
/// assert!(!g.is_ascii_whitespace());
/// assert!(!zero.is_ascii_whitespace());
/// assert!(!percent.is_ascii_whitespace());
/// assert!(space.is_ascii_whitespace());
/// assert!(lf.is_ascii_whitespace());
/// assert!(!esc.is_ascii_whitespace());
/// ```
///
///
///
///
///
///
///
#[must_use]
#[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
#[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
#[inline]
pub const fn is_ascii_whitespace(&self) -> bool {
matches!(*self, '\t' | '\n' | '\x0C' | '\r' | ' ')
}
/// 检查值是否为 ASCII 控制字符:
/// U+0000 NUL ..= U+001F 单元分隔符,或 U+007F 删除。
/// 请注意,大多数 ASCII 空格字符是控制字符,而 SPACE 不是。
///
///
/// # Examples
///
/// ```
/// let uppercase_a = 'A';
/// let uppercase_g = 'G';
/// let a = 'a';
/// let g = 'g';
/// let zero = '0';
/// let percent = '%';
/// let space = ' ';
/// let lf = '\n';
/// let esc = '\x1b';
///
/// assert!(!uppercase_a.is_ascii_control());
/// assert!(!uppercase_g.is_ascii_control());
/// assert!(!a.is_ascii_control());
/// assert!(!g.is_ascii_control());
/// assert!(!zero.is_ascii_control());
/// assert!(!percent.is_ascii_control());
/// assert!(!space.is_ascii_control());
/// assert!(lf.is_ascii_control());
/// assert!(esc.is_ascii_control());
/// ```
#[must_use]
#[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
#[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
#[inline]
pub const fn is_ascii_control(&self) -> bool {
matches!(*self, '\0'..='\x1F' | '\x7F')
}
}
pub(crate) struct EscapeDebugExtArgs {
/// 转义扩展字素代码点?
pub(crate) escape_grapheme_extended: bool,
/// 转义单引号?
pub(crate) escape_single_quote: bool,
/// 转义双引号?
pub(crate) escape_double_quote: bool,
}
impl EscapeDebugExtArgs {
pub(crate) const ESCAPE_ALL: Self = Self {
escape_grapheme_extended: true,
escape_single_quote: true,
escape_double_quote: true,
};
}
#[inline]
const fn len_utf8(code: u32) -> usize {
if code < MAX_ONE_B {
1
} else if code < MAX_TWO_B {
2
} else if code < MAX_THREE_B {
3
} else {
4
}
}
/// 将原始 u32 值编码为 UTF-8 到提供的字节缓冲区中,然后返回包含编码字符的缓冲区的子切片。
///
///
/// 与 `char::encode_utf8` 不同,此方法还处理代理范围内的代码点。
/// (在代理范围内创建 `char` 是 UB。) 结果是有效的 [广义的 UTF-8],但无效的 UTF-8。
///
/// [generalized UTF-8]: https://simonsapin.github.io/wtf-8/#generalized-utf8
///
/// # Panics
///
/// 如果缓冲区不够大,就会出现 panics。
/// 长度为四的缓冲区足够大,可以对任何 `char` 进行编码。
///
#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
#[doc(hidden)]
#[inline]
pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
let len = len_utf8(code);
match (len, &mut dst[..]) {
(1, [a, ..]) => {
*a = code as u8;
}
(2, [a, b, ..]) => {
*a = (code >> 6 & 0x1F) as u8 | TAG_TWO_B;
*b = (code & 0x3F) as u8 | TAG_CONT;
}
(3, [a, b, c, ..]) => {
*a = (code >> 12 & 0x0F) as u8 | TAG_THREE_B;
*b = (code >> 6 & 0x3F) as u8 | TAG_CONT;
*c = (code & 0x3F) as u8 | TAG_CONT;
}
(4, [a, b, c, d, ..]) => {
*a = (code >> 18 & 0x07) as u8 | TAG_FOUR_B;
*b = (code >> 12 & 0x3F) as u8 | TAG_CONT;
*c = (code >> 6 & 0x3F) as u8 | TAG_CONT;
*d = (code & 0x3F) as u8 | TAG_CONT;
}
_ => panic!(
"encode_utf8: need {} bytes to encode U+{:X}, but the buffer has {}",
len,
code,
dst.len(),
),
};
&mut dst[..len]
}
/// 将原始 u32 值编码为 UTF-16 到提供的 `u16` 缓冲区中,然后返回包含编码字符的缓冲区的子切片。
///
///
/// 与 `char::encode_utf16` 不同,此方法还处理代理范围内的代码点。
/// (在代理范围内创建 `char` 是 UB。)
///
/// # Panics
///
/// 如果缓冲区不够大,就会出现 panics。
/// 长度为 2 的缓冲区足够大,可以对任何 `char` 进行编码。
#[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")]
#[doc(hidden)]
#[inline]
pub fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
// SAFETY: 每个 arm 检查是否有足够的位可写入
unsafe {
if (code & 0xFFFF) == code && !dst.is_empty() {
// BMP 失败了
*dst.get_unchecked_mut(0) = code as u16;
slice::from_raw_parts_mut(dst.as_mut_ptr(), 1)
} else if dst.len() >= 2 {
// 辅助展开分解为代理。
code -= 0x1_0000;
*dst.get_unchecked_mut(0) = 0xD800 | ((code >> 10) as u16);
*dst.get_unchecked_mut(1) = 0xDC00 | ((code as u16) & 0x3FF);
slice::from_raw_parts_mut(dst.as_mut_ptr(), 2)
} else {
panic!(
"encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
char::from_u32_unchecked(code).len_utf16(),
code,
dst.len(),
)
}
}
}