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
//! # subset-map //! //! ## Summary //! //! `subset-map` is a map like data structure where the keys are combinations //! of elements the `SubsetMap` has been initialized with. //! //! The order of the elements is defined by the position of an element //! within the elements the `SubsetMap` has been initialized with. //! //! `SubsetMap` clones the elements into the subsets. So you should //! consider to only use element types where you would feel good to assign //! them the `Copy` trait. //! //! Lookup is done linearly. Therefore `SubsetMap` should only be used //! with not too big sets of elements. //! //! ### Example //! //! ``` //! use subset_map::*; //! // Initialize the map where the payloads are basically the keys //! let subset_map = SubsetMap::fill(&[1, 2, 3], |x| x.iter().cloned().collect::<Vec<_>>()); //! //! assert_eq!(subset_map.get(&[1]), Some(&vec![1])); //! assert_eq!(subset_map.get(&[2]), Some(&vec![2])); //! assert_eq!(subset_map.get(&[3]), Some(&vec![3])); //! assert_eq!(subset_map.get(&[1, 2]), Some(&vec![1, 2])); //! assert_eq!(subset_map.get(&[2, 3]), Some(&vec![2, 3])); //! assert_eq!(subset_map.get(&[1, 3]), Some(&vec![1, 3])); //! assert_eq!(subset_map.get(&[1, 2, 3]), Some(&vec![1, 2, 3])); //! //! // No internal ordering is performed: //! // The position in the original set is crucial: //! assert_eq!(subset_map.get(&[2,1]), None); //! ``` //! //! ## Features //! //! The `serde` feature allows serialization and deserialization with `serde`. //! //! ## Recent Changes //! //! * 0.3.2 //! * Added more methods to iterate/walk //! * 0.3.1 //! * Added methods to work with payloads //! * 0.3.0 //! * [BREAKING CHANGES]: Changed API to be more consistent //! * 0.2.2 //! * fixed `size` function //! * 0.2.1 //! * Optimized `find` and `lookup` a bit //! * Added `size` finction to return the number of combinations //! * 0.2.0 //! * Renamed MatchQuality to `LookupResult` //! * `LookupResult` also contains the no match case //! * improved documentation //! //! ## License //! //! `subset-map` is distributed under the terms of both the MIT license and the Apache License (Version //! 2.0). //! //! Copyright(2018) Christian Douven //! //! See LICENSE-APACHE and LICENSE-MIT for details. #[cfg(feature = "serde")] #[macro_use] extern crate serde; type Nodes<I, P> = Vec<SubsetMapNode<I, P>>; /// A map like data structure where the keys are subsets made of /// combinations of the original sets. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct SubsetMap<E, P> { nodes: Nodes<E, P>, } impl<E, P> SubsetMap<E, P> where E: Clone, { /// Creates a new instance where the payloads are /// initialized with a closure that is passed the /// current subset of elements. /// /// This function assigns values to those combinations where /// the given closure `init` returns `Some`. /// /// # Example /// /// ``` /// use subset_map::*; /// /// let subset_map = SubsetMap::new(&[1, 2], |x| { /// let sum = x.iter().sum::<i32>(); /// if sum == 1 { /// None /// } else { /// Some(sum) /// } /// }); /// /// assert_eq!(subset_map.get(&[1]), None); /// assert_eq!(subset_map.get(&[2]), Some(&2)); /// assert_eq!(subset_map.get(&[1, 2]), Some(&3)); /// assert_eq!(subset_map.get(&[]), None); /// assert_eq!(subset_map.get(&[2, 1]), None); /// assert_eq!(subset_map.get(&[0]), None); /// assert_eq!(subset_map.get(&[0, 1]), None); /// ``` pub fn new<F>(elements: &[E], mut init: F) -> SubsetMap<E, P> where F: FnMut(&[E]) -> Option<P>, { init_root::<_, _, _, ()>(elements, &mut |elements| Ok(init(elements))).unwrap() } /// Creates a new instance where the payloads are /// initialized with a closure that is passed the /// current subset of elements. /// /// This fuction will assign an element to each subset. /// /// # Example /// /// ``` /// use subset_map::*; /// /// let subset_map = SubsetMap::fill(&[1, 2], |x| x.iter().sum::<i32>()); /// assert_eq!(subset_map.get(&[1]), Some(&1)); /// assert_eq!(subset_map.get(&[2]), Some(&2)); /// assert_eq!(subset_map.get(&[1, 2]), Some(&3)); /// assert_eq!(subset_map.get(&[]), None); /// assert_eq!(subset_map.get(&[2, 1]), None); /// assert_eq!(subset_map.get(&[0]), None); /// assert_eq!(subset_map.get(&[0, 1]), None); /// ``` pub fn fill<F>(elements: &[E], mut init: F) -> SubsetMap<E, P> where F: FnMut(&[E]) -> P, { init_root::<_, _, _, ()>(elements, &mut |elements| Ok(Some(init(elements)))).unwrap() } /// Initializes the `SubsetMap` with a closure that can fail. /// This function initializes all those subsets with the returned payloads /// where the `init` closure returned an `Result::Ok(Option::Some)` /// given that all calls on the closure returned `Result::Ok`. /// /// Failure of the `init` closure will result in a failure /// of the whole initialization process. /// /// # Example /// /// The whole initialization process fails. /// /// ``` /// use subset_map::*; /// /// let subset_map = SubsetMap::init(&[1, 2], |x| { /// let sum = x.iter().sum::<i32>(); /// if sum == 1 { /// Ok(Some(sum)) /// } else if sum == 2 { /// Ok(None) /// } else { /// Err("bang!") /// } /// }); /// /// assert_eq!(subset_map, Err("bang!")); /// ``` pub fn init<F, X>(elements: &[E], mut init: F) -> Result<SubsetMap<E, P>, X> where F: FnMut(&[E]) -> Result<Option<P>, X>, { init_root(elements, &mut init) } /// Initializes the `SubsetMap` with a closure that can fail. /// This function initializes all subsets with the returned payloads /// given that all calls on the closure returned `Result::Ok`. /// /// Failure of the `init` closure will result in a failure /// of the whole initialization process. /// /// # Example /// /// ``` /// use subset_map::*; /// /// let subset_map = SubsetMap::init_filled(&[1, 2], |x| { /// let sum = x.iter().sum::<i32>(); /// if sum != 3 { /// Ok(sum) /// } else { /// Err("bang!") /// } /// }); /// /// assert_eq!(subset_map, Err("bang!")); /// ``` pub fn init_filled<F, X>(elements: &[E], mut init: F) -> Result<SubsetMap<E, P>, X> where F: FnMut(&[E]) -> Result<P, X>, { init_root::<_, _, _, X>(elements, &mut |elements| init(elements).map(Some)) } /// Creates a new instance where the payloads are all initialized /// with the same value. /// /// # Example /// /// ``` /// use subset_map::*; /// /// let subset_map = SubsetMap::with_value(&[1, 2], || 42); /// assert_eq!(subset_map.get(&[1]), Some(&42)); /// assert_eq!(subset_map.get(&[2]), Some(&42)); /// assert_eq!(subset_map.get(&[1, 2]), Some(&42)); /// assert_eq!(subset_map.get(&[]), None); /// assert_eq!(subset_map.get(&[2, 1]), None); /// assert_eq!(subset_map.get(&[0]), None); /// assert_eq!(subset_map.get(&[0, 1]), None); /// ``` pub fn with_value<F>(elements: &[E], mut init: F) -> SubsetMap<E, P> where F: FnMut() -> P, { init_root::<_, _, _, ()>(elements, &mut |_| Ok(Some(init()))).unwrap() } /// Creates a new instance where the payloads are all initialized /// with the `Default::default()` value of the payload type. /// Creates a new instance where the payloads are all initialized /// with the same value. /// /// # Example /// /// ``` /// use subset_map::*; /// /// let subset_map = SubsetMap::with_default(&[1, 2]); /// assert_eq!(subset_map.get(&[1]), Some(&0)); /// assert_eq!(subset_map.get(&[2]), Some(&0)); /// assert_eq!(subset_map.get(&[1, 2]), Some(&0)); /// assert_eq!(subset_map.get(&[]), None); /// assert_eq!(subset_map.get(&[2, 1]), None); /// assert_eq!(subset_map.get(&[0]), None); /// assert_eq!(subset_map.get(&[0, 1]), None); /// ``` pub fn with_default(elements: &[E]) -> SubsetMap<E, P> where P: Default, { init_root::<_, _, _, ()>(elements, &mut |_| Ok(Some(P::default()))).unwrap() } /// Gets a payload by the given subset. /// /// Only "perfect" matches on `subset` are returned. /// /// The function returns `None` regardless of whether /// `subset` was part of the map or there was no payload /// assigned to the given subset. /// /// ``` /// use subset_map::*; /// /// let subset_map = SubsetMap::new(&[1, 2, 3], |x| { /// let payload = x.iter().cloned().collect::<Vec<_>>(); /// if payload.len() == 1 { /// None /// } else { /// Some(payload) /// } /// }); /// assert_eq!(subset_map.get(&[1]), None); /// assert_eq!(subset_map.get(&[2]), None); /// assert_eq!(subset_map.get(&[3]), None); /// assert_eq!(subset_map.get(&[1, 2]), Some(&vec![1, 2])); /// assert_eq!(subset_map.get(&[2, 3]), Some(&vec![2, 3])); /// assert_eq!(subset_map.get(&[1, 3]), Some(&vec![1, 3])); /// assert_eq!(subset_map.get(&[1, 2, 3]), Some(&vec![1, 2, 3])); /// /// assert_eq!(subset_map.get(&[]), None); /// assert_eq!(subset_map.get(&[7]), None); /// assert_eq!(subset_map.get(&[3, 2, 1]), None); /// assert_eq!(subset_map.get(&[1, 3, 2]), None); /// assert_eq!(subset_map.get(&[3, 2, 1]), None); /// assert_eq!(subset_map.get(&[2, 1]), None); /// ``` pub fn get<'a>(&'a self, subset: &[E]) -> Option<&'a P> where E: Eq, { get(subset, &self.nodes) } /// Looks up a payload by the given subset and returns the /// corresponding owned value. /// /// The function returns `None` regardless of wether /// `subset` was part of the map or there was no payload /// assigned to the given subset. /// /// Only perfect matches on `subset` are returned. See `get`. pub fn get_owned(&self, subset: &[E]) -> Option<P::Owned> where E: Eq, P: ToOwned, { get(subset, &self.nodes).map(|p| p.to_owned()) } /// Looks up a subset and maybe returns the assigned payload. /// /// Elements in `subset` that are not part of the initial set are /// skipped. /// /// The returned `LookupResult` may still contain an optional /// payload. None indicates that the subset was matched but /// there was no payload for the given subset. /// /// Use this method if you are interested whether there was /// a matching subset and then process the maybe present payload. /// Otherwise use `find` or `lookup`. /// /// # Example /// /// ``` /// use subset_map::*; /// /// let subset_map = SubsetMap::new(&[1u32, 2, 3], |x| { /// if x == &[2] { /// None /// } else { /// let payload = x.iter().cloned().collect::<Vec<_>>(); /// Some(payload) /// } /// }); /// /// let empty: &[u32] = &[]; /// /// // A perfect match with a payload: /// let match_result = subset_map.lookup(&[1]); /// assert_eq!(match_result.payload(), Some(&vec![1])); /// assert_eq!(match_result.excluded_elements(), empty); /// assert_eq!(match_result.is_match(), true); /// assert_eq!(match_result.is_perfect(), true); /// assert_eq!(match_result.is_excluded(), false); /// /// // A perfect match that has no payload: /// let match_result = subset_map.lookup(&[2]); /// assert_eq!(match_result.payload(), None); /// assert_eq!(match_result.excluded_elements(), empty); /// assert_eq!(match_result.is_match(), true); /// assert_eq!(match_result.is_perfect(), true); /// assert_eq!(match_result.is_excluded(), false); /// /// // There is no answer at all: /// let match_result = subset_map.lookup(&[42]); /// assert_eq!(match_result.is_no_match(), true); /// assert_eq!(match_result.is_perfect(), false); /// assert_eq!(match_result.is_excluded(), false); /// assert_eq!(match_result.excluded_elements(), empty); /// /// // A nearby match but that has a payload: /// let match_result = subset_map.lookup(&[3,1]); /// assert_eq!(match_result.payload(), Some(&vec![3])); /// assert_eq!(match_result.excluded_elements(), &[1]); /// assert_eq!(match_result.is_perfect(), false); /// assert_eq!(match_result.is_excluded(), true); /// assert_eq!(match_result.is_match(), true); /// /// ``` pub fn lookup<'a>(&'a self, subset: &[E]) -> LookupResult<'a, E, P> where E: Eq, { lookup(subset, &self.nodes) } /// Finds a payload by the given subset. /// /// Elements in `subset` that are not part of the initial set are /// skipped. /// /// If there was no match or no payload for the given subset /// `FindResult::NotFound` is returned. /// /// Use this function if you are mostly interested in /// payloads and how they were matched. Otherwise /// use `lookup` or `get` /// /// # Example /// /// ``` /// use subset_map::*; /// /// let subset_map = SubsetMap::new(&[1u32, 2, 3], |x| { /// if x == &[2] { /// None /// } else { /// let payload = x.iter().cloned().collect::<Vec<_>>(); /// Some(payload) /// } /// }); /// /// let empty: &[u32] = &[]; /// /// // A perfect match with a payload: /// let match_result = subset_map.find(&[1]); /// /// assert_eq!(match_result.payload(), Some(&vec![1])); /// assert_eq!(match_result.is_found(), true); /// assert_eq!(match_result.is_found_and_perfect(), true); /// assert_eq!(match_result.is_found_and_excluded(), false); /// assert_eq!(match_result.excluded_elements(), empty); /// /// // A perfect match that has no payload: /// let match_result = subset_map.find(&[2]); /// /// assert_eq!(match_result.payload(), None); /// assert_eq!(match_result.is_found(), false); /// assert_eq!(match_result.is_found_and_perfect(), false); /// assert_eq!(match_result.is_found_and_excluded(), false); /// assert_eq!(match_result.excluded_elements(), empty); /// /// // There is no answer at all: /// let match_result = subset_map.find(&[42]); /// /// assert_eq!(match_result.payload(), None); /// assert_eq!(match_result.is_not_found(), true); /// assert_eq!(match_result.is_found_and_perfect(), false); /// assert_eq!(match_result.is_found_and_excluded(), false); /// assert_eq!(match_result.excluded_elements(), empty); /// /// // A nearby match but that has a payload: /// let match_result = subset_map.find(&[3,1]); /// /// assert_eq!(match_result.is_found_and_perfect(), false); /// assert_eq!(match_result.is_found_and_excluded(), true); /// assert_eq!(match_result.is_found(), true); /// assert_eq!(match_result.payload(), Some(&vec![3])); /// assert_eq!(match_result.excluded_elements(), &[1]); /// ``` pub fn find<'a>(&'a self, subset: &[E]) -> FindResult<'a, E, P> where E: Eq, { match self.lookup(subset) { LookupResult::Perfect(Some(p)) => FindResult::Perfect(p), LookupResult::Perfect(None) => FindResult::NotFound, LookupResult::Excluded(Some(p), e) => FindResult::Excluded(p, e), LookupResult::Excluded(None, _) => FindResult::NotFound, LookupResult::NoMatch => FindResult::NotFound, } } /// Sets the payload of all subsets to `None` /// where the given payload does not fulfill the `predicate` pub fn filter_values<F>(&mut self, mut predicate: F) where F: FnMut(&P) -> bool, { self.nodes .iter_mut() .for_each(|n| n.filter_values(&mut predicate)) } /// Executes the given mutable closure `f` /// on the value of each node. pub fn walk_values<F>(&self, mut f: F) where F: FnMut(&P), { self.nodes.iter().for_each(|n| n.walk_values(&mut f)) } /// Executes the given mutable closure `f` /// on the value of each node until the /// first closure returns false. pub fn walk_values_until<F>(&self, mut f: F) where F: FnMut(&P) -> bool, { for node in &self.nodes { if !node.walk_values_until(&mut f) { return; } } } /// Executes the given mutable closure `f` /// on the payload of each node pub fn walk_payloads<F>(&self, mut f: F) where F: FnMut(Option<&P>), { self.nodes.iter().for_each(|n| n.walk_payloads(&mut f)) } /// Executes the given mutable closure `f` /// on the payload of each node until the /// first closure returns false. pub fn walk_payloads_until<F>(&self, mut f: F) where F: FnMut(Option<&P>) -> bool, { for node in &self.nodes { if !node.walk_payloads_until(&mut f) { return; } } } /// Walk all elements with their payloads pub fn walk<F>(&self, mut f: F) where F: FnMut(&[&E], Option<&P>), { self.nodes.iter().for_each(|n| n.walk(&mut f)) } /// Executes the given mutable closure `f` /// on the payload of each node pub fn for_each_value<F>(&self, mut f: F) where F: FnMut(&P), { self.walk_values_until(|p| { f(p); true }) } /// Executes the given mutable closure `f` /// on the payload of each node pub fn for_each_payload<F>(&self, mut f: F) where F: FnMut(Option<&P>), { self.walk_payloads_until(|p| { f(p); true }) } /// Returns true if there are nodes and all /// of these have a payload set. pub fn all_subsets_have_values(&self) -> bool { if self.is_empty() { return false; } let mut all_set = true; self.walk_payloads_until(|p| { if p.is_none() { all_set = false; false } else { true } }); all_set } /// Returns true if there are no subsets or all /// of these have no payload set. /// /// # Example /// /// An empty map has no values: /// /// ``` /// use subset_map::*; /// /// let subset_map = SubsetMap::<u8, u8>::with_default(&[]); /// /// assert_eq!(subset_map.no_subset_with_value(), true); /// ``` /// /// An map with a set entry has values: /// /// ``` /// use subset_map::*; /// /// let subset_map = SubsetMap::<u8, u8>::with_default(&[1]); /// /// assert_eq!(subset_map.no_subset_with_value(), false); /// ``` /// /// An non empty map where at least one subset has a value: /// /// ``` /// use subset_map::*; /// /// let mut subset_map = SubsetMap::fill(&[1, 2], |c| c.len()); /// /// subset_map.filter_values(|p| *p == 2); /// /// assert_eq!(subset_map.no_subset_with_value(), false); /// ``` /// /// An non empty map where no subset has a value: /// /// ``` /// use subset_map::*; /// /// let mut subset_map = SubsetMap::<u8, u8>::with_default(&[1, 2]); /// /// // Set all payloads to `None` /// subset_map.filter_values(|p| false); /// /// assert_eq!(subset_map.no_subset_with_value(), true); /// ``` pub fn no_subset_with_value(&self) -> bool { if self.is_empty() { return true; } let mut no_value_set = true; self.walk_payloads_until(|p| { if p.is_some() { no_value_set = false; false } else { true } }); no_value_set } /// Returns true if the map is empty and contains no subsets. pub fn is_empty(&self) -> bool { self.nodes.is_empty() } /// The number of subsets in this map pub fn size(&self) -> usize { 2usize.pow(self.nodes.len() as u32) - 1 } } impl<E, P> Default for SubsetMap<E, P> { fn default() -> Self { SubsetMap { nodes: Default::default(), } } } #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] struct SubsetMapNode<E, P> { pub element: E, pub payload: Option<P>, pub nodes: Nodes<E, P>, } impl<E, P> SubsetMapNode<E, P> { pub fn filter_values<F>(&mut self, predicate: &mut F) where F: FnMut(&P) -> bool, { let keep = self.payload.as_ref().map(|p| predicate(p)).unwrap_or(true); if !keep { self.payload = None; } self.nodes .iter_mut() .for_each(|n| n.filter_values(predicate)) } pub fn walk_values<F>(&self, f: &mut F) where F: FnMut(&P), { if let Some(ref payload) = self.payload { f(payload); } self.nodes.iter().for_each(|n| n.walk_values(f)) } pub fn walk_payloads<F>(&self, f: &mut F) where F: FnMut(Option<&P>), { f(self.payload.as_ref()); self.nodes.iter().for_each(|n| n.walk_payloads(f)) } pub fn walk_values_until<F>(&self, f: &mut F) -> bool where F: FnMut(&P) -> bool, { let go_on = if let Some(ref payload) = self.payload { f(payload) } else { true }; if go_on { for node in &self.nodes { if !node.walk_values_until(f) { return false; } } } true } pub fn walk_payloads_until<F>(&self, f: &mut F) -> bool where F: FnMut(Option<&P>) -> bool, { if f(self.payload.as_ref()) { for node in &self.nodes { if !node.walk_payloads_until(f) { return false; } } true } else { false } } pub fn walk<F>(&self, mut f: F) where F: FnMut(&[&E], Option<&P>), { let mut elements = Vec::new(); self.walk_internal(&mut elements, &mut f) } fn walk_internal<'a, F>(&'a self, elements: &mut Vec<&'a E>, f: &mut F) where F: FnMut(&[&E], Option<&P>), { elements.push(&self.element); f(elements.as_slice(), self.payload.as_ref()); self.nodes.iter().for_each(|n| n.walk_internal(elements, f)); elements.pop(); } } /// The result of `SubsetMap::lookup`. /// /// It can either be a perfect match on the subset /// or a match where some elements of the input set /// had to be excluded. /// /// A value of `None` for the payload indicates /// that there was a match for a given subset but /// nevertheless there was no payload stored for /// that subset. #[derive(Debug)] pub enum LookupResult<'a, E, P: 'a> { /// The input set exactly matched a combination /// of the original set. Perfect(Option<&'a P>), /// There were some elements in the input set that had /// to be excluded to match a subset of the original set /// /// The excluded elements are returned. Excluded(Option<&'a P>, Vec<E>), /// There was no match at all for the given subset NoMatch, } impl<'a, E, P> LookupResult<'a, E, P> { pub fn payload(&self) -> Option<&P> { match *self { LookupResult::Perfect(p) => p, LookupResult::Excluded(p, _) => p, LookupResult::NoMatch => None, } } /// Returns the excluded elements if there was /// a match at all. /// /// If there was no match the returned slice /// is also empty. pub fn excluded_elements(&self) -> &[E] { match *self { LookupResult::Perfect(_) => &[], LookupResult::Excluded(_, ref skipped) => &*skipped, LookupResult::NoMatch => &[], } } /// Returns `true` if there was a perfect match pub fn is_perfect(&self) -> bool { match *self { LookupResult::Perfect(_) => true, _ => false, } } /// Returns `true` if there was a match /// but some elements had to be excluded pub fn is_excluded(&self) -> bool { match *self { LookupResult::Excluded(_, _) => true, _ => false, } } /// Returns `true` if there was no match at all pub fn is_no_match(&self) -> bool { !self.is_match() } /// Returns `true` if there was a match even /// though some elements had to be excluded pub fn is_match(&self) -> bool { match *self { LookupResult::NoMatch => false, _ => true, } } } /// The result of `SubsetMap::find`. /// /// It can either be a perfect match on the subset /// or a match where some elements of the input set /// had to be excluded. /// /// For `FindResult::NotFound` no tracking of /// excluded elements is done. #[derive(Debug)] pub enum FindResult<'a, E, P: 'a> { /// The input set exactly matched a combination /// of the original set and there was a payload. Perfect(&'a P), /// There were some elements in the input set that had /// to be excluded to match a subset of the original set. /// /// Still there was a payload at the given position. /// /// The excluded elements are returned. Excluded(&'a P, Vec<E>), /// There was no match at all or the payload /// for the matched subset was `None` NotFound, } impl<'a, E, P> FindResult<'a, E, P> { pub fn payload(&self) -> Option<&P> { match *self { FindResult::Perfect(p) => Some(p), FindResult::Excluded(p, _) => Some(p), FindResult::NotFound => None, } } /// Returns the excluded elements if there was /// a match at all. /// /// If there was no match the returned slice /// is also empty. pub fn excluded_elements(&self) -> &[E] { match *self { FindResult::Perfect(_) => &[], FindResult::Excluded(_, ref skipped) => &*skipped, FindResult::NotFound => &[], } } /// Returns `true` if there was a perfect match pub fn is_found_and_perfect(&self) -> bool { match *self { FindResult::Perfect(_) => true, _ => false, } } /// Returns `true` if there was a match /// but some elements had to be excluded pub fn is_found_and_excluded(&self) -> bool { match *self { FindResult::Excluded(_, _) => true, _ => false, } } /// Returns `true` if there was no match /// or if the payload for the matched subset was /// `None` pub fn is_not_found(&self) -> bool { !self.is_found() } /// Returns `true` if there was a match even /// though some elements had to be excluded /// and if there was a payload for the matched /// subset. pub fn is_found(&self) -> bool { match *self { FindResult::NotFound => false, _ => true, } } } fn init_root<E, P, F, X>(elements: &[E], init_with: &mut F) -> Result<SubsetMap<E, P>, X> where E: Clone, F: FnMut(&[E]) -> Result<Option<P>, X>, { let mut stack = Vec::new(); let mut nodes = Vec::new(); for fixed in 0..elements.len() { let element = elements[fixed].clone(); let payload = init_with(&elements[fixed..=fixed])?; let mut node = SubsetMapNode { element, payload, nodes: Vec::new(), }; stack.clear(); stack.push(elements[fixed].clone()); init_node(elements, &mut stack, fixed, &mut node, init_with)?; nodes.push(node) } Ok(SubsetMap { nodes }) } fn init_node<E, P, F, X>( elements: &[E], stack: &mut Vec<E>, fixed: usize, into: &mut SubsetMapNode<E, P>, init_with: &mut F, ) -> Result<(), X> where E: Clone, F: FnMut(&[E]) -> Result<Option<P>, X>, { for fixed in fixed + 1..elements.len() { stack.push(elements[fixed].clone()); let mut node = SubsetMapNode { element: elements[fixed].clone(), payload: init_with(&stack)?, nodes: Vec::new(), }; let _ = init_node(elements, stack, fixed, &mut node, init_with); stack.pop(); into.nodes.push(node); } Ok(()) } fn get<'a, 'b, E, P>(subset: &'b [E], nodes: &'a [SubsetMapNode<E, P>]) -> Option<&'a P> where E: Eq, { let mut nodes = nodes; let mut result = None; for element in subset { if let Some(node) = nodes.iter().find(|n| n.element == *element) { result = node.payload.as_ref(); nodes = &node.nodes; } else { return None; } } result } fn lookup<'a, 'b, E, P>(subset: &'b [E], nodes: &'a [SubsetMapNode<E, P>]) -> LookupResult<'a, E, P> where E: Eq + Clone, { let mut excluded = Vec::new(); let mut nodes = nodes; let mut result_node = None; for element in subset { if let Some(node) = nodes.iter().find(|n| n.element == *element) { result_node = Some(node); nodes = &node.nodes; } else { excluded.push(element.clone()) } } if let Some(result_node) = result_node { if excluded.is_empty() { LookupResult::Perfect(result_node.payload.as_ref()) } else { LookupResult::Excluded(result_node.payload.as_ref(), excluded) } } else { LookupResult::NoMatch } } #[cfg(test)] mod tests { use super::*; #[test] fn create_empty() { let sample = SubsetMap::<u32, ()>::default(); assert!(sample.is_empty()); } #[test] fn one_element() { let sample = SubsetMap::fill(&[1], |_| 1); assert_eq!(sample.get(&[1]), Some(&1)); assert_eq!(sample.get(&[]), None); assert_eq!(sample.get(&[2]), None); } #[test] fn two_elements() { let sample = SubsetMap::fill(&[1, 2], |x| x.iter().sum::<i32>()); assert_eq!(sample.get(&[1]), Some(&1)); assert_eq!(sample.get(&[2]), Some(&2)); assert_eq!(sample.get(&[1, 2]), Some(&3)); assert_eq!(sample.get(&[]), None); assert_eq!(sample.get(&[2, 1]), None); assert_eq!(sample.get(&[0]), None); assert_eq!(sample.get(&[0, 1]), None); } #[test] fn three_elements() { let sample = SubsetMap::fill(&[1, 2, 3], |x| x.iter().sum::<i32>()); assert_eq!(sample.get(&[1]), Some(&1)); assert_eq!(sample.get(&[2]), Some(&2)); assert_eq!(sample.get(&[3]), Some(&3)); assert_eq!(sample.get(&[1, 2]), Some(&3)); assert_eq!(sample.get(&[2, 3]), Some(&5)); assert_eq!(sample.get(&[1, 3]), Some(&4)); assert_eq!(sample.get(&[1, 2, 3]), Some(&6)); assert_eq!(sample.get(&[]), None); assert_eq!(sample.get(&[2, 1]), None); assert_eq!(sample.get(&[0]), None); assert_eq!(sample.get(&[0, 1]), None); } #[test] fn three_elements_identity_vec() { let sample = SubsetMap::fill(&[1, 2, 3], |x| x.to_vec()); assert_eq!(sample.get(&[1]), Some(&vec![1])); assert_eq!(sample.get(&[2]), Some(&vec![2])); assert_eq!(sample.get(&[3]), Some(&vec![3])); assert_eq!(sample.get(&[1, 2]), Some(&vec![1, 2])); assert_eq!(sample.get(&[2, 3]), Some(&vec![2, 3])); assert_eq!(sample.get(&[1, 3]), Some(&vec![1, 3])); assert_eq!(sample.get(&[1, 2, 3]), Some(&vec![1, 2, 3])); } #[test] fn walk_5_elems_keeps_order() { let elements: Vec<_> = (0..5).collect(); let mut n = 0; let map = SubsetMap::fill(&elements, |_x| { n += 1; n }); let mut n = 0; map.walk(|_elements, payload| { n += 1; assert_eq!(payload, Some(&n)); }) } #[test] fn test_lookup_result() { let subset_map = SubsetMap::new(&[1u32, 2, 3, 4], |x| { if x == &[2, 3] { None } else { let payload = x.iter().cloned().collect::<Vec<_>>(); Some(payload) } }); let empty: &[u32] = &[]; let match_result = subset_map.lookup(&[]); assert_eq!(match_result.payload(), None); assert_eq!(match_result.excluded_elements(), empty); assert_eq!(match_result.is_match(), false); assert_eq!(match_result.is_perfect(), false); assert_eq!(match_result.is_excluded(), false); let match_result = subset_map.lookup(&[1]); assert_eq!(match_result.payload(), Some(&vec![1])); assert_eq!(match_result.excluded_elements(), empty); assert_eq!(match_result.is_match(), true); assert_eq!(match_result.is_perfect(), true); assert_eq!(match_result.is_excluded(), false); let match_result = subset_map.lookup(&[2, 3]); assert_eq!(match_result.payload(), None); assert_eq!(match_result.excluded_elements(), empty); assert_eq!(match_result.is_match(), true); assert_eq!(match_result.is_perfect(), true); assert_eq!(match_result.is_excluded(), false); let match_result = subset_map.lookup(&[42]); assert_eq!(match_result.is_no_match(), true); assert_eq!(match_result.is_perfect(), false); assert_eq!(match_result.is_excluded(), false); assert_eq!(match_result.excluded_elements(), empty); let match_result = subset_map.lookup(&[42, 3]); assert_eq!(match_result.payload(), Some(&vec![3])); assert_eq!(match_result.excluded_elements(), &[42]); assert_eq!(match_result.is_perfect(), false); assert_eq!(match_result.is_excluded(), true); assert_eq!(match_result.is_match(), true); let match_result = subset_map.lookup(&[3, 1]); assert_eq!(match_result.payload(), Some(&vec![3])); assert_eq!(match_result.excluded_elements(), &[1]); assert_eq!(match_result.is_perfect(), false); assert_eq!(match_result.is_excluded(), true); assert_eq!(match_result.is_match(), true); let match_result = subset_map.lookup(&[3, 1, 4, 2]); assert_eq!(match_result.payload(), Some(&vec![3, 4])); assert_eq!(match_result.excluded_elements(), &[1, 2]); assert_eq!(match_result.is_perfect(), false); assert_eq!(match_result.is_excluded(), true); assert_eq!(match_result.is_match(), true); let match_result = subset_map.lookup(&[4, 3, 2, 1]); assert_eq!(match_result.payload(), Some(&vec![4])); assert_eq!(match_result.excluded_elements(), &[3, 2, 1]); assert_eq!(match_result.is_perfect(), false); assert_eq!(match_result.is_excluded(), true); assert_eq!(match_result.is_match(), true); let match_result = subset_map.lookup(&[99, 2, 1, 77, 78, 3, 4, 2, 1, 2]); assert_eq!(match_result.payload(), Some(&vec![2, 3, 4])); assert_eq!(match_result.excluded_elements(), &[99, 1, 77, 78, 2, 1, 2]); assert_eq!(match_result.is_perfect(), false); assert_eq!(match_result.is_excluded(), true); assert_eq!(match_result.is_match(), true); } }