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
#![warn(deprecated_in_future)] #![feature(slice_range)] #![feature(maybe_uninit_uninit_array)] #![feature(maybe_uninit_array_assume_init)] #![feature(maybe_uninit_write_slice)] #![feature(maybe_uninit_extra)] #![feature(iter_zip)] #![feature(extend_one)] #![feature(exact_size_is_empty)] #![feature(trusted_len)] #![feature(min_specialization)] #![feature(decl_macro)] #![deny(unsafe_op_in_unsafe_fn)] #![deny(unaligned_references)] #![feature(box_syntax)] #![feature(box_into_inner)] #![feature(slice_partition_dedup)] #![feature(iter_map_while)] #![warn(rust_2018_idioms)] mod buf; mod drain; mod drain_filter; mod eq; mod error; mod extend; mod extend_from_within; mod extend_with; mod from; mod from_elem; mod from_iter; mod from_iter_nested; mod into_iter; mod kind; mod macros; mod splice; #[cfg(test)] mod tests; mod write_slice; use buf::Storage; pub use drain::Drain; pub use drain_filter::DrainFilter; use error::{infallible, TryReserveError}; use extend::SpecExtend; use extend_from_within::ExtendFromWithinSpec; use extend_with::{ExtendElement, ExtendFunc, ExtendWith}; use from::SpecFrom; use from_elem::SpecFromElem; use from_iter::SpecFromIter; use from_iter_nested::SpecFromIterNested; pub use into_iter::IntoIter; use kind::Kind; pub use macros::small_vec; pub use splice::Splice; use std::{ alloc::{self, Layout}, borrow::{Borrow, BorrowMut}, cmp, fmt, hash::{Hash, Hasher}, io, iter::{repeat, FromIterator}, mem::{self, ManuallyDrop, MaybeUninit}, ops::{Deref, DerefMut, Index, IndexMut, Range, RangeBounds}, ptr::{self, NonNull}, slice::{self, SliceIndex}, }; use write_slice::SpecWriteSlice; unsafe fn deallocate<T>(ptr: *mut T, capacity: usize) { // This unwrap should succeed since the same did when allocating. let layout = Layout::array::<T>(capacity).expect("fail "); unsafe { alloc::dealloc(ptr as *mut u8, layout); } } /// A `Vec`-like container that can store a small number of elements inline. /// /// `SmallVec` acts like a vector, but can store a limited amount of data inline within the /// `SmallVec` struct rather than in a separate allocation. /// If the data exceeds this limit, the `SmallVec` will *spill* its data onto the heap, /// allocating a new buffer to hold it. /// /// # Example /// /// ``` /// use small_vec2::SmallVec; /// let mut v: SmallVec<u8, 4> = SmallVec::new(); // initialize an empty vector /// /// // The vector can hold up to 4 items without spilling onto the heap. /// v.extend(0..4); /// assert_eq!(v.len(), 4); /// assert!(!v.spilled()); /// assert_eq!(v, &[0, 1, 2, 3]); /// // Pushing another element will force the buffer to spill: /// v.push(4); /// assert_eq!(v.len(), 5); /// assert!(v.spilled()); /// ``` pub struct SmallVec<T, const INLINE_CAPACITY: usize> { // Safety invariants: // * The active union field of `buf` must be consistent with the tag of `kind`. buf: Storage<T, INLINE_CAPACITY>, len: usize, kind: Kind, } impl<T, const N: usize> SmallVec<T, N> { /// Create a new empty `SmallVec`. /// /// The maximum capacity is given by the generic parameter `INLINE_CAPACITY`. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let v: SmallVec<u8, 2> = SmallVec::new(); /// ``` #[inline] pub fn new() -> Self { Self { buf: Storage::from_inline(MaybeUninit::uninit_array()), len: 0, kind: Kind::Stack, } } /// The maximum number of elements this vector can hold inline #[inline] pub(crate) const fn inline_capacity() -> usize { if mem::size_of::<T>() == 0 { usize::MAX } else { N } } /// Return the number of elements in the `SmallVec`. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut array: SmallVec<u8, 3> = SmallVec::from([1, 2, 3]); /// array.pop(); /// assert_eq!(array.len(), 2); /// ``` #[inline] pub fn len(&self) -> usize { self.len } /// Returns whether the `SmallVec` is empty. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut array: SmallVec<u8, 1> = SmallVec::from([1]); /// array.pop(); /// assert_eq!(array.is_empty(), true); /// ``` #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns `true` if the storage has spilled into a separate heap-allocated buffer. #[inline] pub fn spilled(&self) -> bool { self.len() > Self::inline_capacity() || self.get_kind().is_heap() } /// Return the capacity of the `SmallVec`. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let array: SmallVec<u8, 3> = SmallVec::from([1, 2, 3]); /// assert_eq!(array.capacity(), 3); /// ``` #[inline] pub fn capacity(&self) -> usize { if self.spilled() { unsafe { &self.buf.heap }.capacity() } else { Self::inline_capacity() } } /// Sets the length of a vector. /// /// # Safety /// /// This will explicitly set the size of the vector, without actually /// modifying its buffers, so it is up to the caller to ensure that the /// vector is actually the specified size. #[inline] pub unsafe fn set_len(&mut self, new_len: usize) { self.len = new_len; } pub(crate) fn set_inline(&mut self) { self.kind = Kind::Stack; } pub(crate) fn set_heap(&mut self) { self.kind = Kind::Heap; } pub(crate) fn get_kind(&self) -> Kind { self.kind } /// Return a slice containing all elements of the vector. #[inline] pub fn as_slice(&self) -> &[T] { self } /// Return a mutable slice containing all elements of the vector. #[inline] pub fn as_mut_slice(&mut self) -> &mut [T] { self } /// Returns a raw pointer to the vector's buffer. #[inline] fn as_ptr(&self) -> *const T { if self.spilled() { unsafe { self.buf.heap() } } else { unsafe { self.buf.inline() } } } /// Returns a raw mutable pointer to the vector's buffer. #[inline] fn as_mut_ptr(&mut self) -> *mut T { if self.spilled() { unsafe { self.buf.heap_mut() } } else { unsafe { self.buf.inline_mut() } } } pub(crate) fn try_grow_to(&mut self, new_capacity: usize) -> Result<(), TryReserveError> { let len = self.len(); let cap = self.capacity(); let ptr = self.as_mut_ptr(); let unspilled = !self.spilled(); assert!(new_capacity >= len); if new_capacity <= Self::inline_capacity() { if unspilled { // in inline return Ok(()); } // heap to inline self.buf = Storage::from_inline(MaybeUninit::uninit_array()); unsafe { ptr::copy_nonoverlapping(ptr, self.buf.inline_mut(), len) }; unsafe { self.set_len(len) }; unsafe { deallocate(ptr, cap) }; self.set_inline(); } else if new_capacity != cap { let layout = Layout::array::<T>(new_capacity)?; debug_assert!(layout.size() > 0); let new_alloc; if unspilled { //inline to heap new_alloc = NonNull::new(unsafe { alloc::alloc(layout) }) .ok_or(TryReserveError::AllocError { layout })? .cast() .as_ptr(); unsafe { ptr.copy_to(new_alloc, len) }; //注意 self.set_heap(); } else { // heap // This should never fail since the same succeeded // when previously allocating `ptr`. let old_layout = Layout::array::<T>(cap)?; let new_ptr = unsafe { alloc::realloc(ptr as *mut u8, old_layout, layout.size()) }; new_alloc = NonNull::new(new_ptr) .ok_or(TryReserveError::AllocError { layout })? .cast() .as_ptr(); } self.buf = Storage::from_heap(unsafe { Vec::from_raw_parts(new_alloc, len, new_capacity) }); unsafe { self.set_len(len) }; } Ok(()) } /// Re-allocate to set the capacity to `max(new_capacity, INLINE_CAPACITY)`. /// /// # Panics /// /// Panics if `new_capacity` is less than the vector's length /// or if the capacity computation overflows `usize`. pub fn grow_to(&mut self, new_capacity: usize) { infallible(self.try_grow_to(new_capacity)) } pub(crate) fn try_shrink_to(&mut self, new_capacity: usize) -> Result<(), TryReserveError> { let len = self.len(); let cap = self.capacity(); let ptr = self.as_mut_ptr(); let unspilled = !self.spilled(); assert!(new_capacity <= cap); if new_capacity <= Self::inline_capacity() { if unspilled { // inline return Ok(()); } // heap to inline self.buf = Storage::from_inline(MaybeUninit::uninit_array()); unsafe { ptr::copy_nonoverlapping(ptr, self.buf.inline_mut(), len) }; unsafe { self.set_len(len) }; self.set_inline(); unsafe { deallocate(ptr, cap) }; } else if new_capacity != cap { let layout = Layout::array::<T>(new_capacity)?; debug_assert!(layout.size() > 0); // heap // This should never fail since the same succeeded // when previously allocating `ptr`. let old_layout = Layout::array::<T>(cap)?; let new_ptr = unsafe { alloc::realloc(ptr as *mut u8, old_layout, layout.size()) }; let new_alloc = NonNull::new(new_ptr) .ok_or(TryReserveError::AllocError { layout })? .cast() .as_ptr(); self.buf = Storage::from_heap(unsafe { Vec::from_raw_parts(new_alloc, len, new_capacity) }); unsafe { self.set_len(len) }; } Ok(()) } /// Shrinks the capacity of the vector with a lower bound. /// /// The capacity will remain at least as large as both the length /// and the supplied value. /// /// If the current capacity is less than the lower limit, this is a no-op. pub fn shrink_to(&mut self, new_capacity: usize) { infallible(self.try_shrink_to(new_capacity)) } /// Shrink the capacity of the vector as much as possible. /// /// When possible, this will move data from an external heap buffer to the vector's inline /// storage. pub fn shrink_to_fit(&mut self) { if !self.spilled() { return; } let len = self.len(); if Self::inline_capacity() >= len { // heap to inline let cap = self.capacity(); let ptr = unsafe { self.buf.heap_mut() }; self.buf = Storage::from_inline(MaybeUninit::uninit_array()); unsafe { ptr.copy_to_nonoverlapping(self.buf.inline_mut(), len) }; unsafe { deallocate(ptr, cap) }; self.set_inline(); unsafe { self.set_len(len) }; } else if self.capacity() > len { self.grow_to(len) } } /// Reserve capacity for `additional` more elements to be inserted. /// /// May reserve more space to avoid frequent reallocations. pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { let len = self.len(); let cap = self.capacity(); if cap - len >= additional { return Ok(()); } let new_cap = len .checked_add(additional) .and_then(usize::checked_next_power_of_two) .ok_or(TryReserveError::CapacityOverflow)?; self.try_grow_to(new_cap) } /// Reserve capacity for `additional` more elements to be inserted. /// /// May reserve more space to avoid frequent reallocations. /// /// # Panics /// /// Panics if the capacity computation overflows `usize`. pub fn reserve(&mut self, additional: usize) { infallible(self.try_reserve(additional)) } /// Reserve the minimum capacity for `additional` more elements to be inserted. pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { let len = self.len(); let cap = self.capacity(); if cap - len >= additional { return Ok(()); } let new_cap = len .checked_add(additional) .ok_or(TryReserveError::CapacityOverflow)?; self.try_grow_to(new_cap) } /// Reserve the minimum capacity for `additional` more elements to be inserted. /// /// # Panics /// /// Panics if the new capacity overflows `usize`. pub fn reserve_exact(&mut self, additional: usize) { infallible(self.try_reserve_exact(additional)) } #[inline] pub(crate) fn storage(&self) -> &[T] { let len = self.len(); unsafe { slice::from_raw_parts(self.as_ptr(), len) } } #[inline] pub(crate) fn storage_mut(&mut self) -> &mut [T] { let len = self.len(); unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), len) } } /// Shorten the vector, keeping the first `len` elements and dropping the rest. /// /// If `len` is greater than or equal to the vector's current length, this has no /// effect. /// /// This does not re-allocate. If you want the vector's capacity to shrink, call /// [`SmallVec::shrink_to_fit`] after truncating. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut array: SmallVec<u8, 5> = SmallVec::from([1, 2, 3, 4, 5]); /// array.truncate(3); /// assert_eq!(array, &[1, 2, 3]); /// array.truncate(4); /// assert_eq!(array, &[1, 2, 3]); /// ``` pub fn truncate(&mut self, new_len: usize) { let len = self.len(); if new_len < len { unsafe { self.set_len(new_len) }; let tail = unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(new_len), len - new_len) }; unsafe { ptr::drop_in_place(tail) }; } } /// Remove all elements in the vector. #[inline] pub fn clear(&mut self) { self.truncate(0) } /// Removes consecutive duplicate elements. #[inline] pub fn dedup(&mut self) where T: PartialEq<T>, { self.dedup_by(|a, b| a == b); } /// Removes consecutive elements that map to the same key. #[inline] pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq<K>, { self.dedup_by(|a, b| key(a) == key(b)); } /// Removes consecutive duplicate elements using the given equality relation. pub fn dedup_by<F>(&mut self, mut same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool, { // See the implementation of `Vec::dedup_by` in the // standard library for an explanation of this algorithm. let len = self.len(); if len <= 1 { return; } let ptr = self.as_mut_ptr(); let mut w: usize = 1; for r in 1..len { unsafe { let p_r = ptr.add(r); let p_wm1 = ptr.add(w - 1); if !same_bucket(&mut *p_r, &mut *p_wm1) { if r != w { let p_w = p_wm1.add(1); mem::swap(&mut *p_r, &mut *p_w); } w += 1; } } } self.truncate(w); } /// Insert an element at position `index`, shifting all elements after it to the right. /// /// # Panics /// /// Panics if `index` is out of bounds. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut array = SmallVec::<&str, 2>::new(); /// array.insert(0, "x"); /// array.insert(0, "y"); /// assert_eq!(array, &["y", "x"]); /// ``` pub fn insert(&mut self, index: usize, element: T) { #[cold] #[inline(never)] fn assert_failed(index: usize, len: usize) -> ! { panic!( "insertion index (is {}) should be <= len (is {})", index, len ); } let len = self.len(); if index > len { assert_failed(index, len); } // space for the new element if len == self.capacity() { self.reserve(1); } unsafe { // infallible // The spot to put the new value { let p = self.as_mut_ptr().add(index); // Shift everything over to make space. (Duplicating the // `index`th element into two consecutive places.) ptr::copy(p, p.offset(1), len - index); // Write it in, overwriting the first copy of the `index`th // element. ptr::write(p, element); } self.set_len(len + 1); } } /// Push value to the end of the vector. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut array = SmallVec::<_, 2>::new(); /// array.push(1); /// array.push(2); /// assert_eq!(array, &[1, 2]); /// ``` #[inline] pub fn push(&mut self, value: T) { let len = self.len(); let cap = self.capacity(); if len == cap { self.reserve(1); } unsafe { let dst = self.as_mut_ptr().add(len); ptr::write(dst, value); self.set_len(len + 1); } } /// Remove an item from the end of the vector and return it, or None if empty. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut array = SmallVec::<_, 2>::new(); /// array.push(1); /// assert_eq!(array.pop(), Some(1)); /// assert_eq!(array.pop(), None); /// ``` #[inline] pub fn pop(&mut self) -> Option<T> { if self.is_empty() { None } else { let last = self.len() - 1; unsafe { self.set_len(last); Some(ptr::read(self.as_mut_ptr().add(last))) } } } /// Resizes the `SmallVec` in-place so that `len` is equal to `new_len`. /// /// If `new_len` is greater than `len`, the `SmallVec` is extended by the difference, with each /// additional slot filled with the result of calling the closure `f`. The return values from `f` /// will end up in the `SmallVec` in the order they have been generated. /// /// If `new_len` is less than `len`, the `SmallVec` is simply truncated. /// /// This method uses a closure to create new values on every push. If you'd rather `Clone` a given /// value, use `resize`. If you want to use the `Default` trait to generate values, you can pass /// `Default::default()` as the second argument. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut vec : SmallVec<_, 4> = SmallVec::from(vec![1, 2, 3]); /// vec.resize_with(5, Default::default); /// assert_eq!(vec, &[1, 2, 3, 0, 0]); /// /// let mut vec : SmallVec<_, 4> = SmallVec::from(vec![]); /// let mut p = 1; /// vec.resize_with(4, || { p *= 2; p }); /// assert_eq!(vec, &[2, 4, 8, 16]); /// ``` pub fn resize_with<F>(&mut self, new_len: usize, f: F) where F: FnMut() -> T, { let len = self.len(); if len < new_len { self.extend_with(new_len - len, ExtendFunc(f)); } else { self.truncate(new_len); } } /// Resizes the vector so that its length is equal to `len`. /// /// If `len` is less than the current length, the vector simply truncated. /// /// If `len` is greater than the current length, `value` is appended to the /// vector until its length equals `len`. pub fn resize(&mut self, new_len: usize, value: T) where T: Clone, { let len = self.len(); if len < new_len { // self.extend_with(new_len - len, ExtendElement(value)); self.extend(repeat(value).take(new_len - len)); } else { self.truncate(new_len); } } /// Remove the element at position `index`, replacing it with the last element. /// /// This does not preserve ordering, but is O(1). /// /// # Panics /// /// Panics if `index` is out of bounds. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut array: SmallVec<u8, 3> = SmallVec::from([1, 2, 3]); /// assert_eq!(array.swap_remove(0), 1); /// assert_eq!(array, &[3, 2]); /// /// assert_eq!(array.swap_remove(1), 2); /// assert_eq!(array, &[3]); /// ``` #[inline] pub fn swap_remove(&mut self, index: usize) -> T { let len = self.len(); self.swap(len - 1, index); self.pop().unwrap() } /// Retains only the elements specified by the predicate. /// /// In other words, remove all elements `e` such that `f(&e)` returns `false`. /// This method operates in place and preserves the order of the retained /// elements. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut array: SmallVec<u32, 4> = SmallVec::from([1, 2, 3, 4]); /// array.retain(|x| *x & 1 != 0 ); /// assert_eq!(array, &[1, 3]); /// ``` pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&mut T) -> bool, { let mut del = 0; let len = self.len(); for i in 0..len { if !f(&mut self[i]) { del += 1; } else if del > 0 { self.swap(i - del, i); } } self.truncate(len - del); } /// Construct an empty `SmallVec` with enough capacity pre-allocated to store at least `capacity` /// elements. /// /// Will create a heap allocation only if `capacity` is larger than the inline capacity. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let v: SmallVec<u8, 3> = SmallVec::with_capacity(100); /// assert!(v.is_empty()); /// assert!(v.capacity() >= 100); /// ``` pub fn with_capacity(capacity: usize) -> Self { let mut v = SmallVec::new(); v.reserve_exact(capacity); v } /// Splits the collection into two at the given index. /// /// Returns a newly allocated vector containing the elements in the range /// `[at, len)`. After the call, the original vector will be left containing /// the elements `[0, at)` with its previous capacity unchanged. /// /// # Panics /// /// Panics if `at > len`. /// /// ``` /// # use small_vec2::SmallVec; /// let mut vec: SmallVec<u32, 3> = SmallVec::from(vec![1, 2, 3]); /// let vec2 = vec.split_off(2); /// assert_eq!(vec, &[1, 2]); /// assert_eq!(vec2, &[3]); /// let mut vec: SmallVec<u32, 3> = SmallVec::from([1, 2, 3]); /// let vec2 = vec.split_off(2); /// assert_eq!(vec, &[1, 2]); /// assert_eq!(vec2, &[3]); /// ``` #[inline] #[must_use = "use `.truncate()` if you don't need the other half"] pub fn split_off(&mut self, at: usize) -> Self { #[cold] #[inline(never)] fn assert_failed(at: usize, len: usize) -> ! { panic!("`at` split index (is {}) should be <= len (is {})", at, len); } if at > self.len() { assert_failed(at, self.len()); } if at == 0 { // the new vector can take over the original buffer and avoid the copy return mem::replace(self, SmallVec::with_capacity(self.capacity())); } let other_len = self.len() - at; let mut other = SmallVec::with_capacity(other_len); // Unsafely `set_len` and copy items to `other`. unsafe { self.set_len(at); other.set_len(other_len); ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len()); } other } /// Returns the remaining spare capacity of the vector as a slice of /// `MaybeUninit<T>`. /// /// The returned slice can be used to fill the vector with data (e.g. by /// reading from a file) before marking the data as initialized using the /// [`set_len`] method. /// /// [`set_len`]: SmallVec::set_len /// /// # Examples /// /// ``` /// #![feature(maybe_uninit_extra)] /// # use small_vec2::SmallVec; /// // Allocate vector big enough for 10 elements. /// let mut v: SmallVec<_, 10> = SmallVec::with_capacity(10); /// // Fill in the first 3 elements. /// let uninit = v.spare_capacity_mut(); /// uninit[0].write(0); /// uninit[1].write(1); /// uninit[2].write(2); /// // Mark the first 3 elements of the vector as being initialized. /// unsafe { /// v.set_len(3); /// } /// assert_eq!(v, &[0, 1, 2]); /// ``` #[inline] pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] { // Note: // This method is not implemented in terms of `split_at_spare_mut`, // to prevent invalidation of pointers to the buffer. unsafe { slice::from_raw_parts_mut( self.as_mut_ptr().add(self.len()) as *mut MaybeUninit<T>, self.capacity() - self.len(), ) } } /// Returns vector content as a slice of `T`, along with the remaining spare /// capacity of the vector as a slice of `MaybeUninit<T>`. /// /// The returned spare capacity slice can be used to fill the vector with data /// (e.g. by reading from a file) before marking the data as initialized using /// the [`set_len`] method. /// /// [`set_len`]: SmallVec::set_len /// /// Note that this is a low-level API, which should be used with care for /// optimization purposes. If you need to append data to a `SmallVec` /// you can use [`push`], [`extend`], [`extend_from_slice`], /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or /// [`resize_with`], depending on your exact needs. /// /// [`push`]: SmallVec::push /// [`extend`]: SmallVec::extend /// [`extend_from_slice`]: SmallVec::extend_from_slice /// [`extend_from_within`]: SmallVec::extend_from_within /// [`insert`]: SmallVec::insert /// [`append`]: SmallVec::append /// [`resize`]: SmallVec::resize /// [`resize_with`]: SmallVec::resize_with /// /// # Examples /// /// ``` /// #![feature(maybe_uninit_extra)] /// # use small_vec2::SmallVec; /// let mut v: SmallVec<_, 3> = SmallVec::from(vec![1, 1, 2]); /// // Reserve additional space big enough for 10 elements. /// v.reserve(10); /// let (init, uninit) = v.split_at_spare_mut(); /// let sum = init.iter().copied().sum::<u32>(); /// // Fill in the next 4 elements. /// uninit[0].write(sum); /// uninit[1].write(sum * 2); /// uninit[2].write(sum * 3); /// uninit[3].write(sum * 4); /// // Mark the 4 elements of the vector as being initialized. /// unsafe { /// let len = v.len(); /// v.set_len(len + 4); /// } /// assert_eq!(v, &[1, 1, 2, 4, 8, 12, 16]); /// ``` pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) { let Range { start: ptr, end: spare_ptr, } = self.as_mut_ptr_range(); let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>(); let spare_len = self.capacity() - self.len; // SAFETY: // - `ptr` is guaranteed to be valid for `len` elements // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized` unsafe { let initialized = slice::from_raw_parts_mut(ptr, self.len()); let spare = slice::from_raw_parts_mut(spare_ptr, spare_len); (initialized, spare) } } unsafe fn split_at_spare_mut_with_len( &mut self, ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) { let Range { start: ptr, end: spare_ptr, } = self.as_mut_ptr_range(); let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>(); let spare_len = self.capacity() - self.len; // SAFETY: // - `ptr` is guaranteed to be valid for `len` elements // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized` unsafe { let initialized = slice::from_raw_parts_mut(ptr, self.len); let spare = slice::from_raw_parts_mut(spare_ptr, spare_len); (initialized, spare, &mut self.len) } } /// Creates a draining iterator that removes the specified range in the vector /// and yields the removed items. /// /// Note 1: The element range is removed even if the iterator is only /// partially consumed or not consumed at all. /// /// Note 2: It is unspecified how many elements are removed from the vector /// if the `Drain` value is leaked. /// /// # Panics /// /// Panics if the starting point is greater than the end point or if /// the end point is greater than the length of the vector. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut v1: SmallVec<u8, 3> = SmallVec::from([1, 2, 3]); /// let v2: SmallVec<u8, 3> = v1.drain(0..2).collect(); /// assert_eq!(v1, [3]); /// assert_eq!(v2, [1, 2]); /// ``` pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, N> where R: RangeBounds<usize>, { let len = self.len(); let Range { start, end } = slice::range(range, ..len); // Calling `set_len` creates a fresh and thus unique mutable references, making all // older aliases we created invalid. So we cannot call that function. unsafe { self.set_len(start) }; let range_slice = unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start) }; let tail_len = len - end; let iter = range_slice.iter(); let vec = NonNull::from(self); Drain::new(end, tail_len, iter, vec) } /// Creates a splicing iterator that replaces the specified range in the vector /// with the given `replace_with` iterator and yields the removed items. /// `replace_with` does not need to be the same length as `range`. /// /// `range` is removed even if the iterator is not consumed until the end. /// /// It is unspecified how many elements are removed from the vector /// if the `Splice` value is leaked. /// /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped. /// /// This is optimal if: /// /// * The tail (elements in the vector after `range`) is empty, /// * or `replace_with` yields fewer or equal elements than `range`’s length /// * or the lower bound of its `size_hint()` is exact. /// /// Otherwise, a temporary vector is allocated and the tail is moved twice. /// /// # Panics /// /// Panics if the starting point is greater than the end point or if /// the end point is greater than the length of the vector. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut v: SmallVec<_, 3> = SmallVec::from([1, 2, 3]); /// let new = [7, 8]; /// let u: SmallVec<_, 2> = v.splice(..2, new.iter().cloned()).collect(); /// assert_eq!(v, [7, 8, 3]); /// assert_eq!(u, [1, 2]); /// ``` #[inline] pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, N> where R: RangeBounds<usize>, I: IntoIterator<Item = T>, { let drain = self.drain(range); let replace_with = replace_with.into_iter(); Splice::new(drain, replace_with) } /// Creates an iterator which uses a closure to determine if an element should be removed. /// /// If the closure returns true, then the element is removed and yielded. /// If the closure returns false, the element will remain in the vector and will not be yielded /// by the iterator. /// /// Using this method is equivalent to the following code: /// /// ``` /// # use small_vec2::SmallVec; /// let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 }; /// let mut vec:SmallVec<_,6> = SmallVec::from(vec![1, 2, 3, 4, 5, 6]); /// let mut i = 0; /// while i != vec.len() { /// if some_predicate(&mut vec[i]) { /// let val = vec.remove(i); /// // your code here /// } else { /// i += 1; /// } /// } /// assert_eq!(vec, vec![1, 4, 5]); /// ``` /// /// But `drain_filter` is easier to use. `drain_filter` is also more efficient, /// because it can backshift the elements of the array in bulk. /// /// Note that `drain_filter` also lets you mutate every element in the filter closure, /// regardless of whether you choose to keep or remove it. /// /// # Examples /// /// Splitting an array into evens and odds, reusing the original allocation: /// /// ``` /// # use small_vec2::SmallVec; /// let mut numbers: SmallVec<_, 15> = SmallVec::from(vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]); /// /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>(); /// let odds = numbers; /// /// assert_eq!(evens, vec![2, 4, 6, 8, 14]); /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); /// ``` #[inline] pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F, N> where F: FnMut(&mut T) -> bool, { let old_len = self.len(); // Guard against us getting leaked (leak amplification) unsafe { self.set_len(0) }; DrainFilter::new(self, 0, 0, old_len, filter, false) } /// Remove and return the element at position `index`, shifting all elements after it to the /// left. /// /// # Panics /// /// Panics if `index` is out of bounds. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut array: SmallVec<u8, 3> = SmallVec::from([1, 2, 3]); /// let removed_elt = array.remove(0); /// assert_eq!(removed_elt, 1); /// assert_eq!(array, &[2, 3]); /// ``` pub fn remove(&mut self, index: usize) -> T { #[cold] #[inline(never)] fn assert_failed(index: usize, len: usize) -> ! { panic!("removal index (is {}) should be < len (is {})", index, len); } let len = self.len(); if index >= len { assert_failed(index, len); } unsafe { // infallible let ret; { // the place we are taking from. let ptr = self.as_mut_ptr().add(index); // copy it out, unsafely having a copy of the value on // the stack and in the vector at the same time. ret = ptr::read(ptr); // Shift everything down to fill in that spot. ptr::copy(ptr.offset(1), ptr, len - index - 1); } self.set_len(len - 1); ret } } #[inline] unsafe fn append_elements(&mut self, other: *const [T]) { let count = unsafe { (*other).len() }; self.reserve(count); let len = self.len(); unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; self.len += count; } /// Moves all the elements of `other` into `self`, leaving `other` empty. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut v0: SmallVec<u8, 16> = SmallVec::from(vec![1, 2, 3]); /// let mut v1: SmallVec<u8, 32> = SmallVec::from(vec![4, 5, 6]); /// v0.append(&mut v1); /// assert_eq!(v0, [1, 2, 3, 4, 5, 6]); /// assert_eq!(v1, []); /// /// let mut v0: SmallVec<u8, 3> = SmallVec::from([1, 2, 3]); /// let mut v1: SmallVec<u8, 3> = SmallVec::from([4, 5, 6]); /// v0.append(&mut v1); /// assert_eq!(v0, [1, 2, 3, 4, 5, 6]); /// assert_eq!(v1, []); /// ``` #[inline] pub fn append<const M: usize>(&mut self, other: &mut SmallVec<T, M>) { unsafe { self.append_elements(other.as_slice() as _); other.set_len(0); } } /// Convert the SmallVec into an array if possible. Otherwise return `Err(Self)`. /// /// This method returns `Err(Self)` if the SmallVec is too short (and the array contains uninitialized elements), /// or if the SmallVec is too long (and all the elements were spilled to the heap). pub fn into_inner(self) -> Result<[T; N], Self> { if self.spilled() || self.len() != Self::inline_capacity() { Err(self) } else { unsafe { let data = ptr::read(&self.buf); mem::forget(self); Ok(MaybeUninit::array_assume_init(data.into_inline())) } } } /// Convert a SmallVec to a Vec, without reallocating if the SmallVec has already spilled onto /// the heap. pub fn into_vec(mut self) -> Vec<T> { if self.spilled() { unsafe { let ptr = self.buf.heap_mut(); let len = self.len(); let cap = self.capacity(); let v = Vec::from_raw_parts(ptr, len, cap); mem::forget(self); v } } else { self.into_iter().collect() } } /// Converts a `SmallVec` into a `Box<[T]>` without reallocating if the `SmallVec` has already spilled /// onto the heap. /// /// Note that this will drop any excess capacity. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut vec: SmallVec<u32, 10> = SmallVec::with_capacity(10); /// vec.extend([1, 2, 3].iter().cloned()); /// assert_eq!(vec.capacity(), 10); /// let slice = vec.into_boxed_slice(); /// assert_eq!(slice.into_vec().capacity(), 3); /// ``` pub fn into_boxed_slice(self) -> Box<[T]> { self.into_vec().into_boxed_slice() } pub fn from_slice(slice: &[T]) -> Self where T: Copy, { let len = slice.len(); if len <= Self::inline_capacity() { Self { len, buf: Storage::from_inline(unsafe { let mut data = MaybeUninit::uninit_array(); ptr::copy_nonoverlapping(slice.as_ptr(), data.as_mut_ptr().cast(), len); data }), kind: Kind::Stack, } } else { let vec = slice.to_vec(); Self { len: vec.len(), buf: Storage::from_heap(vec), kind: Kind::Heap, } } } /// Constructs a new `SmallVec` on the stack from an array without /// copying elements. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let buf = [1, 2, 3, 4, 5]; /// let small_vec: SmallVec<u8, 5> = SmallVec::from_array(buf); /// assert_eq!(small_vec, &[1, 2, 3, 4, 5]); /// ``` pub fn from_array(array: [T; N]) -> Self where T: Clone, { let mut dst: [MaybeUninit<T>; N] = MaybeUninit::uninit_array(); MaybeUninit::write_slice_cloned(&mut dst, &array); Self { len: array.len(), buf: Storage::from_inline(dst), kind: Kind::Stack, } } /// Construct a new `SmallVec` from a `Vec<T>`. /// /// Elements will be copied to the inline buffer if `vec.capacity()` <= `Self::inline_capacity()`. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let vec = vec![1, 2, 3, 4, 5]; /// let small_vec: SmallVec<u32, 3> = SmallVec::from_vec(vec); /// assert_eq!(small_vec, &[1, 2, 3, 4, 5]); /// ``` pub fn from_vec(mut vec: Vec<T>) -> Self { let len = vec.len(); if vec.capacity() <= Self::inline_capacity() { let mut buf = Storage::from_inline(MaybeUninit::uninit_array()); unsafe { vec.set_len(0); ptr::copy_nonoverlapping(vec.as_ptr(), buf.inline_mut(), len); } Self { len, buf, kind: Kind::Stack, } } else { Self { len, buf: Storage::from_heap(vec), kind: Kind::Heap, } } } fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) { self.reserve(n); let mut ptr = unsafe { self.as_mut_ptr().add(self.len()) }; // Write all elements except the last one for _ in 1..n { unsafe { ptr::write(ptr, value.next()); ptr = ptr.offset(1); } self.len += 1; } if n > 0 { // We can write the last element directly without cloning needlessly unsafe { ptr::write(ptr, value.last()) }; self.len += 1; } } fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) { while let Some(element) = iterator.next() { let len = self.len(); if len == self.capacity() { let (lower, _) = iterator.size_hint(); self.reserve(lower.saturating_add(1)); } unsafe { ptr::write(self.as_mut_ptr().add(len), element); // NB can't overflow since we would have had to alloc the address space self.set_len(len + 1); } } } /// Copy elements from a slice and append them to the vector. /// /// For slices of `Copy` types, this is more efficient than `extend`. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut vec: SmallVec<usize, 10> = SmallVec::new(); /// vec.push(1); /// vec.extend_from_slice(&[2, 3]); /// assert_eq!(vec, &[1, 2, 3]); /// ``` pub fn extend_from_slice(&mut self, other: &[T]) where T: Clone, { // 注意 self.spec_extend(other.iter()) } pub fn from_elem(elem: T, n: usize) -> Self where T: Clone, { // 注意 <T as SpecFromElem>::spec_from_elem(elem, n) } /// Copies elements from `src` range to the end of the vector. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut vec: SmallVec<_, 5> = SmallVec::from(vec![0, 1, 2, 3, 4]); /// vec.extend_from_within(2..); /// assert_eq!(vec, &[0, 1, 2, 3, 4, 2, 3, 4]); /// /// vec.extend_from_within(..2); /// assert_eq!(vec, &[0, 1, 2, 3, 4, 2, 3, 4, 0, 1]); /// /// vec.extend_from_within(4..8); /// assert_eq!(vec, &[0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]); /// ``` pub fn extend_from_within<R>(&mut self, src: R) where R: RangeBounds<usize>, T: Clone, { let range = slice::range(src, ..self.len()); self.reserve(range.len()); // SAFETY: // - `slice::range` guarantees that the given range is valid for indexing self unsafe { self.spec_extend_from_within(range) }; } /// Creates a `SmallVec` directly from the raw components of another /// `SmallVec`. /// /// # Safety /// /// This is highly unsafe, due to the number of invariants that aren't /// checked: /// /// * `ptr` needs to have been previously allocated via `SmallVec` for its /// spilled storage (at least, it's highly likely to be incorrect if it /// wasn't). /// * `ptr`'s `T` type needs to be the same size and alignment that /// it was allocated with /// * `length` needs to be less than or equal to `capacity`. /// * `capacity` needs to be the capacity that the pointer was allocated /// with. /// /// Violating these may cause problems like corrupting the allocator's /// internal data structures. /// /// Additionally, `capacity` must be greater than the amount of inline /// storage has; that is, the new `SmallVec` must need to spill over /// into heap allocated storage. This condition is asserted against. /// /// The ownership of `ptr` is effectively transferred to the /// `SmallVec` which may then deallocate, reallocate or change the /// contents of memory pointed to by the pointer at will. Ensure /// that nothing else uses the pointer after calling this /// function. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// # use std::ptr; /// let v: SmallVec<_, 3> = SmallVec::from(vec![1, 2, 3, 4, 5]); /// let spilled = v.spilled(); /// let (p, len, cap) = v.into_raw_parts(); /// unsafe { /// // Overwrite memory with [4, 5, 6, 7, 8]. /// // /// // This is only safe if `spilled` is true! Otherwise, we are /// // writing into the old `SmallVec`'s inline storage on the /// // stack. /// assert!(spilled); /// for i in 0..len { /// ptr::write(p.add(i), 4 + i); /// } /// // Put everything back together into a SmallVec with a different /// // amount of inline storage, but which is still less than `cap`. /// let rebuilt = SmallVec::<_, 3>::from_raw_parts(p, len, cap); /// assert_eq!(rebuilt, [4, 5, 6, 7, 8]); /// } /// ``` pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self where T: Clone, { if capacity > Self::inline_capacity() { Self { len: length, buf: Storage::from_heap(unsafe { Vec::from_raw_parts(ptr, length, capacity) }), kind: Kind::Heap, } } else { let mut dst: [MaybeUninit<T>; N] = MaybeUninit::uninit_array(); let src = unsafe { slice::from_raw_parts(ptr, length) }; // let v = unsafe { Vec::from_raw_parts(ptr, length, capacity) }; // let src = v.as_slice(); MaybeUninit::spec_write_slice(&mut dst[..length], src); Self { len: length, buf: Storage::from_inline(dst), kind: Kind::Stack, } } } /// Decomposes a `SmallVec` into its raw components. /// /// Returns the raw pointer to the underlying data, the length of /// the vector (in elements), and the allocated capacity of the /// data (in elements). These are the same arguments in the same /// order as the arguments to [`SmallVec::from_raw_parts`]. /// /// After calling this function, the caller is responsible for the /// memory previously managed by the `SmallVec`. The only way to do /// this is to convert the raw pointer, length, and capacity back /// into a `SmallVec` with the [`SmallVec::from_raw_parts`] function, allowing /// the destructor to perform the cleanup. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let v: SmallVec<i32, 2> = SmallVec::from(vec![-1, 0, 1]); /// let (ptr, len, cap) = v.into_raw_parts(); /// let rebuilt: SmallVec<u32, 2> = unsafe { /// // We can now make changes to the components, such as /// // transmuting the raw pointer to a compatible type. /// let ptr = ptr as *mut u32; /// SmallVec::from_raw_parts(ptr, len, cap) /// }; /// assert_eq!(rebuilt, &[4294967295, 0, 1]); /// ``` pub fn into_raw_parts(self) -> (*mut T, usize, usize) { let mut me = ManuallyDrop::new(self); (me.as_mut_ptr(), me.len(), me.capacity()) } } impl<Item, const N: usize> Drop for SmallVec<Item, N> { fn drop(&mut self) { if self.spilled() { let ptr = self.as_mut_ptr(); unsafe { Vec::from_raw_parts(ptr, self.len(), self.capacity()) }; } else { unsafe { ptr::drop_in_place(&mut self[..]) }; } } } /// Create an `SmallVec` from an array. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut array: SmallVec<u8, 3> = SmallVec::from([1, 2, 3]); /// assert_eq!(array.len(), 3); /// assert_eq!(array.capacity(), 3); /// ``` impl<T: Clone, const N: usize> From<[T; N]> for SmallVec<T, N> { fn from(array: [T; N]) -> Self { SmallVec::from_array(array) } } /// Create an `SmallVec` from an Vec. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut array: SmallVec<u8, 3> = SmallVec::from(vec![1, 2, 3]); /// assert_eq!(array.len(), 3); /// assert_eq!(array.capacity(), 3); /// ``` impl<T, const N: usize> From<Vec<T>> for SmallVec<T, N> { fn from(vec: Vec<T>) -> Self { SmallVec::from_vec(vec) } } /// Create an ` SmallVec` from an slice. /// /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let mut array: SmallVec<u8, 3> = SmallVec::from(&[1, 2, 3][..2]); /// assert_eq!(array.len(), 2); /// assert_eq!(array.capacity(), 3); /// ``` impl<T: Clone, const N: usize> From<&[T]> for SmallVec<T, N> { fn from(slice: &[T]) -> Self { // 注意 SmallVec::spec_from(slice) } } /// # Examples /// /// ``` /// # use small_vec2::SmallVec; /// let vec1: SmallVec<isize, 2> = SmallVec::new(); /// assert_eq!("[]", format!("{:?}", vec1)); /// let vec2: SmallVec<isize, 2> = SmallVec::from([0, 1]); /// assert_eq!("[0, 1]", format!("{:?}", vec2)); /// let slice: &[isize] = &[4, 5]; /// assert_eq!("[4, 5]", format!("{:?}", slice)); impl<T, const N: usize> fmt::Debug for SmallVec<T, N> where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.iter()).finish() } } impl<T, const N: usize> Default for SmallVec<T, N> { #[inline] fn default() -> Self { SmallVec::new() } } impl<T, const N: usize> Clone for SmallVec<T, N> where T: Clone, { fn clone(&self) -> Self { self.iter().cloned().collect() } fn clone_from(&mut self, other: &Self) { // drop anything that will not be overwritten self.truncate(other.len()); // self.len <= other.len due to the truncate above, so the // slices here are always in-bounds. let (init, tail) = other.split_at(self.len()); // reuse the contained values' allocations/resources. self.clone_from_slice(init); self.extend_from_slice(tail); } } impl<T, const N: usize> Deref for SmallVec<T, N> { type Target = [T]; fn deref(&self) -> &Self::Target { self.storage() } } impl<T, const N: usize> DerefMut for SmallVec<T, N> { fn deref_mut(&mut self) -> &mut Self::Target { self.storage_mut() } } impl<T, const N: usize> Hash for SmallVec<T, N> where T: Hash, { #[inline] fn hash<H: Hasher>(&self, state: &mut H) { Hash::hash(&**self, state) } } impl<T: Eq, const N: usize> Eq for SmallVec<T, N> {} impl<T, const N: usize> PartialOrd for SmallVec<T, N> where T: PartialOrd, { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { (**self).partial_cmp(other) } fn lt(&self, other: &Self) -> bool { (**self).lt(other) } fn le(&self, other: &Self) -> bool { (**self).le(other) } fn ge(&self, other: &Self) -> bool { (**self).ge(other) } fn gt(&self, other: &Self) -> bool { (**self).gt(other) } } impl<T, const N: usize> Ord for SmallVec<T, N> where T: Ord, { fn cmp(&self, other: &Self) -> cmp::Ordering { (**self).cmp(other) } } impl<T, const N: usize> Borrow<[T]> for SmallVec<T, N> { fn borrow(&self) -> &[T] { self } } impl<T, const N: usize> BorrowMut<[T]> for SmallVec<T, N> { fn borrow_mut(&mut self) -> &mut [T] { self } } impl<T, const N: usize> AsRef<[T]> for SmallVec<T, N> { fn as_ref(&self) -> &[T] { self } } impl<T, const N: usize> AsMut<[T]> for SmallVec<T, N> { fn as_mut(&mut self) -> &mut [T] { self } } impl<T, I: SliceIndex<[T]>, const N: usize> Index<I> for SmallVec<T, N> { type Output = I::Output; #[inline] fn index(&self, index: I) -> &Self::Output { Index::index(&**self, index) } } impl<T, I: SliceIndex<[T]>, const N: usize> IndexMut<I> for SmallVec<T, N> { #[inline] fn index_mut(&mut self, index: I) -> &mut Self::Output { IndexMut::index_mut(&mut **self, index) } } /// `Write` appends written data to the end of the vector. impl<const N: usize> io::Write for SmallVec<u8, N> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.extend_from_slice(buf); Ok(buf.len()) } fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { self.extend_from_slice(buf); Ok(()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } /// Iterate the `SmallVec` with each element by value. /// /// The vector is consumed by this operation. impl<T, const N: usize> IntoIterator for SmallVec<T, N> { type IntoIter = IntoIter<T, N>; type Item = T; fn into_iter(self) -> IntoIter<T, N> { let len = self.len(); IntoIter::new(0, len, self) } } /// Iterate the `SmallVec` with references to each element. impl<'a, T: 'a, const N: usize> IntoIterator for &'a SmallVec<T, N> { type IntoIter = slice::Iter<'a, T>; type Item = &'a T; fn into_iter(self) -> Self::IntoIter { self.iter() } } /// Iterate the `SmallVec` with mutable references to each element. impl<'a, T: 'a, const N: usize> IntoIterator for &'a mut SmallVec<T, N> { type IntoIter = slice::IterMut<'a, T>; type Item = &'a mut T; fn into_iter(self) -> Self::IntoIter { self.iter_mut() } } /// Extend the `SmallVec` with an iterator. /// /// # Panics /// /// Panics if extending the vector exceeds its capacity. impl<T, const N: usize> Extend<T> for SmallVec<T, N> { #[inline] fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { // 注意 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter()) } #[inline] fn extend_one(&mut self, item: T) { self.push(item); } #[inline] fn extend_reserve(&mut self, additional: usize) { self.reserve(additional); } } impl<'a, T: Copy + 'a, const N: usize> Extend<&'a T> for SmallVec<T, N> { fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) { // 注意 self.spec_extend(iter.into_iter()) } #[inline] fn extend_one(&mut self, &item: &'a T) { self.push(item); } #[inline] fn extend_reserve(&mut self, additional: usize) { self.reserve(additional); } } /// Create an `SmallVec` from an iterator. /// /// # Panics /// /// Panics if the number of elements in the iterator exceeds the smallvec's capacity. impl<T, const N: usize> FromIterator<T> for SmallVec<T, N> { #[inline] fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { // 注意 #[allow(clippy::from_iter_instead_of_collect)] <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter()) } }