Skip to content

Commit

Permalink
feat(map): add forgotten FromNonEmptyIterator
Browse files Browse the repository at this point in the history
An oversight discovered when developing downstream.
  • Loading branch information
fosskers committed Aug 19, 2024
1 parent 8b84341 commit a9913de
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# `nonempty-collections`

## Unreleased

#### Added

- Missing `FromNonEmptyIterator` for `HashMap`.

## 0.2.7 (2024-07-22)

#### Added
Expand Down
43 changes: 42 additions & 1 deletion src/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use crate::NEVec;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::collections::HashSet;
use std::hash::Hash;
use std::iter::{Product, Sum};
Expand Down Expand Up @@ -736,7 +737,27 @@ impl<T> FromNonEmptyIterator<T> for Vec<T> {
}
}

impl<T: Eq + Hash> FromNonEmptyIterator<T> for HashSet<T> {
impl<K, V> FromNonEmptyIterator<(K, V)> for HashMap<K, V>
where
K: Eq + Hash,
{
fn from_nonempty_iter<I>(iter: I) -> Self
where
I: IntoNonEmptyIterator<Item = (K, V)>,
{
let ((head_key, head_val), rest) = iter.into_nonempty_iter().first();

let mut hm = HashMap::new();
hm.insert(head_key, head_val);
hm.extend(rest);
hm
}
}

impl<T> FromNonEmptyIterator<T> for HashSet<T>
where
T: Eq + Hash,
{
fn from_nonempty_iter<I>(iter: I) -> Self
where
I: IntoNonEmptyIterator<Item = T>,
Expand Down Expand Up @@ -1344,3 +1365,23 @@ where
self.iter.next()
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::{nem, NEMap};

#[test]
fn into_hashset() {
let m = nem!['a' => 1, 'b' => 2, 'c' => 3];
let _: HashSet<_> = m.values().collect();
}

#[test]
fn into_hashmap() {
let m = nem!['a' => 1, 'b' => 2, 'c' => 3];
let h: HashMap<_, _> = m.iter().map(|(k, v)| (*k, *v)).collect();
let n = NEMap::try_from(h).unwrap();
assert_eq!(m, n);
}
}

0 comments on commit a9913de

Please sign in to comment.