readable/str/str.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
//---------------------------------------------------------------------------------------------------- Use
// use bincode::{Encode,Decode};
// use serde::{Serialize,serde::Deserialize};
// use anyhow::anyhow;
// use log::{error,info,warn,debug,trace};
// use disk::{Bincode2,Json};
use std::sync::Arc;
use std::rc::Rc;
use std::borrow::Cow;
//---------------------------------------------------------------------------------------------------- Str
/// A fixed sized stack string
///
/// [`Str`] is a generic stack-based string with a maximum byte length of [`u8::MAX`].
///
/// The generic `N` is a [`usize`] and represents the maximum length of the string,
/// however all constructor functions for [`Str`] will panic at _compile time_ if `N > 255`.
///
/// ## Size
/// The internal length is stored as a [`u8`], and as such will
/// take minimal space, allowing for longer strings to be stored.
///
/// Due to `#[repr(C)]`, `N + 1` is how many bytes your [`Str`] will take up.
///
/// Using [`Str`] in powers of 2 is recommended.
/// ```rust
/// # use readable::str::*;
/// // 64 bytes in total, 63 bytes available for the string.
/// // This will fit in a typical CPU cache-line.
/// assert_eq!(std::mem::size_of::<Str::<63>>(), 64);
///
/// // Maximum string length of 255 fits into 256 bytes.
/// assert_eq!(std::mem::size_of::<Str::<255>>(), 256);
///
/// // Beware, due to `#[repr(C)]`, `Str` is not
/// // automatically re-arranged and padded by Rust.
/// assert_eq!(std::mem::size_of::<Str::<6>>(), 7);
/// ```
///
/// ## Compile-time panic
/// Any usage of [`Str`] will panic at compile time if `N > 255`:
/// ```rust,ignore
/// # use readable::str::*;
/// /// These will all panic at _compile time_
/// Str::<256>::new();
/// Str::<256>::try_from("");
/// Str::<256>::from_static_str("");
/// Str::<256>::from_static_bytes(b"");
/// ```
///
/// ## Usage
/// ```rust
/// # use readable::str::*;
/// // Create a `Str` with a maximum capacity of `24` bytes.
/// const N: usize = 24;
/// let mut string = Str::<N>::new();
/// assert!(string.is_empty());
///
/// // Copy the bytes from an actual `str`
/// let other_str = "this str is 24 bytes :-)";
/// assert_eq!(other_str.len(), N);
/// string.copy_str(other_str).unwrap();
///
/// // They're the same.
/// assert_eq!(string, other_str);
///
/// // Clear the string.
/// string.clear();
/// assert!(string.is_empty());
/// assert_eq!(string.len(), 0);
///
/// // `push_str()` should be the exact same.
/// string.push_str(other_str).unwrap();
/// assert_eq!(string, other_str);
///
/// // This string is full.
/// assert!(string.is_full());
/// assert_eq!(string.len(), N);
///
/// // Pushing new strings will error.
/// let err = string.push_str(other_str);
/// assert_eq!(err, Err(24));
/// // Still the same.
/// assert_eq!(string, other_str);
///
/// // Although, we can still overwrite it.
/// string.copy_str("hello-------------------");
/// assert_eq!(string, "hello-------------------");
/// assert_eq!(string.len(), 24);
/// ```
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[repr(C)]
pub struct Str<const N: usize> {
buf: [u8; N],
len: u8,
}
//---------------------------------------------------------------------------------------------------- Impl
impl<const N: usize> Str<N> {
/// The maximum length of this string as a [`u8`].
///
/// This should `==` to `N` in valid cases.
///
/// ## Compile-time panic
/// This associated constant will cause [`Str`] constructor
/// functions to panic at compile time is `N > 255`.
pub const CAPACITY: u8 = {
if N > u8::MAX as usize {
panic!("N must not be greater than 255");
} else {
N as u8
}
};
#[inline]
#[must_use]
/// Returns an empty [`Str`].
///
/// ```rust
/// # use readable::str::*;
/// let string = Str::<4>::new();
/// assert!(string.is_empty());
/// assert_eq!(string.len(), 0);
/// assert!(string.as_str().is_empty());
/// assert_eq!(string.as_str().len(), 0);
/// ```
pub const fn new() -> Self {
// Will cause panics at compile time.
Self::CAPACITY;
Self {
buf: [0; N],
len: 0,
}
}
#[must_use]
#[allow(clippy::missing_panics_doc)] // compile-time
/// Create a [`Self`] from static bytes.
///
/// The length of the input doesn't need to be the
/// same as `N`, it just needs to be equal or less.
///
/// Exact length:
/// ```rust
/// # use readable::str::*;
/// const BYTES: [u8; 3] = *b"abc";
/// const STR: Str<3> = Str::from_static_bytes(&BYTES);
///
/// assert_eq!(STR, "abc");
/// ```
/// Slightly less length is okay too:
/// ```rust
/// # use readable::str::*;
/// const BYTES: [u8; 2] = *b"ab";
/// const STR: Str<3> = Str::from_static_bytes(&BYTES);
///
/// assert_eq!(STR.len(), 2);
/// assert_eq!(STR, "ab");
/// ```
///
/// # Compile-time panic
/// This function will panic at compile time if either:
/// - The `byte` length is longer than `N`
/// - The byte's are not valid UTF-8 bytes
///
/// ```rust,ignore
/// # use readable::str::*;
/// // This doesn't fit, will panic at compile time.
/// const STR: Str<3> = Str::from_static_bytes("abcd");
/// ```
pub const fn from_static_bytes(bytes: &'static [u8]) -> Self {
// Will cause panics at compile time.
Self::CAPACITY;
let len = bytes.len();
assert!(len <= N, "byte length is longer than N");
assert!(std::str::from_utf8(bytes).is_ok(), "bytes are not valid UTF-8");
let mut buf = [0_u8; N];
let mut i = 0;
while i < len {
buf[i] = bytes[i];
i += 1;
}
Self {
buf,
len: len as u8,
}
}
#[must_use]
/// Create a [`Self`] from a static [`str`].
///
/// The length of the input doesn't need to be the
/// same as `N`, it just needs to be equal or less.
///
/// Exact length:
/// ```rust
/// # use readable::str::*;
/// const S: &str = "abc";
/// const STR: Str<3> = Str::from_static_str(&S);
///
/// assert_eq!(STR, "abc");
/// ```
/// Slightly less length is okay too:
/// ```rust
/// # use readable::str::*;
/// const S: &str = "ab";
/// const STR: Str<3> = Str::from_static_str(&S);
///
/// assert_eq!(STR.len(), 2);
/// assert_eq!(STR, "ab");
/// ```
///
/// ## Compile-time panic
/// This function will panic at compile time
/// if the [`str`] length is longer than `N`.
///
/// ```rust,ignore
/// # use readable::str::*;
/// // This doesn't fit, will panic at compile time.
/// const STR: Str<3> = Str::from_static_str("abcd");
/// ```
pub const fn from_static_str(s: &'static str) -> Self {
Self::from_static_bytes(s.as_bytes())
}
#[inline]
#[must_use]
/// Return all the bytes of this [`Str`], whether valid UTF-8 or not.
///
/// ``` rust
/// # use readable::str::*;
/// let mut string = Str::<10>::new();
/// string.push_str("hello").unwrap();
///
/// // The string length is 5, but the slice
/// // returned is the full capacity, 10.
/// assert_eq!(string.as_bytes_all().len(), 10);
/// ```
pub const fn as_bytes_all(&self) -> &[u8] {
self.buf.as_slice()
}
#[inline]
#[must_use]
/// Return all the bytes of this [`Str`] (mutably), whether valid UTF-8 or not
///
/// ## Safety
/// The caller must ensure that the content of the slice is valid
/// UTF-8 before the borrow ends and the underlying [`Str`] is used.
///
/// The caller must also ensure the `len` is correctly set
/// with [`Str::set_len`] or [`Str::set_len_u8`].
///
/// ``` rust
/// # use readable::str::*;
/// let mut string = Str::<5>::new();
/// string.push_str("hi").unwrap();
/// assert_eq!(string, "hi");
/// assert_eq!(string.len(), 2);
///
/// // Safety: We must ensure we leave
/// // leave the bytes as valid UTF-8 bytes
/// // and that we set the length correctly.
/// unsafe {
/// // Mutate to valid UTF-8 bytes.
/// let mut_ref = string.as_bytes_all_mut();
/// mut_ref.copy_from_slice(&b"world"[..]);
/// // Set the new length.
/// string.set_len(5);
/// }
///
/// assert_eq!(string, "world");
/// assert_eq!(string.len(), 5);
/// ```
pub unsafe fn as_bytes_all_mut(&mut self) -> &mut [u8] {
self.buf.as_mut_slice()
}
#[inline]
#[must_use]
/// Return the length of the _valid_ UTF-8 bytes of this [`Str`]
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<5>::new();
/// s.push_str("h").unwrap();
/// assert_eq!(s.len(), 1_usize);
///
/// s.push_str("ello").unwrap();
/// assert_eq!(s.len(), 5_usize);
/// ```
pub const fn len(&self) -> usize {
self.len as usize
}
#[inline]
#[must_use]
/// Return the length of the _valid_ UTF-8 bytes of this [`Str`] as a [`u8`]
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<5>::new();
/// s.push_str("h").unwrap();
/// assert_eq!(s.len_u8(), 1_u8);
///
/// s.push_str("ello").unwrap();
/// assert_eq!(s.len_u8(), 5_u8);
/// ```
pub const fn len_u8(&self) -> u8 {
self.len
}
#[inline]
/// Set the length of the _valid_ UTF-8 bytes of this [`Str`]
///
/// This will usually be used when manually mutating [`Str`] with [`Str::as_bytes_all_mut()`].
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<3>::new();
/// assert_eq!(s.len(), 0);
///
/// unsafe { s.set_len(3); } // <- Using the `Str`
/// assert_eq!(s.len(), 3); // beyond this point
/// // is a bad idea.
///
/// // This wouldn't be undefined behavior,
/// // but the inner buffer is all zeros.
/// assert_eq!(s.as_str(), "\0\0\0");
///
/// // Overwrite the bytes.
/// unsafe {
/// let mut_ref = s.as_bytes_all_mut();
/// mut_ref[0] = b'a';
/// mut_ref[1] = b'b';
/// mut_ref[2] = b'c';
/// }
/// // Should be safe from this point.
/// assert_eq!(s.as_str(), "abc");
/// assert_eq!(s.len(), 3);
/// ```
///
/// ## Safety
/// Other functions will rely on the internal length
/// to be correct, so the caller must ensure this length
/// is actually correct.
pub unsafe fn set_len(&mut self, len: usize) {
self.len = len as u8;
}
#[inline]
/// Set the length of the _valid_ UTF-8 bytes of this [`Str`]
///
/// This will usually be used when manually mutating [`Str`] with [`Str::as_bytes_all_mut()`].
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<3>::new();
/// assert_eq!(s.len(), 0);
///
/// unsafe { s.set_len_u8(3); } // <- Using the `Str`
/// assert_eq!(s.len(), 3); // beyond this point
/// // is a bad idea.
///
/// // This wouldn't be undefined behavior,
/// // but the inner buffer is all zeros.
/// assert_eq!(s.as_str(), "\0\0\0");
///
/// // Overwrite the bytes.
/// unsafe {
/// let mut_ref = s.as_bytes_all_mut();
/// mut_ref[0] = b'a';
/// mut_ref[1] = b'b';
/// mut_ref[2] = b'c';
/// }
/// // Should be safe from this point.
/// assert_eq!(s.as_str(), "abc");
/// assert_eq!(s.len(), 3);
/// ```
///
/// ## Safety
/// Other functions will rely on the internal length
/// to be correct, so the caller must ensure this length
/// is actually correct.
pub unsafe fn set_len_u8(&mut self, len: u8) {
self.len = len;
}
#[inline]
#[must_use]
/// How many available bytes are left in this [`Str`]
/// before the [`Self::CAPACITY`] is completely filled.
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<5>::new();
/// s.push_str("hi");
/// assert_eq!(s.remaining(), 3);
/// ```
pub const fn remaining(&self) -> usize {
(Self::CAPACITY - self.len) as usize
}
#[inline]
#[must_use]
/// Returns only the valid `UTF-8` bytes of this [`Str`] as a byte slice.
///
/// ```rust
/// # use readable::str::*;
/// let s = Str::<10>::from_static_str("hello");
/// assert_eq!(s.as_bytes().len(), 5);
/// ```
pub const fn as_bytes(&self) -> &[u8] {
// SAFETY: we trust `.len()`.
unsafe {
std::slice::from_raw_parts(
self.as_ptr(),
self.len(),
)
}
}
#[inline]
#[must_use]
/// [`Self::as_bytes()`], but returns mutable bytes
///
/// ## Safety
/// The length must be set correctly if mutated.
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<10>::from_static_str("hello");
/// assert_eq!(s.as_bytes().len(), 5);
///
/// unsafe {
///
/// // Length not set yet.
/// s.as_bytes_mut().copy_from_slice(&[0; 5]);
/// assert_eq!(s.as_bytes_mut().len(), 5);
///
/// // Set.
/// s.set_len(0);
/// }
///
/// assert_eq!(s.as_str(), "");
/// assert_eq!(s.as_bytes().len(), 0);
/// ```
pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
// SAFETY: we trust `.len()`.
unsafe {
std::slice::from_raw_parts_mut(
self.as_mut_ptr(),
self.len(),
)
}
}
#[inline]
#[must_use]
/// Returns a pointer to the first byte in the string array.
/// ```rust
/// # use readable::str::*;
/// let s = Str::<5>::from_static_str("hello");
///
/// let ptr = s.as_ptr();
/// unsafe {
/// // The first byte is the char `h`.
/// assert_eq!(*ptr, b'h');
/// }
/// ```
pub const fn as_ptr(&self) -> *const u8 {
self.buf.as_ptr()
}
#[inline]
/// Returns a mutable pointer to the first byte in the string array.
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<5>::from_static_str("hello");
///
/// let ptr = s.as_mut_ptr();
/// unsafe {
/// // The first byte is the char `h`.
/// assert_eq!(*ptr, b'h');
/// // Let's change it.
/// *ptr = b'e';
/// }
///
/// assert_eq!(s, "eello");
/// ```
pub fn as_mut_ptr(&mut self) -> *mut u8 {
self.buf.as_mut_ptr()
}
#[inline]
#[must_use]
/// Returns only the valid `UTF-8` bytes of this [`Str`] as a `Vec<u8>`
///
/// ```rust
/// # use readable::str::*;
/// let s = Str::<10>::from_static_str("hello");
/// let v = s.into_vec();
/// assert_eq!(v.len(), 5);
///
/// let s = unsafe { String::from_utf8_unchecked(v) };
/// assert_eq!(s, "hello");
/// ```
pub fn into_vec(self) -> Vec<u8> {
self.as_bytes().to_vec()
}
#[must_use]
/// Check this [`Str`] for correctness.
///
/// When constructing/receiving a [`Str`] outside of
/// its constructors, it may not be guaranteed that
/// the invariants are upheld.
///
/// This function will return `true` if:
/// - Internal length is greater than the internal byte array
/// - `.as_str()` would return invalid UTF-8
///
/// ```rust
/// # use readable::str::*;
/// // Create `Str` with maximum 5 length.
/// let mut string = Str::<5>::new();
/// assert_eq!(string.invalid(), false);
///
/// // Unsafely set the length to 10.
/// unsafe { string.set_len(10); }
/// // This string is now invalid.
/// assert_eq!(string.invalid(), true);
/// ```
pub const fn invalid(&self) -> bool {
let len = self.len as usize;
let buf_len = self.buf.len();
len > buf_len || std::str::from_utf8(self.as_bytes()).is_err()
}
#[inline]
/// Clears all bytes of this [`Str`].
///
/// ```rust
/// # use readable::str::*;
/// // Create a string.
/// let mut s = Str::<5>::from_static_str("hello");
/// assert_eq!(s, "hello");
///
/// // Clear the string.
/// s.clear();
/// assert_eq!(s, "");
/// assert!(s.is_empty());
/// ```
///
/// ## Note
/// This does not actually mutate any bytes,
/// it simply sets the internal length to `0`.
///
/// Do not rely on this to clear the actual bytes.
pub fn clear(&mut self) {
// SAFETY: We are manually setting the length.
unsafe { self.set_len(0); }
}
/// Zeros all bytes of this [`Str`] and sets the length to `0`
///
/// Unlike [`Str::clear()`], this actually sets all
/// the bytes in the internal array to `0`.
///
/// ```rust
/// # use readable::str::*;
/// // Create a string.
/// let mut s = Str::<5>::from_static_str("hello");
/// assert_eq!(s, "hello");
///
/// // Zero the string.
/// s.zero();
/// assert_eq!(s, "");
/// assert!(s.is_empty());
/// ```
pub fn zero(&mut self) {
// should be a fast 0 memset.
// https://github.com/rust-lang/rfcs/issues/2067
self.buf.fill(0);
// SAFETY: We are manually setting the length.
unsafe { self.set_len(0); }
}
#[inline]
#[must_use]
/// If this [`Str`] is empty.
///
/// ``` rust
/// # use readable::str::*;
/// let mut s = Str::<10>::new();
/// assert_eq!(s, "");
/// assert!(s.is_empty());
///
/// s.push_str("a").unwrap();
/// assert!(!s.is_empty());
/// ```
pub const fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
#[must_use]
/// If this [`Str`] is full (no more capacity left).
///
/// ``` rust
/// # use readable::str::*;
/// let mut s = Str::<3>::new();
/// assert_eq!(s.len(), 0);
/// assert!(!s.is_full());
///
/// s.push_str("123").unwrap();
/// assert_eq!(s.len(), 3);
/// assert!(s.is_full());
/// ```
pub const fn is_full(&self) -> bool {
self.len == Self::CAPACITY
}
#[inline]
#[must_use]
/// This [`Str`], as a valid UTF-8 [`str`].
///
/// ``` rust
/// # use readable::str::*;
/// let s = Str::<5>::from_static_str("hello");
/// assert_eq!(s.as_str(), "hello");
/// ```
///
/// # Panics
/// This will panic in debug mode if [`Self::invalid`] returns true.
pub const fn as_str(&self) -> &str {
debug_assert!(
!self.invalid(),
"Str::invalid() returned true, inner str is corrupt"
);
// SAFETY: `.as_valid_slice()` must be correctly implemented.
// The internal state must be correct.
unsafe { std::str::from_utf8_unchecked(self.as_bytes()) }
}
#[inline]
/// This [`Str`], as a valid, mutable, UTF-8 [`str`].
///
/// ## Safety
/// The length must be set correctly if mutated.
///
/// The `str` must be valid UTF-8.
///
/// ``` rust
/// # use readable::str::*;
/// let mut s = Str::<5>::from_static_str("hello");
/// assert_eq!(s.as_str(), "hello");
///
/// unsafe {
/// s.as_str_mut().make_ascii_uppercase();
/// }
///
/// assert_eq!(s.as_str(), "HELLO");
/// ```
pub unsafe fn as_str_mut(&mut self) -> &mut str {
// SAFETY: `.as_valid_slice()` must be correctly implemented.
// The internal state must be correct.
unsafe { std::str::from_utf8_unchecked_mut(self.as_bytes_mut()) }
}
#[inline]
#[must_use]
/// Consumes `self` into a [`String`]
///
/// ``` rust
/// # use readable::str::*;
/// let s = Str::<5>::from_static_str("hello");
///
/// let s: String = s.into_string();
/// assert_eq!(s, "hello");
/// ```
pub fn into_string(self) -> String {
// SAFETY: The internal state must be correct.
unsafe { String::from_utf8_unchecked(self.into_vec()) }
}
#[inline]
/// Overwrites `self` with the [`str`] `s`.
///
/// The input `s` must be the exact same length
/// as `N` or this function will error.
///
/// # Errors
/// If the copy was successful, [`Result::Ok`] is returned with the new length of the string.
///
/// If the copy failed because `s.len() > N`, [`Result::Err`] is returned with how many extra bytes couldn't fit.
///
/// If the copy failed because `s.len() != N`, [`Result::Err`] is returned as `Err(0)`.
///
/// ```rust
/// # use readable::str::*;
/// let mut string = Str::<3>::new();
///
/// // Input string is 4 in length, we can't copy it.
/// // There is 1 extra byte that can't fit.
/// assert_eq!(string.copy_str("abcd"), Err(1));
///
/// // Input string is 2 in length, not exactly 3.
/// // `Err(0)` will be returned to indicate this.
/// assert_eq!(string.copy_str("ab"), Err(0));
///
/// // This fits.
/// assert_eq!(string.copy_str("abc"), Ok(3));
/// ```
pub fn copy_str(&mut self, s: impl AsRef<str>) -> Result<usize, usize> {
let s = s.as_ref();
let s_bytes = s.as_bytes();
let s_len = s.len();
if s_len > N {
return Err(s_len - N);
}
if s_len != N {
return Err(0);
}
// SAFETY: We are directly mutating the bytes and length.
// We know the correct values.
unsafe {
self.as_bytes_all_mut().copy_from_slice(s_bytes);
self.set_len(s_len);
}
Ok(s_len)
}
#[inline]
/// Performs the same operation as [`Self::copy_str()`] except
/// this function does not check if the input [`str`] `s` is too long.
///
/// If the copy was successful, the new length of the string is returned.
///
/// If the copy failed, this function will panic.
///
/// ```rust
/// # use readable::str::*;
/// let mut string = Str::<3>::new();
///
/// // Input string is 3 in length, we can copy it.
/// assert_eq!(string.copy_str_unchecked("abc"), 3);
/// ```
///
/// # Panics
/// Instead of erroring, this function will panic if the input `s.len() != N`.
///
/// Input too long:
/// ```rust,should_panic
/// # use readable::str::*;
/// let mut string = Str::<3>::new();
///
/// // Input string is 5 in length, this will panic.
/// string.copy_str_unchecked("abcd");
/// ```
/// Input not long enough:
/// ```rust,should_panic
/// # use readable::str::*;
/// let mut string = Str::<3>::new();
///
/// // Input string is 2 in length, this will panic.
/// string.copy_str_unchecked("ab");
/// ```
/// Input is just right:
/// ```rust
/// # use readable::str::*;
/// let mut string = Str::<3>::new();
/// string.copy_str_unchecked("abc");
/// assert_eq!(string, "abc")
/// ```
pub fn copy_str_unchecked(&mut self, s: impl AsRef<str>) -> usize {
let s = s.as_ref();
let s_bytes = s.as_bytes();
let s_len = s.len();
// SAFETY: We are directly mutating the bytes and length.
// We know the correct values.
unsafe {
self.as_bytes_all_mut().copy_from_slice(s_bytes);
self.set_len(s_len);
}
s_len
}
#[inline]
/// Appends `self` with the [`str`] `s`.
///
/// # Errors
/// If the push was successful (or `s` was empty),
/// [`Result::Ok`] is returned with the new length of the string.
///
/// If the push failed, [`Result::Err`] is returned
/// with how many extra bytes couldn't fit.
///
/// ```rust
/// # use readable::str::*;
/// let mut string = Str::<3>::new();
///
/// // Input string is 4 in length.
/// // We can't push it.
/// let err = string.push_str("abcd");
/// assert_eq!(err, Err(1));
///
/// // The string is still empty.
/// assert!(string.is_empty());
///
/// // This 2 length string will fit.
/// string.push_str("ab").unwrap();
/// assert_eq!(string, "ab");
/// // This 1 length string will fit.
/// string.push_str("c").unwrap();
/// assert_eq!(string, "abc");
///
/// // But not anymore.
/// let err = string.push_str("d");
/// assert_eq!(err, Err(1));
/// assert_eq!(string, "abc");
/// ```
pub fn push_str(&mut self, s: impl AsRef<str>) -> Result<usize, usize> {
let s = s.as_ref();
let s_bytes = s.as_bytes();
let s_len = s.len();
if s_len == 0 {
return Ok(self.len());
}
let remaining = self.remaining();
if s_len > remaining {
return Err(s_len - remaining);
}
let self_len = self.len();
let new_len = s_len + self.len();
// SAFETY: We are directly mutating the bytes and length.
// We know the correct values.
unsafe {
self.as_bytes_all_mut()[self_len..new_len].copy_from_slice(s_bytes);
self.set_len(new_len);
}
Ok(new_len)
}
/// Appends `self` with the [`str`] `s`.
///
/// If the push was successful (or `s` was empty),
/// a `usize` is returned, representing the new length of the string.
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<5>::new();
/// assert_eq!(s.push_str_panic("wow"), 3);
/// ```
///
/// ## Panics
/// If the push failed, this function panics.
///
/// Input string is `>` than capacity:
/// ```rust,should_panic
/// # use readable::str::*;
/// let mut s = Str::<3>::new();
/// s.push_str_panic("abcd");
/// ```
///
/// [`Str`] has no more remaining capacity:
/// ```rust,should_panic
/// # use readable::str::*;
/// let mut s = Str::<4>::from_static_str("wow");
/// assert_eq!(s.len(), 3);
/// assert_eq!(s.remaining(), 1);
///
/// // This won't fit, will panic.
/// s.push_str_panic("wow");
/// ```
pub fn push_str_panic(&mut self, s: impl AsRef<str>) -> usize {
let s = s.as_ref();
let s_bytes = s.as_bytes();
let s_len = s.len();
if s_len == 0 {
return self.len as usize;
}
let remaining = self.remaining();
assert!(
s_len <= remaining,
"no more space - remaining: {remaining}, input length: {s_len}, capacity: {N}"
);
let self_len = self.len();
let new_len = s_len + self.len();
// SAFETY: We are directly mutating the bytes and length.
// We know the correct values.
unsafe {
self.as_bytes_all_mut()[self_len..new_len].copy_from_slice(s_bytes);
self.set_len(new_len);
}
new_len
}
#[inline]
/// Appends `self` with the [`str`] `s`, saturating if there is no [`Self::CAPACITY`] left
///
/// This function returns a `usize`, representing how many _bytes_ were written.
///
/// If there is no _byte_ capacity left, this function will return `0`.
///
/// UTF-8 strings are accounted for, and are split on `char` basis, for example:
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<7>::new();
///
/// // Crab is 4 bytes.
/// assert_eq!(4, "π¦".len());
///
/// // Our capacity is only 7, so we can only fit 1.
/// assert_eq!(4, s.push_str_saturating("π¦"));
/// assert_eq!(s, "π¦");
/// assert_eq!(4, s.len());
/// assert_eq!(3, s.remaining());
/// ```
///
/// ## Examples
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<3>::new();
///
/// // Only 1 char, 3 bytes can fit.
/// assert_eq!(3, s.push_str_saturating("γ§γ"));
/// assert_eq!(s, "γ§");
/// s.clear();
///
/// // Only 3 ASCII characters can fit.
/// assert_eq!(3, s.push_str_saturating("hello"));
/// assert_eq!(s, "hel");
/// s.clear();
///
/// // Here, we push 3 characters with 1 capacity left.
/// s.push_str("wo").unwrap();
/// assert_eq!(1, s.push_str_saturating("rld"));
/// // And only 1 character was pushed.
/// assert_eq!(s, "wor");
///
/// // No matter how many times we push now, nothing will be added.
/// assert_eq!(0, s.push_str_saturating("!"));
/// assert_eq!(s, "wor");
/// assert_eq!(0, s.push_str_saturating("γΈγγ"));
/// assert_eq!(s, "wor");
/// assert_eq!(0, s.push_str_saturating("ζ"));
/// assert_eq!(s, "wor");
/// assert_eq!(0, s.push_str_saturating("π¦"));
/// assert_eq!(s, "wor");
/// ```
pub fn push_str_saturating(&mut self, s: impl AsRef<str>) -> usize {
let s = s.as_ref();
let s_len = s.len();
let remaining = self.remaining();
// If byte length is the same or less, we can just copy.
if s_len <= remaining {
self.push_str_panic(s);
return s_len;
}
// Figure out what `char` index we can stop at.
let index = if s.is_ascii() {
remaining
} else {
// Handle UTF-8 correctly.
// We use `.rev()` because we assume the string
// is only slightly longer, so starting linear
// search from the end is faster.
let mut index = 0;
for (i, _) in s.char_indices().rev() {
index = i;
if i <= remaining {
break;
}
}
// We didn't find a good index, push nothing.
if index == 0 {
return 0;
}
index
};
#[allow(clippy::string_slice)]
self.push_str_panic(&s[..index]);
index
}
#[inline]
#[allow(clippy::missing_errors_doc)]
/// [`Str::push_str`], but with a `char`
///
/// This acts in the same way as [`Str::push_str`], but the input is a single [`char`].
///
/// ```rust
/// # use readable::str::*;
/// let mut string = Str::<3>::new();
///
/// // Input char is 4 in length.
/// // We can't push it.
/// let err = string.push_char('π¦');
/// assert_eq!(err, Err(1));
///
/// // The string is still empty.
/// assert!(string.is_empty());
///
/// // This 3 length char will fit.
/// assert_eq!(string.push_char('γ§'), Ok(3));
/// assert_eq!(string, "γ§");
/// ```
pub fn push_char(&mut self, c: char) -> Result<usize, usize> {
if self.remaining() == 0 {
return Err(0);
}
match c.len_utf8() {
1 => self.push_str(c.encode_utf8(&mut [0; 1])),
2 => self.push_str(c.encode_utf8(&mut [0; 2])),
3 => self.push_str(c.encode_utf8(&mut [0; 3])),
_ => self.push_str(c.encode_utf8(&mut [0; 4])),
}
}
#[inline]
/// [`Str::push_str_panic`], but with a `char`
///
/// This acts in the same way as [`Str::push_str_panic`], but the input is a single [`char`].
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<5>::new();
/// assert_eq!(s.push_char_panic('γ'), 3);
/// ```
///
/// ## Panics
/// If the push failed, this function panics.
///
/// Input `char` is `>` than capacity:
/// ```rust,should_panic
/// # use readable::str::*;
/// let mut s = Str::<3>::new();
/// s.push_char_panic('π¦');
/// ```
///
/// [`Str`] has no more remaining capacity:
/// ```rust,should_panic
/// # use readable::str::*;
/// let mut s = Str::<4>::from_static_str("wow");
/// assert_eq!(s.len(), 3);
/// assert_eq!(s.remaining(), 1);
///
/// // This won't fit, will panic.
/// s.push_char_panic('π¦');
/// ```
pub fn push_char_panic(&mut self, c: char) -> usize {
match c.len_utf8() {
1 => self.push_str_panic(c.encode_utf8(&mut [0; 1])),
2 => self.push_str_panic(c.encode_utf8(&mut [0; 2])),
3 => self.push_str_panic(c.encode_utf8(&mut [0; 3])),
_ => self.push_str_panic(c.encode_utf8(&mut [0; 4])),
}
}
/// [`Str::push_str_saturating`], but with a `char`
///
/// This acts in the same way as [`Str::push_str_saturating`], but the input is a single [`char`].
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<7>::new();
///
/// // Crab is 4 bytes.
/// assert_eq!(4, "π¦".len());
///
/// // Our capacity is only 7, so we can only fit 1.
/// assert_eq!(4, s.push_char_saturating('π¦'));
/// assert_eq!(0, s.push_char_saturating('π¦'));
/// assert_eq!(s, "π¦");
/// assert_eq!(4, s.len());
/// assert_eq!(3, s.remaining());
/// ```
///
/// ## Examples
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<3>::new();
///
/// assert_eq!(1, s.push_char_saturating('w'));
/// assert_eq!(1, s.push_char_saturating('o'));
/// assert_eq!(1, s.push_char_saturating('w'));
/// assert_eq!(s, "wow");
///
/// // No matter how many times we push now, nothing will be added.
/// assert_eq!(0, s.push_char_saturating('!'));
/// assert_eq!(s, "wow");
/// assert_eq!(0, s.push_char_saturating('γΈ'));
/// assert_eq!(s, "wow");
/// assert_eq!(0, s.push_char_saturating('ζ'));
/// assert_eq!(s, "wow");
/// assert_eq!(0, s.push_char_saturating('π¦'));
/// assert_eq!(s, "wow");
/// ```
pub fn push_char_saturating(&mut self, c: char) -> usize {
if self.remaining() == 0 {
return 0;
}
match c.len_utf8() {
1 => self.push_str_saturating(c.encode_utf8(&mut [0; 1])),
2 => self.push_str_saturating(c.encode_utf8(&mut [0; 2])),
3 => self.push_str_saturating(c.encode_utf8(&mut [0; 3])),
_ => self.push_str_saturating(c.encode_utf8(&mut [0; 4])),
}
}
#[inline]
#[must_use]
/// Decomposes a [`Str`] into its raw components
///
/// Returns the byte array buffer and the valid UTF-8 length of the [`Str`].
///
/// ```rust
/// # use readable::str::*;
/// let s = Str::<5>::from_static_str("hi");
/// let (buf, len) = s.into_raw();
///
/// assert_eq!(buf, [b'h', b'i', 0, 0, 0]);
/// assert_eq!(len, 2);
/// ```
pub const fn into_raw(self) -> ([u8; N], u8) {
(self.buf, self.len)
}
#[inline]
#[must_use]
/// Creates a new [`Str`] from a byte array buffer and a length
///
/// ```rust
/// # use readable::str::*;
/// let buf = [b'h', b'i', 0, 0, 0];
/// let len = 2;
///
/// // SAFETY: The length covers valid
/// // UTF-8 bytes in the provided buffer.
/// let s = unsafe { Str::<5>::from_raw(buf, len) };
/// assert_eq!(s, "hi");
/// ```
///
/// ## Safety
/// The caller needs to make sure the bytes covered
/// by the `len` are actual valid UTF-8 bytes.
pub const unsafe fn from_raw(buf: [u8; N], len: u8) -> Self {
Self { buf, len }
}
#[inline]
#[must_use]
/// Create a [`Str`] directly from a [`str`]
///
/// ```rust
/// # use readable::str::*;
/// let s = Str::<5>::from_str_exact("12345");
/// assert_eq!(s, "12345");
/// ```
///
/// ## Panics
/// The input input [`str`] `string`'s length must
/// be exactly equal to `Self::CAPACITY` or this
/// function will panic.
///
/// ```rust,should_panic
/// # use readable::str::*;
/// // 1 too many characters, will panic.
/// let s = Str::<4>::from_str_exact("12345");
/// ```
pub fn from_str_exact(string: impl AsRef<str>) -> Self {
// SAFETY: `str` is valid UTF-8
unsafe { Self::from_bytes_exact(string.as_ref().as_bytes()) }
}
#[inline]
#[must_use]
/// Create a [`Str`] directly from bytes
///
/// ```rust
/// # use readable::str::*;
/// let s = unsafe { Str::<5>::from_bytes_exact(b"12345") };
/// assert_eq!(s, "12345");
/// ```
///
/// ## Safety
/// The bytes must be valid UTF-8.
///
/// ## Panics
/// The input bytes `bytes`'s length must
/// be exactly equal to `Self::CAPACITY` or this
/// function will panic.
///
/// ```rust,should_panic
/// # use readable::str::*;
/// // 1 too many characters, will panic.
/// let s = unsafe { Str::<4>::from_bytes_exact(b"12345") };
/// ```
pub unsafe fn from_bytes_exact(bytes: impl AsRef<[u8]>) -> Self {
let mut buf = [0; N];
buf.copy_from_slice(bytes.as_ref());
Self {
len: N as u8,
buf,
}
}
#[inline]
/// Calls [`str::make_ascii_uppercase`].
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<5>::from_static_str("hello");
///
/// s.make_ascii_uppercase();
/// assert_eq!(s, "HELLO");
/// ```
pub fn make_ascii_uppercase(&mut self) {
// SAFETY: we aren't changing the length, safe to call.
unsafe { self.as_str_mut().make_ascii_uppercase(); }
}
#[inline]
/// Calls [`str::make_ascii_lowercase`].
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<5>::from_static_str("HELLO");
///
/// s.make_ascii_lowercase();
/// assert_eq!(s, "hello");
/// ```
pub fn make_ascii_lowercase(&mut self) {
// SAFETY: we aren't changing the length, safe to call.
unsafe { self.as_str_mut().make_ascii_lowercase(); }
}
#[inline]
/// Shortens this [`Str`] to the specified length.
///
/// If `new_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
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<4>::from_static_str("asdf");
///
/// s.truncate(1);
/// assert_eq!(s, "a");
/// ```
///
/// ## Panics
/// Panics if `new_len` does not lie on a [`char`] boundary.
///
/// ```rust,should_panic
/// # use readable::str::*;
/// let mut s = Str::<6>::from_static_str("γ§γ");
///
/// // This does not lie on a full char, it will panic.
/// s.truncate(4);
/// ```
pub fn truncate(&mut self, new_len: usize) {
if new_len <= self.len() {
assert!(self.as_str().is_char_boundary(new_len));
// SAFETY: bytes are valid.
unsafe { self.set_len(new_len); }
}
}
#[inline]
/// Removes a [`char`] from this [`Str`] at a byte position and returns it.
///
/// This is an _O(n)_ operation, as it requires copying every element in the buffer.
///
/// ```
/// # use readable::str::*;
/// let mut s = Str::<3>::from_static_str("foo");
///
/// assert_eq!(s.remove(0), 'f');
/// assert_eq!(s.remove(1), 'o');
/// assert_eq!(s.remove(0), 'o');
/// ```
///
/// ## Panics
/// Panics if `idx` is larger than or equal to the [`Str`]βs length,
/// or if it does not lie on a [`char`] boundary.
pub fn remove(&mut self, idx: usize) -> char {
#[allow(clippy::string_slice)]
let ch = self.as_str()[idx..].chars().next().expect("cannot remove a char from the end of a string");
let next = idx + ch.len_utf8();
let len = self.len();
// SAFETY: https://doc.rust-lang.org/1.74.0/src/alloc/string.rs.html#1298
unsafe {
std::ptr::copy(self.as_ptr().add(next), self.as_mut_ptr().add(idx), len - next);
self.set_len(len - (next - idx));
}
ch
}
#[inline]
/// Removes the last character from the [`Str`] and returns it.
///
/// Returns `None` if this [`Str`] is empty.
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<3>::from_static_str("foo");
///
/// assert_eq!(s.len(), 3);
/// assert_eq!(s.pop(), Some('o'));
/// assert_eq!(s.len(), 2);
/// assert_eq!(s.pop(), Some('o'));
/// assert_eq!(s.len(), 1);
/// assert_eq!(s.pop(), Some('f'));
/// assert_eq!(s.len(), 0);
/// assert_eq!(s.pop(), None);
/// ```
pub fn pop(&mut self) -> Option<char> {
// https://doc.rust-lang.org/1.74.0/src/alloc/string.rs.html#1268
let ch = self.as_str().chars().next_back()?;
let newlen = self.len() - ch.len_utf8();
// SAFETY: setting length.
unsafe { self.set_len(newlen); }
Some(ch)
}
}
//---------------------------------------------------------------------------------------------------- From
/// This is a macro for now since `TryFrom<AsRef<str>>` has some conflicts.
macro_rules! impl_from_str {
($($string:ty),*) => {
$(
impl<const N: usize> TryFrom<$string> for Str<N> {
type Error = usize;
#[inline]
/// This takes in a [`&str`] of any length (equal to or less than N)
/// and will return a `Str` with that same string.
///
/// If this function fails, [`Result::Err`] is returned with how many extra bytes couldn't fit.
///
/// ```rust
/// # use readable::str::*;
/// // Input string is 4 in length, we can't copy it.
/// // There is 1 extra byte that can't fit.
/// assert_eq!(Str::<3>::try_from("abcd"), Err(1));
///
/// assert_eq!(Str::<3>::try_from("abc").unwrap(), "abc");
/// ```
///
/// ## Compile-time panic
/// This function will panic at compile time if `N > 255`.
/// ```rust,ignore
/// # use readable::str::*;
/// // Compile error!
/// Str::<256>::try_from("");
/// ```
fn try_from(string: $string) -> Result<Self, Self::Error> {
let len = string.len();
if len == 0 {
Ok(Self::new())
} else if len < N {
let mut this = Self::new();
this.push_str_panic(&string);
Ok(this)
} else if len == N {
let this = Self::from_str_exact(&string);
Ok(this)
} else {
Err(len - N)
}
}
}
)*
};
}
impl_from_str! {
&str,
Arc<str>, &Arc<str>,
Box<str>, &Box<str>,
Rc<str>, &Rc<str>,
Cow<'_, str>, &Cow<'_, str>,
String, &String
}
/// This is a macro for now since `TryFrom<AsRef<[u8]>>` has some conflicts.
macro_rules! impl_from_bytes {
($($bytes:ty),*) => {
$(
impl<const N: usize> TryFrom<$bytes> for Str<N> {
type Error = usize;
#[inline]
/// This takes in a [`[u8]`] of any length (equal to or less than N)
/// and will return a `Str` with that same string.
///
/// If this function fails, [`Result::Err`] is returned with how many extra bytes couldn't fit.
///
/// If the [`Err`] is `0`, that means the string was not valid UTF-8.
///
/// ```rust
/// # use readable::str::*;
/// // Input string is 4 in length, we can't copy it.
/// // There is 1 extra byte that can't fit.
/// assert_eq!(Str::<3>::try_from(b"abcd"), Err(1));
///
/// assert_eq!(Str::<3>::try_from(b"abc").unwrap(), "abc");
/// ```
///
/// ## Compile-time panic
/// This function will panic at compile time if `N > 255`.
/// ```rust,ignore
/// # use readable::str::*;
/// // Compile error!
/// Str::<256>::try_from(b"");
/// ```
fn try_from(bytes: $bytes) -> Result<Self, Self::Error> {
let Ok(s) = std::str::from_utf8(&bytes) else {
return Err(0);
};
Self::try_from(s)
}
}
)*
};
}
impl_from_bytes! {
&[u8],
Arc<[u8]>, &Arc<[u8]>,
Box<[u8]>, &Box<[u8]>,
Rc<[u8]>, &Rc<[u8]>,
Cow<'_, [u8]>, &Cow<'_, [u8]>,
Vec<u8>, &Vec<u8>
}
impl<const N: usize, const ARRAY: usize> TryFrom<[u8; ARRAY]> for Str<N> {
type Error = usize;
#[inline]
fn try_from(bytes: [u8; ARRAY]) -> Result<Self, Self::Error> {
TryFrom::<&[u8]>::try_from(&bytes)
}
}
impl<const N: usize, const ARRAY: usize> TryFrom<&[u8; ARRAY]> for Str<N> {
type Error = usize;
#[inline]
fn try_from(bytes: &[u8; ARRAY]) -> Result<Self, Self::Error> {
TryFrom::<&[u8]>::try_from(bytes)
}
}
//---------------------------------------------------------------------------------------------------- Traits
impl<const N: usize> PartialEq<str> for Str<N> {
#[inline]
fn eq(&self, other: &str) -> bool {
self.as_str() == other
}
}
impl<const N: usize> PartialEq<&str> for Str<N> {
#[inline]
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl<const N: usize> std::fmt::Display for Str<N> {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl<const N: usize> std::ops::Deref for Str<N> {
type Target = str;
#[inline]
/// Equivalent to [`Str::as_str()`].
///
/// ```rust
/// # use readable::str::*;
/// use std::ops::Deref;
/// let mut s = Str::<3>::from_static_str("foo");
///
/// assert_eq!(s.deref(), "foo");
/// ```
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl<const N: usize> std::convert::AsRef<str> for Str<N> {
#[inline]
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl<const N: usize> std::borrow::Borrow<str> for Str<N> {
#[inline]
fn borrow(&self) -> &str {
self.as_str()
}
}
impl<const N: usize> std::default::Default for Str<N> {
#[inline]
/// Calls [`Self::new`]
fn default() -> Self {
Self::new()
}
}
impl<const N: usize, T: AsRef<str>> std::ops::Add<T> for Str<N> {
type Output = Self;
#[inline]
/// Implements the `+` operator.
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<6>::from_static_str("foo");
///
/// assert_eq!(s + "bar", "foobar");
/// ```
///
/// ## Panics
/// This calls [`Str::push_str_panic`] and will panic in the same ways.
///
/// ```rust,should_panic
/// # use readable::str::*;
/// let mut s = Str::<3>::from_static_str("foo");
///
/// // This will panic, not enough capacity!
/// let _ = s + "bar";
/// ```
fn add(self, s: T) -> Self::Output {
let mut new = self;
new.push_str_panic(s.as_ref());
new
}
}
impl<const N: usize, T: AsRef<str>> std::ops::AddAssign<T> for Str<N> {
#[inline]
/// Implements the `+=` operator.
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<6>::from_static_str("foo");
/// s += "bar";
///
/// assert_eq!(s, "foobar");
/// ```
///
/// ## Panics
/// This calls [`Str::push_str_panic`] and will panic in the same ways.
///
/// ```rust,should_panic
/// # use readable::str::*;
/// let mut s = Str::<3>::from_static_str("foo");
///
/// // This will panic, not enough capacity!
/// s += "bar";
/// ```
fn add_assign(&mut self, s: T) {
self.push_str_panic(s.as_ref());
}
}
impl<const N: usize> AsRef<[u8]> for Str<N> {
#[inline]
/// Calls [`Str::as_bytes()`], only including valid `UTF-8` bytes.
///
/// ```rust
/// # use readable::str::*;
/// // 6 in capacity, but only 3 in length.
/// let mut s = Str::<6>::from_static_str("foo");
///
/// assert_eq!(AsRef::<[u8]>::as_ref(&s), "foo".as_bytes());
/// ```
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl<const N: usize> AsRef<std::path::Path> for Str<N> {
#[inline]
fn as_ref(&self) -> &std::path::Path {
std::path::Path::new(self.as_str())
}
}
impl<const N: usize> AsRef<std::ffi::OsStr> for Str<N> {
#[inline]
fn as_ref(&self) -> &std::ffi::OsStr {
std::ffi::OsStr::new(self.as_str())
}
}
impl<const N: usize> Extend<char> for Str<N> {
#[inline]
/// Calls [`Str::push_char_panic`] for each `char`.
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<3>::new();
///
/// s.extend(['a', 'b', 'c']);
/// assert_eq!(s, "abc");
/// ```
fn extend<T: IntoIterator<Item = char>>(&mut self, iter: T) {
iter
.into_iter()
.for_each(|c| { self.push_char_panic(c); });
}
}
impl<'a, const N: usize> Extend<&'a str> for Str<N> {
#[inline]
/// Calls [`Str::push_str_panic`] for each `str`.
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<12>::new();
///
/// s.extend(["hello", " ", "world", "!"]);
/// assert_eq!(s, "hello world!");
/// ```
fn extend<T: IntoIterator<Item = &'a str>>(&mut self, iter: T) {
iter
.into_iter()
.for_each(|c|{ self.push_str_panic(c); });
}
}
macro_rules! impl_index {
($($range:ident),* $(,)?) => {
$(
impl<const N: usize> std::ops::Index<std::ops::$range<usize>> for Str<N> {
type Output = str;
#[inline]
fn index(&self, index: std::ops::$range<usize>) -> &Self::Output {
self.as_str().index(index)
}
}
)*
};
}
impl<const N: usize> std::ops::Index<std::ops::RangeFull> for Str<N> {
type Output = str;
#[inline]
fn index(&self, index: std::ops::RangeFull) -> &Self::Output {
self.as_str().index(index)
}
}
impl_index! {
Range,
RangeFrom,
RangeInclusive,
RangeTo,
RangeToInclusive,
}
impl<const N: usize> std::fmt::Write for Str<N> {
#[inline]
/// Calls [`Str::push_str()`]
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<12>::new();
///
/// std::fmt::Write::write_str(&mut s, "hello world!").unwrap();
/// assert_eq!(s, "hello world!");
/// ```
fn write_str(&mut self, s: &str) -> std::fmt::Result {
match self.push_str(s) {
Ok(_) => Ok(()),
Err(_) => Err(std::fmt::Error),
}
}
#[inline]
/// Calls [`Str::push_char()`]
///
/// ```rust
/// # use readable::str::*;
/// let mut s = Str::<3>::new();
///
/// std::fmt::Write::write_char(&mut s, 'γ§').unwrap();
/// assert_eq!(s, "γ§");
/// ```
fn write_char(&mut self, c: char) -> std::fmt::Result {
match self.push_char(c) {
Ok(_) => Ok(()),
Err(_) => Err(std::fmt::Error),
}
}
}
//---------------------------------------------------------------------------------------------------- Serde
#[cfg(feature = "serde")]
impl<const N: usize> serde::Serialize for Str<N>
{
#[inline]
/// ```rust
/// # use readable::str::*;
/// let s: Str<5> = Str::from_str_exact("hello");
/// let json = serde_json::to_string(&s).unwrap();
/// assert_eq!(json, "\"hello\"");
/// ```
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: serde::Serializer
{
serializer.serialize_str(self.as_str())
}
}
#[cfg(feature = "serde")]
impl<'de, const N: usize> serde::Deserialize<'de> for Str<N>
{
#[inline]
/// ```rust
/// # use readable::str::*;
/// let s: Str<5> = Str::from_str_exact("hello");
/// let json = serde_json::to_string(&s).unwrap();
/// assert_eq!(json, "\"hello\"");
///
/// let s: Str<5> = serde_json::from_str(&json).unwrap();
/// assert_eq!(s, "hello");
///
/// // Too long.
/// assert!(serde_json::from_str::<Str<4>>(&json).is_err());
/// ```
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: serde::Deserializer<'de>
{
use serde::de::{self, Visitor};
use std::marker::PhantomData;
struct StrVisitor<const N: usize>(PhantomData<[u8; N]>);
impl<const N: usize> Visitor<'_> for StrVisitor<N> {
type Value = Str<N>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(formatter, "a string no more than {N} bytes long")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where E: de::Error,
{
#[allow(clippy::map_err_ignore)]
Str::try_from(v).map_err(|_| E::invalid_length(v.len(), &self))
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where E: de::Error,
{
#[allow(clippy::map_err_ignore)]
Str::try_from(v).map_err(|_| E::invalid_length(v.len(), &self))
}
}
deserializer.deserialize_str(StrVisitor(PhantomData))
}
}
#[cfg(feature = "bincode")]
impl<const N: usize> bincode::Encode for Str<N> {
#[inline]
/// ```rust
/// # use readable::str::*;
/// let s: Str<5> = Str::from_str_exact("hello");
/// let config = bincode::config::standard();
/// let bytes = bincode::encode_to_vec(&s, config).unwrap();
/// assert_eq!(bytes, bincode::encode_to_vec(&"hello", config).unwrap());
/// ```
fn encode<E: bincode::enc::Encoder>(&self, encoder: &mut E) -> Result<(), bincode::error::EncodeError> {
bincode::Encode::encode(self.as_str(), encoder)
}
}
#[cfg(feature = "bincode")]
impl<const N: usize> bincode::Decode for Str<N> {
#[inline]
/// ```rust
/// # use readable::str::*;
/// let s: Str<5> = Str::from_str_exact("hello");
/// let config = bincode::config::standard();
/// let bytes = bincode::encode_to_vec(&s, config).unwrap();
/// assert_eq!(bytes, bincode::encode_to_vec(&"hello", config).unwrap());
///
/// let s: Str<5> = bincode::decode_from_slice(&bytes, config).unwrap().0;
/// assert_eq!(s, "hello");
///
/// // Too long.
/// assert!(bincode::decode_from_slice::<Str<4>, _>(&bytes, config).is_err());
/// ```
fn decode<D: bincode::de::Decoder>(decoder: &mut D) -> Result<Self, bincode::error::DecodeError> {
let s: String = bincode::Decode::decode(decoder)?;
#[allow(clippy::map_err_ignore)]
Self::try_from(s).map_err(|_| bincode::error::DecodeError::Other("Str::invalid() failed"))
}
}
#[cfg(feature = "bincode")]
impl<'de, const N: usize> bincode::BorrowDecode<'de> for Str<N> {
fn borrow_decode<D: bincode::de::BorrowDecoder<'de>>(decoder: &mut D) -> Result<Self, bincode::error::DecodeError> {
bincode::Decode::decode(decoder)
}
}
#[cfg(feature = "borsh")]
impl<const N: usize> borsh::BorshSerialize for Str<N> {
#[inline]
/// ```rust
/// # use readable::str::*;
/// let s: Str<5> = Str::from_str_exact("hello");
///
/// let bytes = borsh::to_vec(&s).unwrap();
/// assert_eq!(bytes, borsh::to_vec(&"hello").unwrap());
/// ```
fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
borsh::BorshSerialize::serialize(self.as_str(), writer)
}
}
#[cfg(feature = "borsh")]
impl<const N: usize> borsh::BorshDeserialize for Str<N> {
#[inline]
/// ```rust
/// # use readable::str::*;
/// let s: Str<5> = Str::from_str_exact("hello");
///
/// let bytes = borsh::to_vec(&s).unwrap();
/// assert_eq!(bytes, borsh::to_vec(&"hello").unwrap());
///
/// let s: Str<5> = borsh::from_slice(&bytes).unwrap();
/// assert_eq!(s, "hello");
///
/// assert!(borsh::from_slice::<Str<4>>(&bytes).is_err());
/// ```
fn deserialize_reader<R: std::io::Read>(reader: &mut R) -> borsh::io::Result<Self> {
let s: String = borsh::BorshDeserialize::deserialize_reader(reader)?;
#[allow(clippy::map_err_ignore)]
Self::try_from(s).map_err(|_| borsh::io::Error::new(borsh::io::ErrorKind::Other, "Str::try_from() failed"))
}
}
//---------------------------------------------------------------------------------------------------- TESTS
//#[cfg(test)]
//mod tests {
// #[test]
// fn __TEST__() {
// }
//}