Skip to content

Commit 56e2c47

Browse files
committed
Merge pull request #18 from thijsc/insert_key_slices
Allow string slices as keys for insertion
2 parents 066dcbf + 9764532 commit 56e2c47

File tree

2 files changed

+28
-8
lines changed

2 files changed

+28
-8
lines changed

src/ordered.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -190,16 +190,19 @@ impl OrderedDocument {
190190

191191
/// Sets the value of the entry with the OccupiedEntry's key,
192192
/// and returns the entry's old value.
193-
pub fn insert(&mut self, key: String, val: Bson) -> Option<Bson> {
194-
let key_slice = &key[..];
195-
196-
if self.contains_key(key_slice) {
197-
let position = self.position(key_slice).unwrap();
198-
self.keys.remove(position);
193+
pub fn insert<KT: Into<String>>(&mut self, key: KT, val: Bson) -> Option<Bson> {
194+
let key = key.into();
195+
196+
{
197+
let key_slice = &key[..];
198+
if self.contains_key(key_slice) {
199+
let position = self.position(key_slice).unwrap();
200+
self.keys.remove(position);
201+
}
199202
}
200203

201204
self.keys.push(key.to_owned());
202-
self.document.insert(key.to_owned(), val.to_owned())
205+
self.document.insert(key, val.to_owned())
203206
}
204207

205208
/// Takes the value of the entry out of the document, and returns it.

tests/modules/ordered.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,24 @@ fn ordered_insert() {
1111
"first".to_owned(),
1212
"second".to_owned(),
1313
"alphanumeric".to_owned(),
14-
);
14+
);
15+
16+
let keys: Vec<_> = doc.iter().map(|(key, _)| key.to_owned()).collect();
17+
assert_eq!(expected_keys, keys);
18+
}
19+
20+
#[test]
21+
fn ordered_insert_shorthand() {
22+
let mut doc = Document::new();
23+
doc.insert("first", Bson::I32(1));
24+
doc.insert("second", Bson::String("foo".to_owned()));
25+
doc.insert("alphanumeric", Bson::String("bar".to_owned()));
26+
27+
let expected_keys = vec!(
28+
"first".to_owned(),
29+
"second".to_owned(),
30+
"alphanumeric".to_owned(),
31+
);
1532

1633
let keys: Vec<_> = doc.iter().map(|(key, _)| key.to_owned()).collect();
1734
assert_eq!(expected_keys, keys);

0 commit comments

Comments
 (0)