From a9d2028477651b5e0dffbe4483f797a387f30775 Mon Sep 17 00:00:00 2001 From: Daniel Baker Date: Tue, 12 Mar 2024 14:21:01 -0700 Subject: [PATCH] Add as_slice functions to map and set with corresponding tests. Allows viewing of contents without coercing to vector. --- Cargo.toml | 2 +- src/lib.rs | 7 +++++++ src/set.rs | 7 +++++++ tests/test.rs | 15 +++++++++++++++ 4 files changed, 30 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index e72c57c..b37a044 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "linear-map" -version = "1.2.0" +version = "1.2.1" license = "MIT/Apache-2.0" description = "A map implemented by searching linearly in a vector." authors = [ diff --git a/src/lib.rs b/src/lib.rs index b976017..5f230b7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -202,6 +202,13 @@ impl LinearMap { } } + /// Returns a a slice viewing the map's keys and references in arbitrary order. + /// + /// The item type is `(K, V)`. + pub fn as_slice(&self) -> &[(K, V)] { + &self.storage + } + /// Returns an iterator yielding references to the map's keys in arbitrary order. /// /// The iterator's item type is `&K`. diff --git a/src/set.rs b/src/set.rs index a3246df..c5cbb74 100644 --- a/src/set.rs +++ b/src/set.rs @@ -504,6 +504,13 @@ where { self.map.remove(value).is_some() } + + /// Returns a a slice viewing the sets values in arbitrary order. + /// + /// The item type is `(T, ())`. + pub fn as_slice(&self) -> &[(T, ())] { + &self.map.storage + } } impl PartialEq for LinearSet diff --git a/tests/test.rs b/tests/test.rs index 8e1de81..4817d92 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -265,6 +265,21 @@ fn test_macro() { }; } +#[test] +fn test_as_slice() { + use linear_map::set::LinearSet; + let names = linear_map! { + 1 => "one", + 2 => "two", + }; + let slice = names.as_slice(); + assert_eq!(slice, &[(1, "one"), (2, "two")]); + let names: LinearSet<&'static str> = names.into_iter().map(|x| x.1).collect::>(); + // LinearSet have (T, ()) as items as an implementation detail. + let slice = names.as_slice(); + assert_eq!(slice, &[("one", ()), ("two", ())]); +} + #[test] fn test_retain() { let mut map: LinearMap = (0..100).map(|x| (x, x * 10)).collect();