From d29c2be66852e26bd12b41fd58164465b6bbd44a Mon Sep 17 00:00:00 2001 From: Alexander Cyon Date: Wed, 3 Jul 2024 12:40:23 +0200 Subject: [PATCH] Add a new constructor to IndexSet and IndexMap respectively: 'just' creating a collection from a single element. --- src/map.rs | 11 +++++++++++ src/set.rs | 11 +++++++++++ tests/tests.rs | 14 +++++++++++++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/map.rs b/src/map.rs index 82824c90..d6629d1c 100644 --- a/src/map.rs +++ b/src/map.rs @@ -1295,6 +1295,17 @@ impl IndexMut for IndexMap { } } +impl IndexMap +where + K: Hash + Eq, + S: BuildHasher + Default, +{ + /// Create an `IndexMap` from the key-value pair. + pub fn just(pair: (K, V)) -> Self { + Self::from_iter([pair]) + } +} + impl FromIterator<(K, V)> for IndexMap where K: Hash + Eq, diff --git a/src/set.rs b/src/set.rs index b5bd05f1..80b81461 100644 --- a/src/set.rs +++ b/src/set.rs @@ -996,6 +996,17 @@ where } } +impl IndexSet +where + T: Hash + Eq, + S: BuildHasher + Default, +{ + /// Create a new set with the single `element` + pub fn just(element: T) -> Self { + Self::from_iter([element]) + } +} + #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] impl From<[T; N]> for IndexSet diff --git a/tests/tests.rs b/tests/tests.rs index 7d522f1c..e078ac64 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -1,4 +1,16 @@ -use indexmap::{indexmap, indexset}; +use indexmap::{indexmap, indexset, IndexMap, IndexSet}; + +#[test] +fn test_set_just() { + let s = IndexSet::::just(42); + assert_eq!(s, IndexSet::<_>::from_iter([42])); +} + +#[test] +fn test_map_just() { + let m = IndexMap::::just((42, 1337)); + assert_eq!(m.get(&42), Some(&1337)); +} #[test] fn test_sort() {