Skip to content

Commit 8f2a127

Browse files
committed
Return iterators for keys() and values()
1 parent e6263f5 commit 8f2a127

File tree

1 file changed

+42
-5
lines changed

1 file changed

+42
-5
lines changed

src/ordered.rs

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use bson::Bson;
22
use std::collections::BTreeMap;
3-
use std::iter::FromIterator;
3+
use std::iter::{FromIterator, Map};
44

55
/// A BSON document represented as an associative BTree Map with insertion ordering.
66
#[derive(Debug, Clone)]
@@ -10,17 +10,48 @@ pub struct OrderedDocument {
1010
}
1111

1212
/// An iterator over OrderedDocument entries.
13+
#[derive(Clone)]
1314
pub struct OrderedDocumentIterator {
1415
ordered_document: OrderedDocument,
1516
index: usize,
1617
}
1718

1819
/// An owning iterator over OrderedDocument entries.
20+
#[derive(Clone)]
1921
pub struct OrderedDocumentIntoIterator<'a> {
2022
ordered_document: &'a OrderedDocument,
2123
index: usize,
2224
}
2325

26+
/// An iterator over an OrderedDocument's keys.
27+
pub struct Keys<'a> {
28+
inner: Map<OrderedDocumentIntoIterator<'a>, fn((&'a String, &'a Bson)) -> &'a String>
29+
}
30+
31+
/// An iterator over an OrderedDocument's values.
32+
pub struct Values<'a> {
33+
inner: Map<OrderedDocumentIntoIterator<'a>, fn((&'a String, &'a Bson)) -> &'a Bson>
34+
}
35+
36+
impl<'a> Clone for Keys<'a> {
37+
fn clone(&self) -> Keys<'a> { Keys { inner: self.inner.clone() } }
38+
}
39+
40+
impl<'a> Iterator for Keys<'a> {
41+
type Item = &'a String;
42+
fn next(&mut self) -> Option<(&'a String)> { self.inner.next() }
43+
}
44+
45+
impl<'a> Clone for Values<'a> {
46+
fn clone(&self) -> Values<'a> { Values { inner: self.inner.clone() } }
47+
}
48+
49+
impl<'a> Iterator for Values<'a> {
50+
type Item = &'a Bson;
51+
52+
fn next(&mut self) -> Option<(&'a Bson)> { self.inner.next() }
53+
}
54+
2455
impl IntoIterator for OrderedDocument {
2556
type Item = (String, Bson);
2657
type IntoIter = OrderedDocumentIterator;
@@ -118,13 +149,19 @@ impl OrderedDocument {
118149
}
119150

120151
/// Gets a collection of all keys in the document.
121-
pub fn keys<'a>(&'a self) -> Vec<&String> {
122-
self.iter().map(|(k, _)| k).collect()
152+
pub fn keys<'a>(&'a self) -> Keys<'a> {
153+
fn first<A, B>((a, _): (A, B)) -> A { a }
154+
let first: fn((&'a String, &'a Bson)) -> &'a String = first;
155+
156+
Keys { inner: self.iter().map(first) }
123157
}
124158

125159
/// Gets a collection of all values in the document.
126-
pub fn values<'a>(&'a self) -> Vec<&Bson> {
127-
self.iter().map(|(_, v)| v).collect()
160+
pub fn values<'a>(&'a self) -> Values<'a> {
161+
fn second<A, B>((_, b): (A, B)) -> B { b }
162+
let second: fn((&'a String, &'a Bson)) -> &'a Bson = second;
163+
164+
Values { inner: self.iter().map(second) }
128165
}
129166

130167
/// Returns the number of elements in the document.

0 commit comments

Comments
 (0)