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
//! Counter counts recurrent elements of iterables. It is based on [the Python
//! implementation](https://docs.python.org/3/library/collections.html#collections.Counter).
//!
//! The struct [`Counter`](struct.Counter.html) is the entry-point type for this module.
//!
//! # Math Underpinnings
//!
//! Mathematically, a `Counter` implements a hash-based version of a [multiset],
//! or bag. This is simply an extension of the notion of a set to the idea that
//! we care not only about whether an entity exists within the set, but the number
//! of occurrences within the set. Normal set operations such as intersection,
//! union, etc. are of course still supported.
//!
//! [multiset]: https://en.wikipedia.org/wiki/Set_(abstract_data_type)#Multiset
//!
//! # Examples
//!
//! ## Just count an iterable
//!
//! ```rust
//! use counter::Counter;
//! let char_counts = "barefoot".chars().collect::<Counter<_>>();
//! let counts_counts = char_counts.values().collect::<Counter<_>>();
//! ```
//!
//! ## Update a count
//!
//! ```rust
//! # use counter::Counter;
//! let mut counts = "aaa".chars().collect::<Counter<_>>();
//! counts[&'a'] += 1;
//! counts[&'b'] += 1;
//! ```
//!
//! ```rust
//! # use counter::Counter;
//! let mut counts = "able babble table babble rabble table able fable scrabble"
//! .split_whitespace().collect::<Counter<_>>();
//! // add or subtract an iterable of the same type
//! counts += "cain and abel fable table cable".split_whitespace();
//! // or add or subtract from another Counter of the same type
//! let other_counts = "scrabble cabbie fable babble"
//! .split_whitespace().collect::<Counter<_>>();
//! let difference = counts - other_counts;
//! ```
//!
//! Extend a `Counter` with another `Counter`:
//! ```rust
//! # use counter::Counter;
//! # use std::collections::HashMap;
//! let mut counter = "abbccc".chars().collect::<Counter<_>>();
//! let another = "bccddd".chars().collect::<Counter<_>>();
//! counter.extend(&another);
//! let expect = [('a', 1), ('b', 3), ('c', 5), ('d', 3)].iter()
//! .cloned().collect::<HashMap<_, _>>();
//! assert_eq!(counter.into_map(), expect);
//! ```
//! ## Get items with keys
//!
//! ```rust
//! # use counter::Counter;
//! let counts = "aaa".chars().collect::<Counter<_>>();
//! assert_eq!(counts[&'a'], 3);
//! assert_eq!(counts[&'b'], 0);
//! ```
//!
//! ## Get the most common items
//!
//! [`most_common_ordered()`] uses the natural ordering of keys which are [`Ord`].
//!
//! [`most_common_ordered()`]: Counter::most_common_ordered
//! [`Ord`]: https://doc.rust-lang.org/stable/std/cmp/trait.Ord.html
//!
//! ```rust
//! # use counter::Counter;
//! let by_common = "eaddbbccc".chars().collect::<Counter<_>>().most_common_ordered();
//! let expected = vec![('c', 3), ('b', 2), ('d', 2), ('a', 1), ('e', 1)];
//! assert!(by_common == expected);
//! ```
//!
//! [`k_most_common_ordered()`] takes an argument `k` of type `usize` and returns the top `k` most
//! common items. This is functionally equivalent to calling `most_common_ordered()` and then
//! truncating the result to length `k`. However, if `k` is smaller than the length of the counter
//! then `k_most_common_ordered()` can be more efficient, often much more so.
//!
//! ```rust
//! # use counter::Counter;
//! let by_common = "eaddbbccc".chars().collect::<Counter<_>>().k_most_common_ordered(2);
//! let expected = vec![('c', 3), ('b', 2)];
//! assert!(by_common == expected);
//! ```
//!
//! [`k_most_common_ordered()`]: Counter::k_most_common_ordered
//! [`most_common_ordered()`]: Counter::most_common_ordered
//!
//! ## Get the most common items using your own ordering
//!
//! For example, here we break ties reverse alphabetically.
//!
//! ```rust
//! # use counter::Counter;
//! let counter = "eaddbbccc".chars().collect::<Counter<_>>();
//! let by_common = counter.most_common_tiebreaker(|&a, &b| b.cmp(&a));
//! let expected = vec![('c', 3), ('d', 2), ('b', 2), ('e', 1), ('a', 1)];
//! assert!(by_common == expected);
//! ```
//!
//! ## Test counters against another
//!
//! Counters are multi-sets and so can be sub- or supersets of each other.
//!
//! A counter is a _subset_ of another if for all its elements, the other
//! counter has an equal or higher count. Test for this with [`is_subset()`]:
//!
//! ```rust
//! # use counter::Counter;
//! let counter = "aaabb".chars().collect::<Counter<_>>();
//! let superset = "aaabbbc".chars().collect::<Counter<_>>();
//! let not_a_superset = "aaae".chars().collect::<Counter<_>>();
//! assert!(counter.is_subset(&superset));
//! assert!(!counter.is_subset(¬_a_superset));
//! ```
//!
//! Testing for a _superset_ is the inverse, [`is_superset()`] is true if the counter can contain another counter in its entirety:
//!
//! ```rust
//! # use counter::Counter;
//! let counter = "aaabbbc".chars().collect::<Counter<_>>();
//! let subset = "aabbb".chars().collect::<Counter<_>>();
//! let not_a_subset = "aaae".chars().collect::<Counter<_>>();
//! assert!(counter.is_superset(&subset));
//! assert!(!counter.is_superset(¬_a_subset));
//! ```
//!
//! These relationships continue to work when [using a _signed_ integer type for the counter][signed]: all values in the subset must be equal or lower to the values in the superset. Negative
//! values are interpreted as 'missing' those values, and the subset would need to miss those
//! same elements, or be short more, to still be a subset:
//!
//! ```rust
//! # use counter::Counter;
//! let mut subset = "aaabb".chars().collect::<Counter<_, i8>>();
//! subset.insert('e', -2); // short 2 'e's
//! subset.insert('f', -1); // and 1 'f'
//! let mut superset = "aaaabbb".chars().collect::<Counter<_, i8>>();
//! superset.insert('e', -1); // short 1 'e'
//! assert!(subset.is_subset(&superset));
//! assert!(superset.is_superset(&subset));
//! ```
//!
//! [`is_subset()`]: Counter::is_subset
//! [`is_superset()`]: Counter::is_superset
//! [signed]: #use-your-own-type-for-the-count
//!
//! ## Counter intersection and union
//!
//! You can intersect two counters, giving you the minimal counts of their
//! combined elements using the [`&` bitwise and operator][BitAnd], and produce
//! their union with the maximum counts using [`|` bitwise or][BitOr]:
//!
//! ```rust
//! # use counter::Counter;
//! let a = "aaabb".chars().collect::<Counter<_>>();
//! let b = "aabbbbe".chars().collect::<Counter<_>>();
//!
//! let intersection = a & b;
//! let expected_intersection = "aabb".chars().collect::<Counter<_>>();
//! assert_eq!(intersection, expected_intersection);
//!
//! let c = "aaabb".chars().collect::<Counter<_>>();
//! let d = "aabbbbe".chars().collect::<Counter<_>>();
//!
//! let union = c | d;
//! let expected_union = "aaabbbbe".chars().collect::<Counter<_>>();
//! assert_eq!(union, expected_union)
//! ```
//!
//! The in-place [`&=`] and [`|=`] operations are also supported.
//!
//! [BitAnd]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
//! [BitOr]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
//! [`&=`]: https://doc.rust-lang.org/std/ops/trait.BitAndAssign.html
//! [`|=`]: https://doc.rust-lang.org/std/ops/trait.BitOrAssign.html
//!
//! ## Treat it like a `HashMap`
//!
//! `Counter<T, N>` implements [`Deref`]`<Target=HashMap<T, N>>` and
//! [`DerefMut`]`<Target=HashMap<T, N>>`, which means that you can perform any operations
//! on it which are valid for a [`HashMap`].
//!
//! [`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html
//! [`Deref`]: https://doc.rust-lang.org/stable/std/ops/trait.Deref.html
//! [`DerefMut`]: https://doc.rust-lang.org/stable/std/ops/trait.DerefMut.html
//!
//! ```rust
//! # use counter::Counter;
//! let mut counter = "aa-bb-cc".chars().collect::<Counter<_>>();
//! counter.remove(&'-');
//! assert!(counter == "aabbcc".chars().collect::<Counter<_>>());
//! ```
//!
//! Note that `Counter<T, N>` itself implements [`Index`]. `Counter::index` returns a reference to
//! a [`Zero::zero`] value for missing keys.
//!
//! [`Index`]: https://doc.rust-lang.org/stable/std/ops/trait.Index.html
//! [`Zero::zero`]: https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero
//!
//! ```rust
//! # use counter::Counter;
//! let counter = "aaa".chars().collect::<Counter<_>>();
//! assert_eq!(counter[&'b'], 0);
//! // panics
//! // assert_eq!((*counter)[&'b'], 0);
//! ```
//!
//! # Advanced Usage
//!
//! ## Count any iterable which is `Hash + Eq`
//!
//! You can't use the `most_common*` functions unless `T` is also [`Clone`], but simple counting
//! works fine on a minimal data type.
//!
//! [`Clone`]: https://doc.rust-lang.org/stable/std/clone/trait.Clone.html
//!
//! ```rust
//! # use counter::Counter;
//! #[derive(Debug, Hash, PartialEq, Eq)]
//! struct Inty {
//! i: usize,
//! }
//!
//! impl Inty {
//! pub fn new(i: usize) -> Inty {
//! Inty { i: i }
//! }
//! }
//!
//! // <https://en.wikipedia.org/wiki/867-5309/Jenny>
//! let intys = vec![
//! Inty::new(8),
//! Inty::new(0),
//! Inty::new(0),
//! Inty::new(8),
//! Inty::new(6),
//! Inty::new(7),
//! Inty::new(5),
//! Inty::new(3),
//! Inty::new(0),
//! Inty::new(9),
//! ];
//!
//! let inty_counts = intys.iter().collect::<Counter<_>>();
//! println!("{:?}", inty_counts);
//! // {Inty { i: 8 }: 2, Inty { i: 0 }: 3, Inty { i: 9 }: 1, Inty { i: 3 }: 1,
//! // Inty { i: 7 }: 1, Inty { i: 6 }: 1, Inty { i: 5 }: 1}
//! assert!(inty_counts.get(&Inty { i: 8 }) == Some(&2));
//! assert!(inty_counts.get(&Inty { i: 0 }) == Some(&3));
//! assert!(inty_counts.get(&Inty { i: 6 }) == Some(&1));
//! ```
//!
//! ## Use your own type for the count
//!
//! Sometimes [`usize`] just isn't enough. If you find yourself overflowing your
//! machine's native size, you can use your own type. Here, we use an [`i8`], but
//! you can use most numeric types, including bignums, as necessary.
//!
//! [`usize`]: https://doc.rust-lang.org/stable/std/primitive.usize.html
//! [`i8`]: https://doc.rust-lang.org/stable/std/primitive.i8.html
//!
//! ```rust
//! # use counter::Counter;
//! # use std::collections::HashMap;
//! let counter: Counter<_, i8> = "abbccc".chars().collect();
//! let expected: HashMap<char, i8> = [('a', 1), ('b', 2), ('c', 3)].iter().cloned().collect();
//! assert!(counter.into_map() == expected);
//! ```
use num_traits::{One, Zero};
use std::borrow::Borrow;
use std::collections::{BinaryHeap, HashMap};
use std::hash::Hash;
use std::iter;
use std::ops::{
Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, Deref, DerefMut, Index, IndexMut,
Sub, SubAssign,
};
type CounterMap<T, N> = HashMap<T, N>;
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Counter<T: Hash + Eq, N = usize> {
map: CounterMap<T, N>,
// necessary for `Index::index` since we cannot declare generic `static` variables.
zero: N,
}
impl<T, N> Counter<T, N>
where
T: Hash + Eq,
{
/// Consumes this counter and returns a [`HashMap`] mapping the items to the counts.
///
/// [`HashMap`]: https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html
pub fn into_map(self) -> HashMap<T, N> {
self.map
}
/// Returns the sum of the counts.
///
/// Use [`len`] to get the number of elements in the counter and use `total` to get the sum of
/// their counts.
///
/// [`len`]: struct.Counter.html#method.len
///
/// # Examples
///
/// ```
/// # use counter::Counter;
/// let counter = Counter::init("abracadabra".chars());
/// assert_eq!(counter.total::<usize>(), 11);
/// assert_eq!(counter.len(), 5);
/// ```
pub fn total<'a, S>(&'a self) -> S
where
S: iter::Sum<&'a N>,
{
self.map.values().sum()
}
}
impl<T, N> Counter<T, N>
where
T: Hash + Eq,
N: Zero,
{
/// Create a new, empty `Counter`
pub fn new() -> Counter<T, N> {
Counter {
map: HashMap::new(),
zero: N::zero(),
}
}
}
impl<T, N> Counter<T, N>
where
T: Hash + Eq,
N: AddAssign + Zero + One,
{
/// Create a new `Counter` initialized with the given iterable.
pub fn init<I>(iterable: I) -> Counter<T, N>
where
I: IntoIterator<Item = T>,
{
let mut counter = Counter::new();
counter.update(iterable);
counter
}
/// Add the counts of the elements from the given iterable to this counter.
pub fn update<I>(&mut self, iterable: I)
where
I: IntoIterator<Item = T>,
{
for item in iterable {
let entry = self.map.entry(item).or_insert_with(N::zero);
*entry += N::one();
}
}
}
impl<T, N> Counter<T, N>
where
T: Hash + Eq,
N: PartialOrd + SubAssign + Zero + One,
{
/// Remove the counts of the elements from the given iterable to this counter.
///
/// Non-positive counts are automatically removed.
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let mut counter = "abbccc".chars().collect::<Counter<_>>();
/// counter.subtract("abba".chars());
/// let expect = [('c', 3)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(counter.into_map(), expect);
/// ```
pub fn subtract<I>(&mut self, iterable: I)
where
I: IntoIterator<Item = T>,
{
for item in iterable {
let mut remove = false;
if let Some(entry) = self.map.get_mut(&item) {
if *entry > N::zero() {
*entry -= N::one();
}
remove = *entry == N::zero();
}
if remove {
self.map.remove(&item);
}
}
}
}
impl<T, N> Counter<T, N>
where
T: Hash + Eq + Clone,
N: Clone + Ord,
{
/// Create a vector of `(elem, frequency)` pairs, sorted most to least common.
///
/// ```rust
/// # use counter::Counter;
/// let mc = "pappaopolo".chars().collect::<Counter<_>>().most_common();
/// let expected = vec![('p', 4), ('o', 3), ('a', 2), ('l', 1)];
/// assert_eq!(mc, expected);
/// ```
///
/// Note that the ordering of duplicates is unstable.
pub fn most_common(&self) -> Vec<(T, N)> {
use std::cmp::Ordering;
self.most_common_tiebreaker(|_a, _b| Ordering::Equal)
}
/// Create a vector of `(elem, frequency)` pairs, sorted most to least common.
///
/// In the event that two keys have an equal frequency, use the supplied ordering function
/// to further arrange the results.
///
/// For example, we can sort reverse-alphabetically:
///
/// ```rust
/// # use counter::Counter;
/// let counter = "eaddbbccc".chars().collect::<Counter<_>>();
/// let by_common = counter.most_common_tiebreaker(|&a, &b| b.cmp(&a));
/// let expected = vec![('c', 3), ('d', 2), ('b', 2), ('e', 1), ('a', 1)];
/// assert_eq!(by_common, expected);
/// ```
pub fn most_common_tiebreaker<F>(&self, mut tiebreaker: F) -> Vec<(T, N)>
where
F: FnMut(&T, &T) -> ::std::cmp::Ordering,
{
let mut items = self
.map
.iter()
.map(|(key, count)| (key.clone(), count.clone()))
.collect::<Vec<_>>();
items.sort_unstable_by(|(a_item, a_count), (b_item, b_count)| {
b_count
.cmp(a_count)
.then_with(|| tiebreaker(a_item, b_item))
});
items
}
}
impl<T, N> Counter<T, N>
where
T: Hash + Eq + Clone + Ord,
N: Clone + Ord,
{
/// Create a vector of `(elem, frequency)` pairs, sorted most to least common.
///
/// In the event that two keys have an equal frequency, use the natural ordering of the keys
/// to further sort the results.
///
/// # Examples
///
/// ```rust
/// # use counter::Counter;
/// let mc = "abracadabra".chars().collect::<Counter<_>>().most_common_ordered();
/// let expect = vec![('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)];
/// assert_eq!(mc, expect);
/// ```
///
/// # Time complexity
///
/// *O*(*n* \* log *n*), where *n* is the number of items in the counter. If all you want is
/// the top *k* items and *k* < *n* then it can be more efficient to use
/// [`k_most_common_ordered`].
///
/// [`k_most_common_ordered`]: Counter::k_most_common_ordered
pub fn most_common_ordered(&self) -> Vec<(T, N)> {
self.most_common_tiebreaker(Ord::cmp)
}
/// Returns the `k` most common items in decreasing order of their counts.
///
/// The returned vector is the same as would be obtained by calling `most_common_ordered` and
/// then truncating the result to length `k`. In particular, items with the same count are
/// sorted in *increasing* order of their keys. Further, if `k` is greater than the length of
/// the counter then the returned vector will have length equal to that of the counter, not
/// `k`.
///
/// # Examples
///
/// ```rust
/// # use counter::Counter;
/// let counter: Counter<_> = "abracadabra".chars().collect();
/// let top3 = counter.k_most_common_ordered(3);
/// assert_eq!(top3, vec![('a', 5), ('b', 2), ('r', 2)]);
/// ```
///
/// # Time complexity
///
/// This method can be much more efficient than [`most_common_ordered`] when *k* is much
/// smaller than the length of the counter *n*. When *k* = 1 the algorithm is equivalent
/// to finding the minimum (or maximum) of *n* items, which requires *n* \- 1 comparisons. For
/// a fixed value of *k* > 1, the number of comparisons scales with *n* as *n* \+ *O*(log *n*)
/// and the number of swaps scales as *O*(log *n*). As *k* approaches *n*, this algorithm
/// approaches a heapsort of the *n* items, which has complexity *O*(*n* \* log *n*).
///
/// For values of *k* close to *n* the sorting algorithm used by [`most_common_ordered`] will
/// generally be faster than the heapsort used by this method by a small constant factor.
/// Exactly where the crossover point occurs will depend on several factors. For small *k*
/// choose this method. If *k* is a substantial fraction of *n*, it may be that
/// [`most_common_ordered`] is faster. If performance matters in your application then it may
/// be worth experimenting to see which of the two methods is faster.
///
/// [`most_common_ordered`]: Counter::most_common_ordered
pub fn k_most_common_ordered(&self, k: usize) -> Vec<(T, N)> {
use std::cmp::Reverse;
if k == 0 {
return vec![];
}
// The quicksort implementation used by `most_common_ordered()` is generally faster than
// the heapsort used below when sorting the entire counter.
if k >= self.map.len() {
return self.most_common_ordered();
}
// Clone the counts as we iterate over the map to eliminate an extra indirection when
// comparing counts. This will be an improvement in the typical case where `N: Copy`.
// Defer cloning the keys until we have selected the top `k` items so that we clone only
// `k` keys instead of all of them.
let mut items = self.map.iter().map(|(t, n)| (Reverse(n.clone()), t));
// Step 1. Make a heap out of the first `k` items; this makes O(k) comparisons.
let mut heap: BinaryHeap<_> = items.by_ref().take(k).collect();
// Step 2. Successively compare each of the remaining `n - k` items to the top of the heap,
// replacing the root (and subsequently sifting down) whenever the item is less than the
// root. This takes at most n - k + k * (1 + log2(k)) * (H(n) - H(k)) comparisons, where
// H(i) is the ith [harmonic number](https://en.wikipedia.org/wiki/Harmonic_number). For
// fixed `k`, this scales as *n* + *O*(log(*n*)).
items.for_each(|item| {
// If `items` is nonempty at this point then we know the heap contains `k > 0`
// elements.
let mut root = heap.peek_mut().expect("the heap is empty");
if *root > item {
*root = item;
}
});
// Step 3. Sort the items in the heap with the second phases of heapsort. The number of
// comparisons is 2 * k * log2(k) + O(k).
heap.into_sorted_vec()
.into_iter()
.map(|(Reverse(n), t)| (t.clone(), n))
.collect()
}
}
impl<T, N> Default for Counter<T, N>
where
T: Hash + Eq,
N: Default,
{
fn default() -> Self {
Self {
map: Default::default(),
zero: Default::default(),
}
}
}
impl<T, N> AddAssign for Counter<T, N>
where
T: Hash + Eq,
N: Zero + AddAssign,
{
/// Add another counter to this counter.
///
/// `c += d;` -> `c[x] += d[x]` for all `x`
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let mut c = "aaab".chars().collect::<Counter<_>>();
/// let d = "abb".chars().collect::<Counter<_>>();
///
/// c += d;
///
/// let expect = [('a', 4), ('b', 3)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(c.into_map(), expect);
/// ```
fn add_assign(&mut self, rhs: Self) {
for (key, value) in rhs.map {
let entry = self.map.entry(key).or_insert_with(N::zero);
*entry += value;
}
}
}
impl<T, N> Add for Counter<T, N>
where
T: Clone + Hash + Eq,
N: AddAssign + Zero,
{
type Output = Counter<T, N>;
/// Add two counters together.
///
/// `out = c + d;` -> `out[x] == c[x] + d[x]` for all `x`
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let c = "aaab".chars().collect::<Counter<_>>();
/// let d = "abb".chars().collect::<Counter<_>>();
///
/// let e = c + d;
///
/// let expect = [('a', 4), ('b', 3)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(e.into_map(), expect);
/// ```
fn add(mut self, rhs: Counter<T, N>) -> Self::Output {
self += rhs;
self
}
}
impl<T, N> SubAssign for Counter<T, N>
where
T: Hash + Eq,
N: PartialOrd + PartialEq + SubAssign + Zero,
{
/// Subtract (keeping only positive values).
///
/// `c -= d;` -> `c[x] -= d[x]` for all `x`,
/// keeping only items with a value greater than [`N::zero()`].
///
/// [`N::zero()`]:
/// https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let mut c = "aaab".chars().collect::<Counter<_>>();
/// let d = "abb".chars().collect::<Counter<_>>();
///
/// c -= d;
///
/// let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(c.into_map(), expect);
/// ```
fn sub_assign(&mut self, rhs: Self) {
for (key, value) in rhs.map {
let mut remove = false;
if let Some(entry) = self.map.get_mut(&key) {
if *entry >= value {
*entry -= value;
} else {
remove = true;
}
if *entry == N::zero() {
remove = true;
}
}
if remove {
self.map.remove(&key);
}
}
}
}
impl<T, N> Sub for Counter<T, N>
where
T: Hash + Eq,
N: PartialOrd + PartialEq + SubAssign + Zero,
{
type Output = Counter<T, N>;
/// Subtract (keeping only positive values).
///
/// `out = c - d;` -> `out[x] == c[x] - d[x]` for all `x`,
/// keeping only items with a value greater than [`N::zero()`].
///
/// [`N::zero()`]:
/// https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let c = "aaab".chars().collect::<Counter<_>>();
/// let d = "abb".chars().collect::<Counter<_>>();
///
/// let e = c - d;
///
/// let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(e.into_map(), expect);
/// ```
fn sub(mut self, rhs: Counter<T, N>) -> Self::Output {
self -= rhs;
self
}
}
impl<T, N> Counter<T, N>
where
T: Hash + Eq,
N: PartialOrd + Zero,
{
/// Test whether this counter is a superset of another counter.
/// This is true if for all elements in this counter and the other,
/// the count in this counter is greater than or equal to the count in the other.
///
/// `c.is_superset(&d);` -> `c.iter().all(|(x, n)| n >= d[x]) && d.iter().all(|(x, n)| c[x] >= n)`
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let c = "aaabbc".chars().collect::<Counter<_>>();
/// let mut d = "abb".chars().collect::<Counter<_>>();
///
/// assert!(c.is_superset(&d));
/// d[&'e'] = 1;
/// assert!(!c.is_superset(&d));
/// ```
pub fn is_superset(&self, other: &Self) -> bool {
// need to test keys from both counters, because if N is signed, counts in `self`
// could be < 0 for elements missing in `other`. For the unsigned case, only elements
// from `other` would need to be tested.
self.keys()
.chain(other.keys())
.all(|key| self[key] >= other[key])
}
/// Test whether this counter is a subset of another counter.
/// This is true if for all elements in this counter and the other,
/// the count in this counter is less than or equal to the count in the other.
///
/// `c.is_subset(&d);` -> `c.iter().all(|(x, n)| n <= d[x]) && d.iter().all(|(x, n)| c[x] <= n)`
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let mut c = "abb".chars().collect::<Counter<_>>();
/// let mut d = "aaabbc".chars().collect::<Counter<_>>();
///
/// assert!(c.is_subset(&d));
/// c[&'e'] = 1;
/// assert!(!c.is_subset(&d));
/// ```
pub fn is_subset(&self, other: &Self) -> bool {
// need to test keys from both counters, because if N is signed, counts in `other`
// could be < 0 for elements missing in `self`. For the unsigned case, only elements
// from `self` would need to be tested.
self.keys()
.chain(other.keys())
.all(|key| self[key] <= other[key])
}
}
impl<T, N> BitAnd for Counter<T, N>
where
T: Hash + Eq,
N: Ord + Zero,
{
type Output = Counter<T, N>;
/// Returns the intersection of `self` and `rhs` as a new `Counter`.
///
/// `out = c & d;` -> `out[x] == min(c[x], d[x])`
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let c = "aaab".chars().collect::<Counter<_>>();
/// let d = "abb".chars().collect::<Counter<_>>();
///
/// let e = c & d;
///
/// let expect = [('a', 1), ('b', 1)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(e.into_map(), expect);
/// ```
fn bitand(self, mut rhs: Counter<T, N>) -> Self::Output {
use std::cmp::min;
let mut counter = Counter::new();
for (key, lhs_count) in self.map {
if let Some(rhs_count) = rhs.remove(&key) {
let count = min(lhs_count, rhs_count);
counter.map.insert(key, count);
}
}
counter
}
}
impl<T, N> BitAndAssign for Counter<T, N>
where
T: Hash + Eq,
N: Ord + Zero,
{
/// Updates `self` with the intersection of `self` and `rhs`
///
/// `c &= d;` -> `c[x] == min(c[x], d[x])`
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let mut c = "aaab".chars().collect::<Counter<_>>();
/// let d = "abb".chars().collect::<Counter<_>>();
///
/// c &= d;
///
/// let expect = [('a', 1), ('b', 1)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(c.into_map(), expect);
/// ```
fn bitand_assign(&mut self, mut rhs: Counter<T, N>) {
for (key, rhs_count) in rhs.drain() {
if rhs_count < self[&key] {
self.map.insert(key, rhs_count);
}
}
}
}
impl<T, N> BitOr for Counter<T, N>
where
T: Hash + Eq,
N: Ord + Zero,
{
type Output = Counter<T, N>;
/// Returns the union of `self` and `rhs` as a new `Counter`.
///
/// `out = c | d;` -> `out[x] == max(c[x], d[x])`
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let c = "aaab".chars().collect::<Counter<_>>();
/// let d = "abb".chars().collect::<Counter<_>>();
///
/// let e = c | d;
///
/// let expect = [('a', 3), ('b', 2)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(e.into_map(), expect);
/// ```
fn bitor(mut self, rhs: Counter<T, N>) -> Self::Output {
for (key, rhs_value) in rhs.map {
let entry = self.map.entry(key).or_insert_with(N::zero);
// We want to update the value of the now occupied entry in `self` with the maximum of
// its current value and `rhs_value`. If that max is `rhs_value`, we can just update
// the value of the entry. If the max is the current value, we do nothing. Note that
// `Ord::max()` returns the second argument (here `rhs_value`) if its two arguments are
// equal, justifying the use of the weak inequality below instead of a strict
// inequality.
//
// Doing it this way with an inequality instead of actually using `std::cmp::max()`
// lets us avoid trying (and failing) to move the non-copy value out of the entry in
// order to pass it as an argument to `std::cmp::max()`, while still holding a mutable
// reference to the value slot in the entry.
//
// And while using the inequality seemingly only requires the bound `N: PartialOrd`, we
// nevertheless prefer to require `Ord` as though we were using `std::cmp::max()`
// because the semantics of `BitOr` for `Counter` really do not make sense if there are
// possibly non-comparable values of type `N`.
if rhs_value >= *entry {
*entry = rhs_value;
}
}
self
}
}
impl<T, N> BitOrAssign for Counter<T, N>
where
T: Hash + Eq,
N: Ord + Zero,
{
/// Updates `self` with the union of `self` and `rhs`
///
/// `c |= d;` -> `c[x] == max(c[x], d[x])`
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let mut c = "aaab".chars().collect::<Counter<_>>();
/// let d = "abb".chars().collect::<Counter<_>>();
///
/// c |= d;
///
/// let expect = [('a', 3), ('b', 2)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(c.into_map(), expect);
/// ```
fn bitor_assign(&mut self, mut rhs: Counter<T, N>) {
for (key, rhs_count) in rhs.drain() {
if rhs_count > self[&key] {
self.map.insert(key, rhs_count);
}
}
}
}
impl<T, N> Deref for Counter<T, N>
where
T: Hash + Eq,
{
type Target = CounterMap<T, N>;
fn deref(&self) -> &CounterMap<T, N> {
&self.map
}
}
impl<T, N> DerefMut for Counter<T, N>
where
T: Hash + Eq,
{
fn deref_mut(&mut self) -> &mut CounterMap<T, N> {
&mut self.map
}
}
impl<'a, T, N> IntoIterator for &'a Counter<T, N>
where
T: Hash + Eq,
{
type Item = (&'a T, &'a N);
type IntoIter = std::collections::hash_map::Iter<'a, T, N>;
fn into_iter(self) -> Self::IntoIter {
self.map.iter()
}
}
impl<T, N> IntoIterator for Counter<T, N>
where
T: Hash + Eq,
{
type Item = (T, N);
type IntoIter = std::collections::hash_map::IntoIter<T, N>;
/// Consumes the `Counter` to produce an iterator that owns the values it returns.
///
/// # Examples
/// ```rust
/// # use counter::Counter;
///
/// let counter: Counter<_> = "aaab".chars().collect();
///
/// let vec: Vec<_> = counter.into_iter().collect();
///
/// for (item, count) in &vec {
/// if item == &'a' {
/// assert_eq!(count, &3);
/// }
/// if item == &'b' {
/// assert_eq!(count, &1);
/// }
/// }
/// ```
fn into_iter(self) -> Self::IntoIter {
self.map.into_iter()
}
}
impl<'a, T, N> IntoIterator for &'a mut Counter<T, N>
where
T: Hash + Eq,
{
type Item = (&'a T, &'a mut N);
type IntoIter = std::collections::hash_map::IterMut<'a, T, N>;
/// Creates an iterator that provides mutable references to the counts, but keeps the keys immutable.
///
/// # Examples
/// ```rust
/// # use counter::Counter;
///
/// let mut counter: Counter<_> = "aaab".chars().collect();
///
/// for (item, count) in &mut counter {
/// if *item == 'a' {
/// // 'a' is so great it counts as 2
/// *count *= 2;
/// }
/// }
///
/// assert_eq!(counter[&'a'], 6);
/// assert_eq!(counter[&'b'], 1);
/// ```
fn into_iter(self) -> Self::IntoIter {
self.map.iter_mut()
}
}
impl<T, Q, N> Index<&'_ Q> for Counter<T, N>
where
T: Hash + Eq + Borrow<Q>,
Q: Hash + Eq,
N: Zero,
{
type Output = N;
/// Index in immutable contexts.
///
/// Returns a reference to a [`zero`] value for missing keys.
///
/// [`zero`]:
/// https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero
///
/// ```
/// # use counter::Counter;
/// let counter = Counter::<_>::init("aabbcc".chars());
/// assert_eq!(counter[&'a'], 2);
/// assert_eq!(counter[&'b'], 2);
/// assert_eq!(counter[&'c'], 2);
/// assert_eq!(counter[&'d'], 0);
/// ```
///
/// Note that the [`zero`] is a struct field but not one of the values of the inner
/// [`HashMap`]. This method does not modify any existing value.
///
/// [`zero`]:
/// https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero
/// [`HashMap`]: https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html
///
/// ```
/// # use counter::Counter;
/// let counter = Counter::<_>::init("".chars());
/// assert_eq!(counter[&'a'], 0);
/// assert_eq!(counter.get(&'a'), None); // as `Deref<Target = HashMap<_, _>>`
/// ```
fn index(&self, key: &'_ Q) -> &N {
self.map.get(key).unwrap_or(&self.zero)
}
}
impl<T, Q, N> IndexMut<&'_ Q> for Counter<T, N>
where
T: Hash + Eq + Borrow<Q>,
Q: Hash + Eq + ToOwned<Owned = T>,
N: Zero,
{
/// Index in mutable contexts.
///
/// If the given key is not present, creates a new entry and initializes it with a [`zero`]
/// value.
///
/// [`zero`]:
/// https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero
///
/// ```
/// # use counter::Counter;
/// let mut counter = Counter::<_>::init("aabbcc".chars());
/// counter[&'c'] += 1;
/// counter[&'d'] += 1;
/// assert_eq!(counter[&'c'], 3);
/// assert_eq!(counter[&'d'], 1);
/// ```
///
/// Unlike `Index::index`, the returned mutable reference to the [`zero`] is actually one of the
/// values of the inner [`HashMap`].
///
/// [`zero`]:
/// https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero
/// [`HashMap`]: https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html
///
/// ```
/// # use counter::Counter;
/// let mut counter = Counter::<_>::init("".chars());
/// assert_eq!(counter.get(&'a'), None); // as `Deref<Target = HashMap<_, _>>`
/// let _ = &mut counter[&'a'];
/// assert_eq!(counter.get(&'a'), Some(&0));
/// ```
fn index_mut(&mut self, key: &'_ Q) -> &mut N {
self.map.entry(key.to_owned()).or_insert_with(N::zero)
}
}
impl<I, T, N> AddAssign<I> for Counter<T, N>
where
I: IntoIterator<Item = T>,
T: Hash + Eq,
N: AddAssign + Zero + One,
{
/// Directly add the counts of the elements of `I` to `self`.
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let mut counter = Counter::init("abbccc".chars());
///
/// counter += "aeeeee".chars();
/// let expected: HashMap<char, usize> = [('a', 2), ('b', 2), ('c', 3), ('e', 5)]
/// .iter().cloned().collect();
/// assert_eq!(counter.into_map(), expected);
/// ```
fn add_assign(&mut self, rhs: I) {
self.update(rhs);
}
}
impl<I, T, N> Add<I> for Counter<T, N>
where
I: IntoIterator<Item = T>,
T: Hash + Eq,
N: AddAssign + Zero + One,
{
type Output = Self;
/// Consume `self` producing a `Counter` like `self` updated with the counts of
/// the elements of `I`.
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let counter = Counter::init("abbccc".chars());
///
/// let new_counter = counter + "aeeeee".chars();
/// let expected: HashMap<char, usize> = [('a', 2), ('b', 2), ('c', 3), ('e', 5)]
/// .iter().cloned().collect();
/// assert_eq!(new_counter.into_map(), expected);
/// ```
fn add(mut self, rhs: I) -> Self::Output {
self.update(rhs);
self
}
}
impl<I, T, N> SubAssign<I> for Counter<T, N>
where
I: IntoIterator<Item = T>,
T: Hash + Eq,
N: PartialOrd + SubAssign + Zero + One,
{
/// Directly subtract the counts of the elements of `I` from `self`,
/// keeping only items with a value greater than [`N::zero()`].
///
/// [`N::zero()`]:
/// https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let mut c = "aaab".chars().collect::<Counter<_>>();
/// c -= "abb".chars();
///
/// let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(c.into_map(), expect);
/// ```
fn sub_assign(&mut self, rhs: I) {
self.subtract(rhs);
}
}
impl<I, T, N> Sub<I> for Counter<T, N>
where
I: IntoIterator<Item = T>,
T: Hash + Eq,
N: PartialOrd + SubAssign + Zero + One,
{
type Output = Self;
/// Consume `self` producing a `Counter` like `self` with the counts of the
/// elements of `I` subtracted, keeping only positive values.
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let c = "aaab".chars().collect::<Counter<_>>();
/// let e = c - "abb".chars();
///
/// let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(e.into_map(), expect);
/// ```
fn sub(mut self, rhs: I) -> Self::Output {
self.subtract(rhs);
self
}
}
impl<T, N> iter::FromIterator<T> for Counter<T, N>
where
T: Hash + Eq,
N: AddAssign + Zero + One,
{
/// Produce a `Counter` from an iterator of items. This is called automatically
/// by [`Iterator::collect()`].
///
/// [`Iterator::collect()`]:
/// https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.collect
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let counter = "abbccc".chars().collect::<Counter<_>>();
/// let expect = [('a', 1), ('b', 2), ('c', 3)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(counter.into_map(), expect);
/// ```
///
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Counter::<T, N>::init(iter)
}
}
impl<T, N> iter::FromIterator<(T, N)> for Counter<T, N>
where
T: Hash + Eq,
N: AddAssign + Zero,
{
/// Creates a counter from `(item, count)` tuples.
///
/// The counts of duplicate items are summed.
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let counter = [('a', 1), ('b', 2), ('c', 3), ('a', 4)].iter()
/// .cloned().collect::<Counter<_>>();
/// let expect = [('a', 5), ('b', 2), ('c', 3)].iter()
/// .cloned().collect::<HashMap<_, _>>();
/// assert_eq!(counter.into_map(), expect);
/// ```
fn from_iter<I: IntoIterator<Item = (T, N)>>(iter: I) -> Self {
let mut cnt = Counter::new();
for (item, item_count) in iter {
let entry = cnt.map.entry(item).or_insert_with(N::zero);
*entry += item_count;
}
cnt
}
}
impl<T, N> Extend<T> for Counter<T, N>
where
T: Hash + Eq,
N: AddAssign + Zero + One,
{
/// Extend a `Counter` with an iterator of items.
///
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let mut counter = "abbccc".chars().collect::<Counter<_>>();
/// counter.extend("bccddd".chars());
/// let expect = [('a', 1), ('b', 3), ('c', 5), ('d', 3)].iter().cloned().collect::<HashMap<_, _>>();
/// assert_eq!(counter.into_map(), expect);
/// ```
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
self.update(iter);
}
}
impl<T, N> Extend<(T, N)> for Counter<T, N>
where
T: Hash + Eq,
N: AddAssign + Zero,
{
/// Extend a counter with `(item, count)` tuples.
///
/// The counts of duplicate items are summed.
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let mut counter = "abbccc".chars().collect::<Counter<_>>();
/// counter.extend([('a', 1), ('b', 2), ('c', 3), ('a', 4)].iter().cloned());
/// let expect = [('a', 6), ('b', 4), ('c', 6)].iter()
/// .cloned().collect::<HashMap<_, _>>();
/// assert_eq!(counter.into_map(), expect);
/// ```
fn extend<I: IntoIterator<Item = (T, N)>>(&mut self, iter: I) {
for (item, item_count) in iter {
let entry = self.map.entry(item).or_insert_with(N::zero);
*entry += item_count;
}
}
}
impl<'a, T: 'a, N: 'a> Extend<(&'a T, &'a N)> for Counter<T, N>
where
T: Hash + Eq + Clone,
N: AddAssign + Zero + Clone,
{
/// Extend a counter with `(item, count)` tuples.
///
/// You can extend a `Counter` with another `Counter`:
/// ```rust
/// # use counter::Counter;
/// # use std::collections::HashMap;
/// let mut counter = "abbccc".chars().collect::<Counter<_>>();
/// let another = "bccddd".chars().collect::<Counter<_>>();
/// counter.extend(&another);
/// let expect = [('a', 1), ('b', 3), ('c', 5), ('d', 3)].iter()
/// .cloned().collect::<HashMap<_, _>>();
/// assert_eq!(counter.into_map(), expect);
/// ```
fn extend<I: IntoIterator<Item = (&'a T, &'a N)>>(&mut self, iter: I) {
for (item, item_count) in iter {
let entry = self.map.entry(item.clone()).or_insert_with(N::zero);
*entry += item_count.clone();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use maplit::hashmap;
use rand::Rng;
use std::collections::HashMap;
#[test]
fn test_creation() {
let _: Counter<usize> = Counter::new();
let initializer = &[1];
let counter = Counter::init(initializer);
let mut expected = HashMap::new();
static ONE: usize = 1;
expected.insert(&ONE, 1);
assert!(counter.map == expected);
}
#[test]
fn test_update() {
let mut counter = Counter::init("abbccc".chars());
let expected = hashmap! {
'a' => 1,
'b' => 2,
'c' => 3,
};
assert!(counter.map == expected);
counter.update("aeeeee".chars());
let expected = hashmap! {
'a' => 2,
'b' => 2,
'c' => 3,
'e' => 5,
};
assert!(counter.map == expected);
}
#[test]
fn test_add_update_iterable() {
let mut counter = Counter::init("abbccc".chars());
let expected = hashmap! {
'a' => 1,
'b' => 2,
'c' => 3,
};
assert!(counter.map == expected);
counter += "aeeeee".chars();
let expected = hashmap! {
'a' => 2,
'b' => 2,
'c' => 3,
'e' => 5,
};
assert!(counter.map == expected);
}
#[test]
fn test_add_update_counter() {
let mut counter = Counter::init("abbccc".chars());
let expected = hashmap! {
'a' => 1,
'b' => 2,
'c' => 3,
};
assert!(counter.map == expected);
let other = Counter::init("aeeeee".chars());
counter += other;
let expected = hashmap! {
'a' => 2,
'b' => 2,
'c' => 3,
'e' => 5,
};
assert!(counter.map == expected);
}
#[test]
fn test_subtract() {
let mut counter = Counter::init("abbccc".chars());
counter.subtract("bbccddd".chars());
let expected = hashmap! {
'a' => 1,
'c' => 1,
};
assert!(counter.map == expected);
}
#[test]
fn test_sub_update_iterable() {
let mut counter = Counter::init("abbccc".chars());
counter -= "bbccddd".chars();
let expected = hashmap! {
'a' => 1,
'c' => 1,
};
assert!(counter.map == expected);
}
#[test]
fn test_sub_update_counter() {
let mut counter = Counter::init("abbccc".chars());
let other = Counter::init("bbccddd".chars());
counter -= other;
let expected = hashmap! {
'a' => 1,
'c' => 1,
};
assert!(counter.map == expected);
}
#[test]
fn test_composite_add_sub() {
let mut counts = Counter::<_>::init(
"able babble table babble rabble table able fable scrabble".split_whitespace(),
);
// add or subtract an iterable of the same type
counts += "cain and abel fable table cable".split_whitespace();
// or add or subtract from another Counter of the same type
let other_counts = Counter::init("scrabble cabbie fable babble".split_whitespace());
let _diff = counts - other_counts;
}
#[test]
fn test_most_common() {
let counter = Counter::init("abbccc".chars());
let by_common = counter.most_common();
let expected = vec![('c', 3), ('b', 2), ('a', 1)];
assert!(by_common == expected);
}
#[test]
fn test_most_common_tiebreaker() {
let counter = Counter::init("eaddbbccc".chars());
let by_common = counter.most_common_tiebreaker(|&a, &b| a.cmp(&b));
let expected = vec![('c', 3), ('b', 2), ('d', 2), ('a', 1), ('e', 1)];
assert!(by_common == expected);
}
#[test]
fn test_most_common_tiebreaker_reversed() {
let counter = Counter::init("eaddbbccc".chars());
let by_common = counter.most_common_tiebreaker(|&a, &b| b.cmp(&a));
let expected = vec![('c', 3), ('d', 2), ('b', 2), ('e', 1), ('a', 1)];
assert!(by_common == expected);
}
// The main purpose of this test is to see that we can call `Counter::most_common_tiebreaker()`
// with a closure that is `FnMut` but not `Fn`.
#[test]
fn test_most_common_tiebreaker_fn_mut() {
let counter: Counter<_> = Counter::init("abracadabra".chars());
// Count how many times the tiebreaker closure is called.
let mut num_ties = 0;
let sorted = counter.most_common_tiebreaker(|a, b| {
num_ties += 1;
a.cmp(b)
});
let expected = vec![('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)];
assert_eq!(sorted, expected);
// We should have called the tiebreaker twice: once to resolve the tie between `'b'` and
// `'r'` and once to resolve the tie between `'c'` and `'d'`.
assert_eq!(num_ties, 2);
}
#[test]
fn test_most_common_ordered() {
let counter = Counter::init("eaddbbccc".chars());
let by_common = counter.most_common_ordered();
let expected = vec![('c', 3), ('b', 2), ('d', 2), ('a', 1), ('e', 1)];
assert!(by_common == expected);
}
#[test]
fn test_k_most_common_ordered() {
let counter: Counter<_> = "abracadabra".chars().collect();
let all = counter.most_common_ordered();
for k in 0..=counter.len() {
let topk = counter.k_most_common_ordered(k);
assert_eq!(&topk, &all[..k]);
}
}
/// This test is fundamentally the same as `test_k_most_common_ordered`, but it operates on
/// a wider variety of data. In particular, it tests both longer, narrower, and wider
/// distributions of data than the other test does.
#[test]
fn test_k_most_common_ordered_heavy() {
let mut rng = rand::thread_rng();
for container_size in [5, 10, 25, 100, 256] {
for max_value_factor in [0.25, 0.5, 1.0, 1.25, 2.0, 10.0, 100.0] {
let max_value = ((container_size as f64) * max_value_factor) as u32;
let mut values = vec![0; container_size];
for value in values.iter_mut() {
*value = rng.gen_range(0..=max_value);
}
let counter: Counter<_> = values.into_iter().collect();
let all = counter.most_common_ordered();
for k in 0..=counter.len() {
let topk = counter.k_most_common_ordered(k);
assert_eq!(&topk, &all[..k]);
}
}
}
}
#[test]
fn test_total() {
let counter = Counter::init("".chars());
let total: usize = counter.total();
assert_eq!(total, 0);
let counter = Counter::init("eaddbbccc".chars());
let total: usize = counter.total();
assert_eq!(total, 9);
}
#[test]
fn test_add() {
let d = Counter::<_>::init("abbccc".chars());
let e = Counter::<_>::init("bccddd".chars());
let out = d + e;
let expected = Counter::init("abbbcccccddd".chars());
assert!(out == expected);
}
#[test]
fn test_sub() {
let d = Counter::<_>::init("abbccc".chars());
let e = Counter::<_>::init("bccddd".chars());
let out = d - e;
let expected = Counter::init("abc".chars());
assert!(out == expected);
}
#[test]
fn test_intersection() {
let d = Counter::<_>::init("abbccc".chars());
let e = Counter::<_>::init("bccddd".chars());
let out = d & e;
let expected = Counter::init("bcc".chars());
assert!(out == expected);
}
#[test]
fn test_union() {
let d = Counter::<_>::init("abbccc".chars());
let e = Counter::<_>::init("bccddd".chars());
let out = d | e;
let expected = Counter::init("abbcccddd".chars());
assert!(out == expected);
}
#[test]
fn test_delete_key_from_backing_map() {
let mut counter = Counter::<_>::init("aa-bb-cc".chars());
counter.remove(&'-');
assert!(counter == Counter::init("aabbcc".chars()));
}
#[test]
fn test_from_iter_simple() {
let counter = "abbccc".chars().collect::<Counter<_>>();
let expected = hashmap! {
'a' => 1,
'b' => 2,
'c' => 3,
};
assert!(counter.map == expected);
}
#[test]
fn test_from_iter_tuple() {
let items = [('a', 1), ('b', 2), ('c', 3)];
let counter = items.iter().cloned().collect::<Counter<_>>();
let expected: HashMap<char, usize> = items.iter().cloned().collect();
assert_eq!(counter.map, expected);
}
#[test]
fn test_from_iter_tuple_with_duplicates() {
let items = [('a', 1), ('b', 2), ('c', 3)];
let counter = items
.iter()
.cycle()
.take(items.len() * 2)
.cloned()
.collect::<Counter<_>>();
let expected: HashMap<char, usize> = items.iter().map(|(c, n)| (*c, n * 2)).collect();
assert_eq!(counter.map, expected);
}
#[test]
fn test_extend_simple() {
let mut counter = "abbccc".chars().collect::<Counter<_>>();
counter.extend("bccddd".chars());
let expected = hashmap! {
'a' => 1,
'b' => 3,
'c' => 5,
'd' => 3,
};
assert!(counter.map == expected);
}
#[test]
fn test_extend_tuple() {
let mut counter = "bccddd".chars().collect::<Counter<_>>();
let items = [('a', 1), ('b', 2), ('c', 3)];
counter.extend(items.iter().cloned());
let expected = hashmap! {
'a' => 1,
'b' => 3,
'c' => 5,
'd' => 3,
};
assert_eq!(counter.map, expected);
}
#[test]
fn test_extend_tuple_with_duplicates() {
let mut counter = "ccc".chars().collect::<Counter<_>>();
let items = [('a', 1), ('b', 2), ('c', 3)];
counter.extend(items.iter().cycle().take(items.len() * 2 - 1).cloned());
let expected: HashMap<char, usize> = items.iter().map(|(c, n)| (*c, n * 2)).collect();
assert_eq!(counter.map, expected);
}
#[test]
fn test_count_minimal_type() {
#[derive(Debug, Hash, PartialEq, Eq)]
struct Inty {
i: usize,
}
impl Inty {
pub fn new(i: usize) -> Inty {
Inty { i }
}
}
// <https://en.wikipedia.org/wiki/867-5309/Jenny>
let intys = vec![
Inty::new(8),
Inty::new(0),
Inty::new(0),
Inty::new(8),
Inty::new(6),
Inty::new(7),
Inty::new(5),
Inty::new(3),
Inty::new(0),
Inty::new(9),
];
let inty_counts = Counter::init(intys);
// println!("{:?}", inty_counts.map); // test runner blanks this
// {Inty { i: 8 }: 2, Inty { i: 0 }: 3, Inty { i: 9 }: 1, Inty { i: 3 }: 1,
// Inty { i: 7 }: 1, Inty { i: 6 }: 1, Inty { i: 5 }: 1}
assert!(inty_counts.map.get(&Inty { i: 8 }) == Some(&2));
assert!(inty_counts.map.get(&Inty { i: 0 }) == Some(&3));
assert!(inty_counts.map.get(&Inty { i: 6 }) == Some(&1));
}
#[test]
fn test_collect() {
let counter: Counter<_> = "abbccc".chars().collect();
let expected = hashmap! {
'a' => 1,
'b' => 2,
'c' => 3,
};
assert!(counter.map == expected);
}
#[test]
fn test_non_usize_count() {
let counter: Counter<_, i8> = "abbccc".chars().collect();
let expected = hashmap! {
'a' => 1,
'b' => 2,
'c' => 3,
};
assert!(counter.map == expected);
}
#[test]
fn test_superset_non_usize_count() {
let mut a: Counter<_, i8> = "abbcccc".chars().collect();
let mut b: Counter<_, i8> = "abb".chars().collect();
assert!(a.is_superset(&b));
// Negative values are possible, a is no longer a superset
a[&'e'] = -1;
assert!(!a.is_superset(&b));
// Adjust b to make a a superset again
b[&'e'] = -2;
assert!(a.is_superset(&b));
}
#[test]
fn test_subset_non_usize_count() {
let mut a: Counter<_, i8> = "abb".chars().collect();
let mut b: Counter<_, i8> = "abbcccc".chars().collect();
assert!(a.is_subset(&b));
// Negative values are possible; a is no longer a subset
b[&'e'] = -1;
assert!(!a.is_subset(&b));
// Adjust a to make it a subset again
a[&'e'] = -2;
assert!(a.is_subset(&b));
}
}