Skip to content

Commit de0f60c

Browse files
TheDan64abr-egn
andauthored
RUST-2266 Add HashSet to Bson conversion (#598)
Co-authored-by: Abraham Egnor <abraham.egnor@mongodb.com>
1 parent 5c20bde commit de0f60c

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/bson.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
//! BSON definition
2323
2424
use std::{
25+
collections::HashSet,
2526
convert::TryFrom,
2627
fmt::{self, Debug, Display, Formatter},
2728
hash::Hash,
@@ -342,6 +343,12 @@ where
342343
}
343344
}
344345

346+
impl<T: Into<Bson>, S> From<HashSet<T, S>> for Bson {
347+
fn from(s: HashSet<T, S>) -> Bson {
348+
Bson::from_iter(s)
349+
}
350+
}
351+
345352
impl<T> From<&[T]> for Bson
346353
where
347354
T: Clone + Into<Bson>,

src/tests/modules/bson.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::{
2+
collections::HashSet,
23
convert::TryFrom,
34
time::{Duration, SystemTime},
45
};
@@ -558,3 +559,44 @@ fn test_hashable() {
558559

559560
assert!(map.is_empty());
560561
}
562+
563+
#[test]
564+
fn test_hash_set_to_bson() {
565+
let mut set1 = HashSet::new();
566+
let mut set2 = HashSet::new();
567+
568+
set1.insert(1);
569+
set1.insert(2);
570+
set1.insert(3);
571+
set2.insert(&1);
572+
set2.insert(&2);
573+
set2.insert(&3);
574+
575+
let d1 = doc! {
576+
"foo": set1,
577+
};
578+
let d2 = doc! {
579+
"foo": set2,
580+
};
581+
let a1: Vec<_> = d1
582+
.get_array("foo")
583+
.unwrap()
584+
.iter()
585+
.map(|v| v.as_i32().unwrap())
586+
.collect();
587+
let a2: Vec<_> = d2
588+
.get_array("foo")
589+
.unwrap()
590+
.iter()
591+
.map(|v| v.as_i32().unwrap())
592+
.collect();
593+
594+
assert_eq!(a1.len(), 3);
595+
assert_eq!(a2.len(), 3);
596+
assert!(a1.contains(&1));
597+
assert!(a1.contains(&2));
598+
assert!(a1.contains(&3));
599+
assert!(a2.contains(&1));
600+
assert!(a2.contains(&2));
601+
assert!(a2.contains(&3));
602+
}

0 commit comments

Comments
 (0)