From eb6e713c1dd0a500441a837ded154b763d2e0353 Mon Sep 17 00:00:00 2001 From: Avril Date: Tue, 17 Nov 2020 22:03:28 +0000 Subject: [PATCH] added reverse --- Cargo.toml | 2 +- src/lib.rs | 14 ++++++++++++++ src/tests.rs | 20 ++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index d517228..63aea1c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ description = "Small byte-sized generic key-value map type" keywords = ["map", "table", "small", "key", "value"] repository = "https://github.com/notflan/smallmap" homepage= "https://git.flanchan.moe/flanchan/smallmap" -version = "1.1.6" +version = "1.2.0" authors = ["Avril "] edition = "2018" license = "MIT" diff --git a/src/lib.rs b/src/lib.rs index 9dc9014..472814d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -389,6 +389,20 @@ where K: Collapse self.0.push(page); None } + + /// Consume this `Map` by swapping its keys and values around. + pub fn reverse(self) -> Map + where V: Collapse + { + let mut output = Map::with_capacity(self.num_pages()); + + for (k,v) in self.into_iter() + { + output.insert(v, k); + } + + output + } } impl IntoIterator for Map diff --git a/src/tests.rs b/src/tests.rs index b5022ce..6b438e6 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -101,6 +101,26 @@ fn type_primitive() test_insert_type!(i128, 0..10000); } +#[test] +fn reverse() +{ + let map = smallmap![ + {"one" => 1}, + {"two" => 2}, + {"three" => 3}, + {"four" => 4}, + ]; + let expected = smallmap![ + {1 => "one"}, + {2 => "two"}, + {3 => "three"}, + {4 => "four"}, + ]; + + assert_eq!(map.reverse(), expected); + assert_eq!(expected.reverse().into_iter().map(|(_, v)| v).sum::(), 4+3+2+1); +} + #[cfg(nightly)] mod benchmarks {