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
//! A [disjoint-sets/union-find] implementation of a vector partitioned in sets.
//!
//! [disjoint-sets/union-find]: https://en.wikipedia.org/wiki/Disjoint-set_data_structure
use {
std::{
ops,
cmp::Ordering,
iter::{
FromIterator,
FusedIterator,
},
},
metadata::Metadata,
extend_mut,
};
#[cfg(feature = "rayon")]
use rayon::prelude::*;
/// A [disjoint-sets/union-find] implementation of a vector partitioned in sets.
///
/// Most methods that are defined on a `Vec` also work on a `PartitionVec`.
/// In addition to this each element stored in the `PartitionVec` is a member of a set.
/// Initially each element has its own set but sets can be joined with the `union` method.
///
/// In addition to the normal implementation we store an additional index for each element.
/// These indices form a circular linked list of the set the element is in.
/// This allows for fast iteration of the set using the `set` method
/// and is used to speed up the performance of other methods.
///
/// This implementation chooses not to expose the `find` method and instead has a `same_set` method.
/// This is so that the representative of the set stays an implementation detail which gives
/// us more freedom to change it behind the scenes for improved performance.
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec!['a', 'b', 'c', 'd'];
/// partition_vec.union(1, 2);
/// partition_vec.union(2, 3);
///
/// assert!(partition_vec.same_set(1, 3));
///
/// for (index, &value) in partition_vec.set(1) {
/// assert!(index >= 1);
/// assert!(index <= 3);
/// assert!(value != 'a');
/// }
/// # }
/// ```
///
/// [disjoint-sets/union-find]: https://en.wikipedia.org/wiki/Disjoint-set_data_structure
#[derive(Clone)]
pub struct PartitionVec<T> {
/// Each index has a value.
/// We store these in a separate `Vec` so we can easily dereference it to a slice.
data: Vec<T>,
/// The metadata for each value, this vec will always have the same size as `values`.
meta: Vec<Metadata>,
}
/// Creates a [`PartitionVec`] containing the arguments.
///
/// There are tree forms of the `partition_vec!` macro:
///
/// - Create a [`PartitionVec`] containing a given list of elements all in distinct sets:
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let partition_vec = partition_vec!['a', 'b', 'c'];
///
/// assert!(partition_vec[0] == 'a');
/// assert!(partition_vec[1] == 'b');
/// assert!(partition_vec[2] == 'c');
///
/// assert!(partition_vec.is_singleton(0));
/// assert!(partition_vec.is_singleton(1));
/// assert!(partition_vec.is_singleton(2));
/// # }
/// ```
///
/// - Create a [`PartitionVec`] containing a given list of elements in the sets specified:
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let partition_vec = partition_vec![
/// 'a' => 0,
/// 'b' => 1,
/// 'c' => 2,
/// 'd' => 1,
/// 'e' => 0,
/// ];
///
/// assert!(partition_vec[0] == 'a');
/// assert!(partition_vec[1] == 'b');
/// assert!(partition_vec[2] == 'c');
/// assert!(partition_vec[3] == 'd');
/// assert!(partition_vec[4] == 'e');
///
/// assert!(partition_vec.same_set(0, 4));
/// assert!(partition_vec.same_set(1, 3));
/// assert!(partition_vec.is_singleton(2));
/// # }
/// ```
///
/// You can use any identifiers that implement `Hash` and `Eq`.
/// Elements with the same set identifiers will be placed in the same set.
/// These identifiers will only be used when constructing a [`PartitionVec`]
/// and will not be stored further.
/// This means `println!("{:?}", partition_vec![3 => 'a', 1 => 'a'])` will display `[3 => 0, 1 => 0]`.
///
/// - Create a [`PartitionVec`] of distinct sets from a given element and size:
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let partition_vec = partition_vec!['a'; 3];
///
/// assert!(partition_vec[0] == 'a');
/// assert!(partition_vec[1] == 'a');
/// assert!(partition_vec[2] == 'a');
///
/// assert!(partition_vec.is_singleton(0));
/// assert!(partition_vec.is_singleton(1));
/// assert!(partition_vec.is_singleton(2));
/// # }
/// ```
///
/// [`PartitionVec`]: partition_vec/struct.PartitionVec.html
#[macro_export]
macro_rules! partition_vec {
($elem: expr; $len: expr) => {
$crate::PartitionVec::from_elem($elem, $len);
};
($($elem: expr),*) => {
{
let len = partitions_count_expr![$($elem),*];
let mut partition_vec = $crate::PartitionVec::with_capacity(len);
$(
partition_vec.push($elem);
)*
partition_vec
}
};
($($elem: expr,)*) => {
partition_vec![$($elem),*];
};
($($elem: expr => $set: expr),*) => {
{
let len = partitions_count_expr![$($elem),*];
let mut partition_vec = $crate::PartitionVec::with_capacity(len);
let mut map = ::std::collections::HashMap::new();
$(
let last_index = partition_vec.len();
partition_vec.push($elem);
if let Some(&index) = map.get(&$set) {
partition_vec.union(index, last_index);
} else {
map.insert($set, last_index);
}
)*
partition_vec
}
};
($($elem: expr => $set: expr,)*) => {
partition_vec![$($elem => $set),*];
}
}
impl<T> PartitionVec<T> {
/// Constructs a new, empty `PartitionVec<T>`.
///
/// The `PartitionVec<T>` will not allocate until elements are pushed onto it.
///
/// # Examples
///
/// ```
/// # #![allow(unused_mut)]
/// use partitions::PartitionVec;
///
/// let mut partition_vec: PartitionVec<()> = PartitionVec::new();
/// ```
#[inline]
pub fn new() -> Self {
Self {
data: Vec::new(),
meta: Vec::new(),
}
}
/// Constructs a new, empty `PartitionVec<T>` with the specified capacity.
///
/// The `PartitionVec<T>` will be able to hold exactly `capacity`
/// elements without reallocating.
/// If capacity is 0, the partition_vec will not allocate.
///
/// # Examples
///
/// ```
/// use partitions::PartitionVec;
///
/// let mut partition_vec = PartitionVec::with_capacity(10);
///
/// assert!(partition_vec.len() == 0);
/// assert!(partition_vec.capacity() == 10);
///
/// // This can be done without reallocating.
/// for i in 0 .. 10 {
/// partition_vec.push(i);
/// }
///
/// // We can add more elements but this will reallocate.
/// partition_vec.push(11);
/// ```
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
Self {
data: Vec::with_capacity(capacity),
meta: Vec::with_capacity(capacity),
}
}
/// Joins the sets of the `first_index` and the `second_index`.
///
/// This method will be executed in `O(α(n))` time where `α` is the inverse
/// Ackermann function. The inverse Ackermann function has value below 5
/// for any value of `n` that can be written in the physical universe.
///
/// # Panics
///
/// If `first_index` or `second_index` is out of bounds.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![(); 4];
///
/// // All elements start out in their own sets.
/// assert!(partition_vec.len_of_set(0) == 1);
/// assert!(partition_vec.len_of_set(1) == 1);
/// assert!(partition_vec.len_of_set(2) == 1);
/// assert!(partition_vec.len_of_set(3) == 1);
///
/// partition_vec.union(1, 2);
///
/// // Now 1 and 2 share a set.
/// assert!(partition_vec.len_of_set(0) == 1);
/// assert!(partition_vec.len_of_set(1) == 2);
/// assert!(partition_vec.len_of_set(2) == 2);
/// assert!(partition_vec.len_of_set(3) == 1);
///
/// partition_vec.union(2, 3);
///
/// // We added 3 to the existing set with 1 and 2.
/// assert!(partition_vec.len_of_set(0) == 1);
/// assert!(partition_vec.len_of_set(1) == 3);
/// assert!(partition_vec.len_of_set(2) == 3);
/// assert!(partition_vec.len_of_set(3) == 3);
/// # }
/// ```
pub fn union(&mut self, first_index: usize, second_index: usize) {
let i = self.find(first_index);
let j = self.find(second_index);
if i == j {
return
}
// We swap the values of the links.
let link_i = self.meta[i].link();
let link_j = self.meta[j].link();
self.meta[i].set_link(link_j);
self.meta[j].set_link(link_i);
// We add to the tree with the highest rank.
match Ord::cmp(&self.meta[i].rank(), &self.meta[j].rank()) {
Ordering::Less => {
self.meta[i].set_parent(j);
},
Ordering::Equal => {
// We add the first tree to the second tree.
self.meta[i].set_parent(j);
// The second tree becomes larger.
self.meta[j].set_rank(self.meta[j].rank() + 1);
},
Ordering::Greater => {
self.meta[j].set_parent(i);
},
}
}
/// Returns `true` if `first_index` and `second_index` are in the same set.
///
/// This method will be executed in `O(α(n))` time where `α` is the inverse
/// Ackermann function.
///
/// # Panics
///
/// If `first_index` or `second_index` are out of bounds.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// # fn main() {
/// let mut partition_vec = partition_vec![(); 4];
///
/// partition_vec.union(1, 3);
/// partition_vec.union(0, 1);
///
/// assert!(partition_vec.same_set(0, 1));
/// assert!(!partition_vec.same_set(0, 2));
/// assert!(partition_vec.same_set(0, 3));
/// assert!(!partition_vec.same_set(1, 2));
/// assert!(partition_vec.same_set(1, 3));
/// assert!(!partition_vec.same_set(2, 3));
/// # }
/// ```
#[inline]
pub fn same_set(&self, first_index: usize, second_index: usize) -> bool {
self.find(first_index) == self.find(second_index)
}
/// Returns `true` if `first_index` and `second_index` are in different sets.
///
/// This method will be executed in `O(α(n))` time where `α` is the inverse
/// Ackermann function.
///
/// # Panics
///
/// If `first_index` or `second_index` are out of bounds.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// # fn main() {
/// let mut partition_vec = partition_vec![(); 4];
///
/// partition_vec.union(1, 3);
/// partition_vec.union(0, 1);
///
/// assert!(!partition_vec.other_sets(0, 1));
/// assert!(partition_vec.other_sets(0, 2));
/// assert!(!partition_vec.other_sets(0, 3));
/// assert!(partition_vec.other_sets(1, 2));
/// assert!(!partition_vec.other_sets(1, 3));
/// assert!(partition_vec.other_sets(2, 3));
/// # }
/// ```
#[inline]
pub fn other_sets(&self, first_index: usize, second_index: usize) -> bool {
self.find(first_index) != self.find(second_index)
}
/// Will remove `index` from its set while leaving the other members in it.
///
/// After this `index` will be the only element of its set.
/// This won't change the `PartitionVec<T>` if `index` is already the only element.
/// This method will be executed in `O(m)` time where `m` is the size of the set of `index`.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![
/// () => 'a',
/// () => 'a',
/// () => 'a',
/// () => 'b',
/// ];
///
/// // 0, 1, and 2 share a set.
/// assert!(partition_vec.len_of_set(0) == 3);
/// assert!(partition_vec.len_of_set(1) == 3);
/// assert!(partition_vec.len_of_set(2) == 3);
/// assert!(partition_vec.len_of_set(3) == 1);
///
/// partition_vec.make_singleton(2);
///
/// // Now 2 has its own set and 1, and 2 still share a set.
/// assert!(partition_vec.len_of_set(0) == 2);
/// assert!(partition_vec.len_of_set(1) == 2);
/// assert!(partition_vec.len_of_set(2) == 1);
/// assert!(partition_vec.len_of_set(3) == 1);
/// # }
/// ```
pub fn make_singleton(&mut self, index: usize) {
let mut current = self.meta[index].link();
if current != index {
// We make this the new root.
let root = current;
self.meta[root].set_rank(1);
// All parents except for the last are updated.
while self.meta[current].link() != index {
self.meta[current].set_parent(root);
current = self.meta[current].link();
}
// We change the last parent and link.
self.meta[current].set_parent(root);
self.meta[current].set_link(root);
}
self.meta[index] = Metadata::new(index);
}
/// Returns `true` if `index` is the only element of its set.
///
/// This will be done in `O(1)` time.
///
/// # Panics
///
/// If `index` is out of bounds.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![(); 4];
///
/// partition_vec.union(1, 3);
///
/// assert!(partition_vec.is_singleton(0));
/// assert!(!partition_vec.is_singleton(1));
/// assert!(partition_vec.is_singleton(2));
/// assert!(!partition_vec.is_singleton(3));
/// # }
/// ```
#[inline]
pub fn is_singleton(&self, index: usize) -> bool {
self.meta[index].link() == index
}
/// Returns the amount of elements in the set that `index` belongs to.
///
/// This will be done in `O(m)` time where `m` is the size of the set that `index` belongs to.
///
/// # Panics
///
/// If `index` is out of bounds.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![true; 3];
///
/// assert!(partition_vec.len_of_set(0) == 1);
/// assert!(partition_vec.len_of_set(1) == 1);
/// assert!(partition_vec.len_of_set(2) == 1);
///
/// partition_vec.union(0, 2);
///
/// assert!(partition_vec.len_of_set(0) == 2);
/// assert!(partition_vec.len_of_set(1) == 1);
/// assert!(partition_vec.len_of_set(2) == 2);
/// # }
/// ```
pub fn len_of_set(&self, index: usize) -> usize {
let mut current = self.meta[index].link();
let mut count = 1;
while current != index {
current = self.meta[current].link();
count += 1;
}
count
}
/// Returns the amount of sets in the `PartitionVec<T>`.
///
/// This method will be executed in `O(n α(n))` where `α` is the inverse Ackermann function.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let partition_vec = partition_vec![
/// 8 => 0,
/// 3 => 1,
/// 4 => 0,
/// 3 => 1,
/// 7 => 2,
/// ];
///
/// assert!(partition_vec.amount_of_sets() == 3);
/// # }
/// ```
pub fn amount_of_sets(&self) -> usize {
let mut done = bit_vec![false; self.len()];
let mut count = 0;
for i in 0 .. self.len() {
if !done.get(self.find(i)).unwrap() {
done.set(self.find(i), true);
count += 1;
}
}
count
}
/// Gives the representative of the set that `index` belongs to.
///
/// This method will be executed in `O(α(n))` time where `α` is the inverse
/// Ackermann function. Each index of a set
/// will give the same value. To see if two indexes point to values in
/// the same subset compare the results of `find`.
///
/// This method is private to keep the representative of the set an implementation
/// detail, this gives greater freedom to change the representative of the set.
///
/// # Panics
///
/// If `index` is out of bounds.
fn find(&self, index: usize) -> usize {
// If the node is its own parent we have found the root.
if self.meta[index].parent() == index {
index
} else {
// This method is recursive so each parent on the way to the root is updated.
let root = self.find(self.meta[index].parent());
// We update the parent to the root for a lower tree.
self.meta[index].set_parent(root);
root
}
}
/// Gives the representative of the set that `index` belongs to.
///
/// This method is slightly faster than `find` but still `O(a(n))` time.
/// This method wont update the parents while finding the representative and should
/// only be used if the parents will be updated immediately afterwards.
///
/// # Panics
///
/// If `index` is out of bounds.
#[inline]
fn find_final(&self, mut index: usize) -> usize {
while index != self.meta[index].parent() {
index = self.meta[index].parent();
}
index
}
/// Returns the number of elements the `PartitionVec<T>` can hold without reallocating.
///
/// # Examples
///
/// ```
/// let mut partition_vec = partitions::PartitionVec::with_capacity(6);
///
/// for i in 0 .. 6 {
/// partition_vec.push(i);
/// }
///
/// assert!(partition_vec.capacity() == 6);
///
/// partition_vec.push(6);
///
/// assert!(partition_vec.capacity() >= 7);
/// ```
#[inline]
pub fn capacity(&self) -> usize {
usize::min(self.data.capacity(), self.meta.capacity())
}
/// Appends an element to the back of the `PartitionVec<T>`.
///
/// This element has its own disjoint set.
///
/// # Panics
///
/// Panics if the number of elements in the `PartitionVec<T>` overflows a `usize`.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![
/// 'a' => 0,
/// 'b' => 0,
/// 'c' => 1,
/// 'd' => 2,
/// ];
///
/// partition_vec.push('e');
///
/// assert!(partition_vec.amount_of_sets() == 4);
/// assert!(partition_vec[4] == 'e');
/// # }
/// ```
#[inline]
pub fn push(&mut self, elem: T) {
let old_len = self.len();
self.data.push(elem);
self.meta.push(Metadata::new(old_len));
}
/// Removes the last element returns it, or `None` if it is empty.
///
/// This will be done in `O(m)` time where `m` is the size of the set
/// that `index` belongs to.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![
/// 'a' => 0,
/// 'b' => 0,
/// 'c' => 1,
/// 'd' => 0,
/// ];
///
/// assert!(partition_vec.pop() == Some('d'));
///
/// assert!(partition_vec.amount_of_sets() == 2);
/// assert!(partition_vec.len() == 3);
/// # }
/// ```
pub fn pop(&mut self) -> Option<T> {
let last_index = self.data.len() - 1;
self.make_singleton(last_index);
self.meta.pop()?;
Some(self.data.pop().unwrap())
}
/// Inserts an element at `index` within the `PartitionVec<T>`, shifting all
/// elements after it to the right.
///
/// This will take `O(n)` time.
///
/// # Panics
///
/// Panics if `index` is out of bounds.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![
/// 0 => 0,
/// 1 => 1,
/// 2 => 0,
/// 3 => 2,
/// ];
///
/// partition_vec.insert(2, -1);
///
/// assert!(partition_vec[2] == -1);
/// assert!(partition_vec.amount_of_sets() == 4);
/// # }
/// ```
pub fn insert(&mut self, index: usize, elem: T) {
// We update the parents and links above the new value.
for i in 0 .. self.meta.len() {
let parent = self.meta[i].parent();
if parent >= index {
self.meta[i].set_parent(parent + 1);
}
let link = self.meta[i].link();
if link >= index {
self.meta[i].set_link(link + 1);
}
}
self.data.insert(index, elem);
self.meta.insert(index, Metadata::new(index));
}
/// Removes and returns the element at position index within the `PartitionVec<T>`,
/// shifting all elements after it to the left.
///
/// This will take `O(n + m)` time where `m` is the size of the set that `index` belongs to.
///
/// # Panics
///
/// Panics if `index` is out of bounds.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![
/// 0 => 0,
/// 1 => 1,
/// 2 => 0,
/// 3 => 2,
/// ];
///
/// assert!(partition_vec.remove(2) == 2);
///
/// assert!(partition_vec[2] == 3);
/// assert!(partition_vec.amount_of_sets() == 3);
/// # }
/// ```
pub fn remove(&mut self, index: usize) -> T {
self.make_singleton(index);
self.meta.remove(index);
// We lower all values that point above the index.
for i in 0 .. self.meta.len() {
let parent = self.meta[i].parent();
if parent > index {
self.meta[i].set_parent(parent - 1);
}
let link = self.meta[i].link();
if link > index {
self.meta[i].set_link(link - 1);
}
}
self.data.remove(index)
}
/// Moves all the elements of `other` into `self`, leaving `other` empty.
///
/// # Panics
///
/// Panics if the number of elements in de `PartitionVec<T>` overflows a `usize`.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut first = partition_vec![
/// 'a' => 0,
/// 'b' => 1,
/// 'c' => 1,
/// ];
/// let mut second = partition_vec![
/// 'a' => 0,
/// 'b' => 0,
/// 'c' => 1,
/// ];
///
/// first.append(&mut second);
///
/// assert!(first.len() == 6);
/// assert!(second.len() == 0);
///
/// assert!(first.amount_of_sets() == 4);
/// assert!(second.amount_of_sets() == 0);
/// # }
/// ```
pub fn append(&mut self, other: &mut Self) {
let old_len = self.len();
self.data.append(&mut other.data);
self.meta.extend(other.meta.drain(..).map(|meta| {
let old = meta.parent();
meta.set_parent(old + old_len);
let old = meta.link();
meta.set_link(old + old_len);
meta
}));
}
/// Reserves capacity for at least `additional` more elements to be
/// inserted in the given `PartitionVec<T>`.
/// The collection may reserve more space to avoid frequent reallocation's.
/// After calling `reserve`, capacity will be greater than
/// or equal to `self.len() + additional`.
/// Does nothing if capacity is already sufficient.
///
/// # Panics
///
/// Panics if the new capacity overflows a `usize`.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![1];
/// partition_vec.reserve(10);
/// assert!(partition_vec.capacity() >= 11);
/// # }
/// ```
#[inline]
pub fn reserve(&mut self, additional: usize) {
self.data.reserve(additional);
self.meta.reserve(additional);
}
/// Reserves the minimum capacity for exactly `additional` more elements to be
/// inserted in the given `PartitionVec<T>`.
/// After calling `reserve_exact`, capacity will be greater than or
/// equal to `self.len() + additional`.
/// Does nothing if the capacity is already sufficient.
///
/// Note that the allocator may give the collection more space than it requests.
/// Therefore capacity can not be relied upon to be precisely minimal.
/// Prefer `reserve` if future insertions are expected.
///
/// # Panics
///
/// Panics if the new capacity overflows a `usize`.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![1];
/// partition_vec.reserve_exact(10);
/// assert!(partition_vec.capacity() >= 11);
/// # }
/// ```
#[inline]
pub fn reserve_exact(&mut self, additional: usize) {
self.data.reserve_exact(additional);
self.meta.reserve_exact(additional);
}
/// Shrinks the capacity of the `PartitionVec<T>` as much as possible.
///
/// It will drop down as close as possible to the length but the allocator
/// may still inform the `PartitionVec<T>` that there is space for a few more
/// elements.
///
/// # Examples
///
/// ```
/// let mut partition_vec = partitions::PartitionVec::with_capacity(10);
///
/// partition_vec.extend([1, 2, 3].iter().cloned());
///
/// assert!(partition_vec.capacity() == 10);
///
/// partition_vec.shrink_to_fit();
///
/// assert!(partition_vec.capacity() >= 3);
/// ```
#[inline]
pub fn shrink_to_fit(&mut self) {
self.data.shrink_to_fit();
self.meta.shrink_to_fit();
}
/// Shortens the `PartitionVec<T>`, keeping the first `new_len` elements and
/// dropping the rest.
///
/// If `new_len` is greater than or equal to the collections current length,
/// this has no effect.
///
/// Note that this method has no effect on the allocated capacity of the
/// collection.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![
/// 'a' => 0,
/// 'b' => 1,
/// 'c' => 0,
/// 'd' => 1,
/// 'e' => 2,
/// ];
///
/// partition_vec.truncate(3);
/// assert!(partition_vec.len() == 3);
/// assert!(partition_vec.capacity() == 5);
/// assert!(partition_vec.len_of_set(0) == 2);
/// assert!(partition_vec.len_of_set(1) == 1);
/// assert!(partition_vec.len_of_set(2) == 2);
/// # }
/// ```
pub fn truncate(&mut self, new_len: usize) {
if new_len >= self.len() {
return
}
for i in 0 .. new_len {
let parent = self.meta[i].parent();
let mut current = self.meta[i].link();
if parent >= new_len {
// We make `i` the new root.
self.meta[i].set_parent(i);
self.meta[i].set_rank(1);
let mut previous = i;
// The last index we saw before we went out of the new bounds.
let mut index_before_oob = if current >= new_len {
Some(previous)
} else {
None
};
while current != i {
if current >= new_len {
// If the current is above the new length we update this value if needed.
if index_before_oob.is_none() {
index_before_oob = Some(previous);
}
} else if let Some(index) = index_before_oob {
// If we are back in bounds for the first time we update the link.
self.meta[index].set_link(current);
index_before_oob = None;
}
self.meta[current].set_parent(i);
previous = current;
current = self.meta[current].link();
}
if let Some(index) = index_before_oob {
self.meta[index].set_link(i);
}
} else if current >= new_len {
while current >= new_len {
current = self.meta[current].link();
}
self.meta[i].set_link(current);
}
}
self.data.truncate(new_len);
self.meta.truncate(new_len);
}
/// Resizes the `PartitionVec<T>` in-place so that `len` is equal to `new_len`.
///
/// If `new_len` is greater than `len`, the collection is extended by the
/// difference, with each additional slot filled with `value`.
/// If `new_len` is less than `len`, the collection is simply truncated.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![4, 9];
/// partition_vec.resize(4, 0);
/// assert!(partition_vec.as_slice() == &[4, 9, 0, 0]);
///
/// let mut partition_vec = partition_vec![
/// 4 => 0,
/// 1 => 1,
/// 3 => 5,
/// 1 => 1,
/// 1 => 3,
/// ];
/// partition_vec.resize(2, 0);
/// assert!(partition_vec.as_slice() == &[4, 1]);
/// # }
/// ```
#[inline]
pub fn resize(&mut self, new_len: usize, value: T) where T: Clone {
let len = self.len();
match Ord::cmp(&new_len, &len) {
Ordering::Less => self.truncate(new_len),
Ordering::Equal => {},
Ordering::Greater => {
self.data.append(&mut vec![value; new_len - len]);
self.meta.extend((len .. new_len).map(Metadata::new));
}
}
}
/// Clears the `PartitionVec<T>`, removing all values.
///
/// Note that this method has no effect on the allocated capacity of the collection.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![2, 3, 4];
/// assert!(!partition_vec.is_empty());
/// partition_vec.clear();
/// assert!(partition_vec.is_empty());
/// # }
/// ```
#[inline]
pub fn clear(&mut self) {
self.data.clear();
self.meta.clear();
}
/// Returns `true` if the partition_vec contains no elements.
///
/// # Examples
///
/// ```
/// let mut partition_vec = partitions::PartitionVec::new();
/// assert!(partition_vec.is_empty());
///
/// partition_vec.push(1);
/// assert!(!partition_vec.is_empty());
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// Converts the `PartitionVec<T>` into `Vec<T>`.
///
/// This will not take the sets of the `PartitionVec<T>` in to account at all.
///
/// # Examples
///
/// ```
/// let mut partition_vec = partitions::PartitionVec::with_capacity(10);
/// partition_vec.extend([1, 2, 3].iter().cloned());
///
/// assert!(partition_vec.capacity() == 10);
/// let slice = partition_vec.into_boxed_slice();
/// assert!(slice.into_vec().capacity() == 3);
/// ```
#[inline]
pub fn into_vec(self) -> Vec<T> {
self.data
}
/// Converts the `PartitionVec<T>` into `Box<[T]>`.
///
/// Note that this will drop any excess capacity.
/// This will not take the sets of the `PartitionVec<T>` in to account at all.
///
/// # Examples
///
/// ```
/// let mut partition_vec = partitions::PartitionVec::with_capacity(10);
/// partition_vec.extend([1, 2, 3].iter().cloned());
///
/// assert!(partition_vec.capacity() == 10);
/// let slice = partition_vec.into_boxed_slice();
/// assert!(slice.into_vec().capacity() == 3);
/// ```
#[inline]
pub fn into_boxed_slice(self) -> Box<[T]> {
self.data.into_boxed_slice()
}
/// Extracts a slice containing the entire `PartitionVec<T>`.
///
/// Equivalent to `&partition_vec[..]`.
/// This will not take the sets of the `PartitionVec<T>` in to account at all.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// use std::io::{self, Write};
/// let buffer = partition_vec![1, 2, 3, 4, 5];
/// io::sink().write(buffer.as_slice()).unwrap();
/// # }
/// ```
#[inline]
pub fn as_slice(&self) -> & [T] {
self.data.as_slice()
}
/// Extracts a mutable slice containing the entire `PartitionVec<T>`.
///
/// Equivalent to `&mut partition_vec[..]`.
/// This will not take the sets of the `PartitionVec<T>` in to account at all.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// use std::io::{self, Read};
/// let mut buffer = partition_vec![0; 3];
/// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
/// # }
#[inline]
pub fn as_mut_slice(&mut self) -> &mut [T] {
self.data.as_mut_slice()
}
/// Returns an iterator over the elements of the set that `index` belongs to.
///
/// The iterator returned yields pairs `(i, &value)` where `i` is the index of the value and
/// `value` is the value itself.
///
/// The order the elements are returned in is not specified.
///
/// # Panics
///
/// If `index` is out of bounds.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let partition_vec = partition_vec![
/// 'a' => "first set",
/// 'b' => "first set",
/// 'c' => "second set",
/// 'd' => "second set",
/// ];
///
/// let mut done = [0, 0, 0, 0];
/// for (index, value) in partition_vec.set(0) {
/// assert!(*value == 'a' || *value == 'b');
/// done[index] += 1;
/// }
/// for (index, value) in partition_vec.set(1) {
/// assert!(*value == 'a' || *value == 'b');
/// done[index] += 1;
/// }
/// for (index, value) in partition_vec.set(2) {
/// assert!(*value == 'c' || *value == 'd');
/// done[index] += 1;
/// }
/// // We visited the first set twice and the second set once.
/// assert!(done == [2, 2, 1, 1]);
/// # }
/// ```
#[inline]
pub fn set(&self, index: usize) -> Set<T> {
let root = self.find_final(index);
self.meta[root].set_rank(1);
Set {
partition_vec: self,
current: Some(root),
root,
}
}
/// Returns an iterator over the elements of the set that `index` belongs to.
///
/// The iterator returned yields pairs `(i, &mut value)` where `i` is the index of the value and
/// `value` is the value itself.
///
/// The order the elements are returned in is not specified.
///
/// # Panics
///
/// If `index` is out of bounds.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![
/// 0 => 'a',
/// 0 => 'b',
/// 0 => 'b',
/// 0 => 'c',
/// ];
///
/// assert!(partition_vec.as_slice() == &[0, 0, 0, 0]);
/// for (index, value) in partition_vec.set_mut(2) {
/// assert!(index == 1 || index == 2);
/// *value += 1;
/// }
/// assert!(partition_vec.as_slice() == &[0, 1, 1, 0]);
/// # }
/// ```
#[inline]
pub fn set_mut(&mut self, index: usize) -> SetMut<T> {
let root = self.find_final(index);
self.meta[root].set_rank(1);
SetMut {
partition_vec: self,
current: Some(root),
root,
}
}
/// Returns an iterator over all sets of the `PartitionVec<T>`.
///
/// The iterator returned yields `Set` iterators.
/// These `Set` iterators yield pairs `(i, &value)` where `i` is the index of
/// the value and `value` is the value itself.
///
/// The sets are returned in order by there first member.
/// The order the elements of a `Set` are returned in is not specified.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let partition_vec = partition_vec![
/// 0 => 'a',
/// 0 => 'a',
/// 2 => 'b',
/// 2 => 'b',
/// 4 => 'c',
/// 4 => 'c',
/// ];
///
/// for set in partition_vec.all_sets() {
/// let mut count = 0;
/// for (index, value) in set {
/// assert!(index == *value || index == *value + 1);
/// count += 1;
/// }
/// assert!(count == 2);
/// }
/// # }
/// ```
#[inline]
pub fn all_sets(&self) -> AllSets<T> {
let len = self.len();
AllSets {
partition_vec: self,
done: bit_vec![false; len],
range: 0 .. len,
}
}
/// Returns an iterator over all sets of the `PartitionVec<T>`.
///
/// The iterator returned yields `SetMut` iterators.
/// These `SetMut` iterators yield pairs `(i, &mut value)` where `i` is the index of
/// the value and `value` is the value itself.
///
/// The sets are returned in order by there first member.
/// The order the elements of a `SetMut` are returned in is not specified.
///
/// # Examples
///
/// ```
/// # #[macro_use]
/// # extern crate partitions;
/// #
/// # fn main() {
/// let mut partition_vec = partition_vec![
/// 0 => 'a',
/// 0 => 'b',
/// 0 => 'a',
/// 0 => 'b',
/// 0 => 'c',
/// 0 => 'c',
/// ];
///
/// assert!(partition_vec.as_slice() == &[0, 0, 0, 0, 0, 0]);
///
/// for (set_number, set_mut) in partition_vec.all_sets_mut().enumerate() {
/// for (index, value) in set_mut {
/// assert!(index < 6);
/// *value = set_number;
/// }
/// }
///
/// assert!(partition_vec.as_slice() == &[0, 1, 0, 1, 2, 2]);
/// # }
/// ```
#[inline]
pub fn all_sets_mut(&mut self) -> AllSetsMut<T> {
let len = self.len();
AllSetsMut {
partition_vec: self,
done: bit_vec![false; len],
range: 0 .. len,
}
}
/// This method is used by the `partition_vec!` macro.
#[doc(hidden)]
#[inline]
pub fn from_elem(elem: T, len: usize) -> Self where T: Clone {
Self {
data: vec![elem; len],
meta: (0 .. len).map(Metadata::new).collect(),
}
}
}
impl<T> Default for PartitionVec<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> std::fmt::Debug for PartitionVec<T> where T: std::fmt::Debug {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
// We map the roots to `usize` names.
let mut map = std::collections::HashMap::with_capacity(self.len());
let mut builder = formatter.debug_list();
let mut names = 0;
for i in 0 .. self.len() {
let root = self.find(i);
let name = if let Some(&name) = map.get(&root) {
// If we already have a name we use it.
name
} else {
// If we don't we make a new name.
let new_name = names;
map.insert(root, new_name);
names += 1;
new_name
};
builder.entry(&format_args!("{:?} => {}", self.data[i], name));
}
builder.finish()
}
}
impl<T> PartialEq for PartitionVec<T> where T: PartialEq {
fn eq(&self, other: &Self) -> bool {
if self.len() != other.len() {
return false
}
// We map the roots of self to the roots of other.
let mut map = std::collections::HashMap::with_capacity(self.len());
for i in 0 .. self.len() {
if self.data[i] != other.data[i] {
return false
}
let self_root = self.find(i);
let other_root = other.find(i);
if let Some(&root) = map.get(&self_root) {
// If we have seen this root we check if we have the same map.
if root != other_root {
return false
}
} else {
// If we have not seen this root we add the relation to the map.
map.insert(self_root, other_root);
}
}
true
}
}
impl<T> Eq for PartitionVec<T> where T: Eq {}
impl<T, I> ops::Index<I> for PartitionVec<T> where I: std::slice::SliceIndex<[T]> {
type Output = I::Output;
#[inline]
fn index(&self, index: I) -> &I::Output {
(**self).index(index)
}
}
impl<T, I> ops::IndexMut<I> for PartitionVec<T> where I: std::slice::SliceIndex<[T]> {
#[inline]
fn index_mut(&mut self, index: I) -> &mut I::Output {
(**self).index_mut(index)
}
}
impl<T> ops::Deref for PartitionVec<T> {
type Target = [T];
fn deref(&self) -> &[T] {
&self.data
}
}
impl<T> ops::DerefMut for PartitionVec<T> {
fn deref_mut(&mut self) -> &mut [T] {
&mut self.data
}
}
impl<T> From<Vec<T>> for PartitionVec<T> {
fn from(vec: Vec<T>) -> Self {
let len = vec.len();
Self {
data: vec,
meta: (0 .. len).map(Metadata::new).collect(),
}
}
}
impl<T> FromIterator<T> for PartitionVec<T> {
fn from_iter<I>(iter: I) -> Self where I: IntoIterator<Item = T> {
let data = Vec::from_iter(iter);
let len = data.len();
Self {
data,
meta: (0 .. len).map(Metadata::new).collect(),
}
}
}
impl<'a, T> FromIterator<&'a T> for PartitionVec<T> where T: Copy + 'a {
fn from_iter<I>(iter: I) -> Self where I: IntoIterator<Item = &'a T> {
Self::from_iter(iter.into_iter().cloned())
}
}
#[cfg(feature = "rayon")]
impl<T> FromParallelIterator<T> for PartitionVec<T> where T: Send {
fn from_par_iter<I>(par_iter: I) -> Self where I: IntoParallelIterator<Item = T> {
let par_iter = par_iter.into_par_iter();
let mut partition = if let Some(len) = par_iter.opt_len() {
Self::with_capacity(len)
} else {
Self::new()
};
partition.par_extend(par_iter);
partition
}
}
#[cfg(feature = "rayon")]
impl<'a, T> FromParallelIterator<&'a T> for PartitionVec<T> where T: Copy+ Send + Sync + 'a {
fn from_par_iter<I>(par_iter: I) -> Self where I: IntoParallelIterator<Item = &'a T> {
Self::from_par_iter(par_iter.into_par_iter().cloned())
}
}
impl<T> IntoIterator for PartitionVec<T> {
type Item = T;
type IntoIter = std::vec::IntoIter<T>;
fn into_iter(self) -> std::vec::IntoIter<T> {
self.data.into_iter()
}
}
impl<'a, T> IntoIterator for &'a PartitionVec<T> {
type Item = &'a T;
type IntoIter = std::slice::Iter<'a, T>;
fn into_iter(self) -> std::slice::Iter<'a, T> {
self.data.iter()
}
}
impl<'a, T> IntoIterator for &'a mut PartitionVec<T> {
type Item = &'a mut T;
type IntoIter = std::slice::IterMut<'a, T>;
fn into_iter(self) -> std::slice::IterMut<'a, T> {
self.data.iter_mut()
}
}
#[cfg(feature = "rayon")]
impl<T> IntoParallelIterator for PartitionVec<T> where T: Send {
type Item = T;
type Iter = rayon::vec::IntoIter<T>;
fn into_par_iter(self) -> Self::Iter {
self.data.into_par_iter()
}
}
#[cfg(feature = "rayon")]
impl<'a, T> IntoParallelIterator for &'a PartitionVec<T> where T: Send + Sync {
type Item = &'a T;
type Iter = rayon::slice::Iter<'a, T>;
fn into_par_iter(self) -> Self::Iter {
self.data.par_iter()
}
}
#[cfg(feature = "rayon")]
impl<'a, T> IntoParallelIterator for &'a mut PartitionVec<T> where T: Send + Sync {
type Item = &'a mut T;
type Iter = rayon::slice::IterMut<'a, T>;
fn into_par_iter(self) -> Self::Iter {
self.data.par_iter_mut()
}
}
impl<T> Extend<T> for PartitionVec<T> {
fn extend<I>(&mut self, iter: I) where I: IntoIterator<Item = T> {
let len = self.len();
self.data.extend(iter);
let new_len = self.data.len();
self.meta.extend((len .. new_len).map(Metadata::new));
}
}
impl<'a, T> Extend<&'a T> for PartitionVec<T> where T: Copy + 'a {
fn extend<I>(&mut self, iter: I) where I: IntoIterator<Item = &'a T> {
let len = self.len();
self.data.extend(iter);
let new_len = self.data.len();
self.meta.extend((len .. new_len).map(Metadata::new));
}
}
#[cfg(feature = "rayon")]
impl<T> ParallelExtend<T> for PartitionVec<T> where T: Send {
fn par_extend<I>(&mut self, par_iter: I) where I: IntoParallelIterator<Item = T>
{
let par_iter = par_iter.into_par_iter();
self.data.par_extend(par_iter);
self.meta.par_extend((0 .. self.data.len()).into_par_iter().map(Metadata::new));
}
}
#[cfg(feature = "rayon")]
impl<'a, T> ParallelExtend<&'a T> for PartitionVec<T> where T: Copy + Send + Sync + 'a {
fn par_extend<I>(&mut self, par_iter: I) where I: IntoParallelIterator<Item = &'a T> {
self.par_extend(par_iter.into_par_iter().cloned())
}
}
/// An iterator over a set in a `PartitionVec<T>`.
///
/// This struct is created by the [`set`] method on [`PartitionVec<T>`].
/// See its documentation for more.
///
/// [`set`]: struct.PartitionVec.html#method.set
/// [`PartitionVec<T>`]: struct.PartitionVec.html
#[derive(Clone, Debug)]
pub struct Set<'a, T: 'a> {
partition_vec: &'a PartitionVec<T>,
current: Option<usize>,
root: usize,
}
impl<'a, T> Iterator for Set<'a, T> {
type Item = (usize, &'a T);
fn next(&mut self) -> Option<(usize, &'a T)> {
let current = self.current?;
self.partition_vec.meta[current].set_parent(self.root);
let next = self.partition_vec.meta[current].link();
// We started at the root.
self.current = if next == self.root {
None
} else {
Some(next)
};
Some((current, &self.partition_vec.data[current]))
}
}
impl<'a, T> FusedIterator for Set<'a, T> {}
/// An iterator over a set in a `PartitionVec<T>` that allows mutating elements.
///
/// This struct is created by the [`set_mut`] method on [`PartitionVec<T>`].
/// See its documentation for more.
///
/// [`set_mut`]: struct.PartitionVec.html#method.set_mut
/// [`PartitionVec<T>`]: struct.PartitionVec.html
#[derive(Debug)]
pub struct SetMut<'a, T: 'a> {
partition_vec: &'a mut PartitionVec<T>,
current: Option<usize>,
root: usize,
}
impl<'a, T> Iterator for SetMut<'a, T> {
type Item = (usize, &'a mut T);
fn next(&mut self) -> Option<(usize, &'a mut T)> {
let current = self.current?;
self.partition_vec.meta[current].set_parent(self.root);
let next = self.partition_vec.meta[current].link();
// We started at the root.
self.current = if next == self.root {
None
} else {
Some(next)
};
// This iterator wont give a reference to this value again so it is safe to extend
// the lifetime of the mutable reference.
unsafe {
Some((current, extend_mut(&mut self.partition_vec.data[current])))
}
}
}
impl<'a, T> FusedIterator for SetMut<'a, T> {}
/// An iterator over all sets in a `PartitionVec<T>`.
///
/// This struct is created by the [`all_sets`] method on [`PartitionVec<T>`].
/// See its documentation for more.
///
/// [`all_sets`]: struct.PartitionVec.html#method.all_sets
/// [`PartitionVec<T>`]: struct.PartitionVec.html
#[derive(Clone, Debug)]
pub struct AllSets<'a, T: 'a> {
partition_vec: &'a PartitionVec<T>,
done: bit_vec::BitVec,
range: ops::Range<usize>,
}
impl<'a, T> Iterator for AllSets<'a, T> {
type Item = Set<'a, T>;
fn next(&mut self) -> Option<Set<'a, T>> {
// We keep going until we find a set we have not returned yet.
loop {
let index = self.range.next()?;
let root = self.partition_vec.find_final(index);
// If we have not returned this set yet.
if !self.done.get(root).unwrap() {
self.done.set(root, true);
return Some(Set {
partition_vec: self.partition_vec,
current: Some(root),
root,
})
}
}
}
}
impl<'a, T> DoubleEndedIterator for AllSets<'a, T> {
fn next_back(&mut self) -> Option<Set<'a, T>> {
// We keep going until we find a set we have not returned yet.
loop {
let index = self.range.next_back()?;
let root = self.partition_vec.find_final(index);
// If we have not returned this set yet.
if !self.done.get(root).unwrap() {
self.done.set(root, true);
return Some(Set {
partition_vec: self.partition_vec,
current: Some(root),
root,
})
}
}
}
}
impl<'a, T> FusedIterator for AllSets<'a, T> {}
/// An iterator over all sets in a `PartitionVec<T>` that allows mutating elements.
///
/// This struct is created by the [`all_sets`] method on [`PartitionVec<T>`].
/// See its documentation for more.
///
/// [`all_sets`]: struct.PartitionVec.html#method.all_sets
/// [`PartitionVec<T>`]: struct.PartitionVec.html
#[derive(Debug)]
pub struct AllSetsMut<'a, T: 'a> {
partition_vec: &'a mut PartitionVec<T>,
done: bit_vec::BitVec,
range: ops::Range<usize>,
}
impl<'a, T> Iterator for AllSetsMut<'a, T> {
type Item = SetMut<'a, T>;
fn next(&mut self) -> Option<SetMut<'a, T>> {
// We keep going until we find a set we have not returned yet.
loop {
let index = self.range.next()?;
let root = self.partition_vec.find_final(index);
// If we have not returned this set yet.
if !self.done.get(root).unwrap() {
self.done.set(root, true);
// This is safe because we will not return this set again.
unsafe { return Some(SetMut {
partition_vec: extend_mut(self).partition_vec,
current: Some(root),
root,
})}
}
}
}
}
impl<'a, T> DoubleEndedIterator for AllSetsMut<'a, T> {
fn next_back(&mut self) -> Option<SetMut<'a, T>> {
// We keep going until we find a set we have not returned yet.
loop {
let index = self.range.next_back()?;
let root = self.partition_vec.find_final(index);
// If we have not returned this set yet.
if !self.done.get(root).unwrap() {
self.done.set(root, true);
// This is safe because we will not return this set again.
unsafe { return Some(SetMut {
partition_vec: extend_mut(self).partition_vec,
current: Some(root),
root,
})}
}
}
}
}
impl<'a, T> FusedIterator for AllSetsMut<'a, T> {}