Skip to content

Commit

Permalink
Add a new constructor to IndexSet and IndexMap respectively: 'just' c…
Browse files Browse the repository at this point in the history
…reating a collection from a single element.
  • Loading branch information
Sajjon committed Jul 3, 2024
1 parent 1a71dde commit d29c2be
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1295,6 +1295,17 @@ impl<K, V, S> IndexMut<usize> for IndexMap<K, V, S> {
}
}

impl<K, V, S> IndexMap<K, V, S>
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<K, V, S> FromIterator<(K, V)> for IndexMap<K, V, S>
where
K: Hash + Eq,
Expand Down
11 changes: 11 additions & 0 deletions src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -996,6 +996,17 @@ where
}
}

impl<T, S> IndexSet<T, S>
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<T, const N: usize> From<[T; N]> for IndexSet<T, RandomState>
Expand Down
14 changes: 13 additions & 1 deletion tests/tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
use indexmap::{indexmap, indexset};
use indexmap::{indexmap, indexset, IndexMap, IndexSet};

#[test]
fn test_set_just() {
let s = IndexSet::<u8>::just(42);
assert_eq!(s, IndexSet::<_>::from_iter([42]));
}

#[test]
fn test_map_just() {
let m = IndexMap::<u8, u16>::just((42, 1337));
assert_eq!(m.get(&42), Some(&1337));
}

#[test]
fn test_sort() {
Expand Down

0 comments on commit d29c2be

Please sign in to comment.