File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change @@ -49,6 +49,7 @@ mod sources;
49
49
pub use sources:: { convert, Convert } ;
50
50
pub use sources:: { convert_ref, ConvertRef } ;
51
51
pub use sources:: { empty, Empty } ;
52
+ pub use sources:: { once, Once } ;
52
53
53
54
/// An interface for dealing with streaming iterators.
54
55
pub trait StreamingIterator {
Original file line number Diff line number Diff line change @@ -42,6 +42,15 @@ pub fn empty<T>() -> Empty<T> {
42
42
}
43
43
}
44
44
45
+ /// Creates an iterator that returns exactly one item
46
+ #[ inline]
47
+ pub fn once < T > ( item : T ) -> Once < T > {
48
+ Once {
49
+ first : true ,
50
+ item : Some ( item) ,
51
+ }
52
+ }
53
+
45
54
/// A streaming iterator which yields elements from a normal, non-streaming, iterator.
46
55
#[ derive( Clone , Debug ) ]
47
56
pub struct Convert < I >
@@ -200,3 +209,41 @@ impl<T> DoubleEndedStreamingIterator for Empty<T> {
200
209
#[ inline]
201
210
fn advance_back ( & mut self ) { }
202
211
}
212
+
213
+ /// A simple iterator that returns exactly one item.
214
+ #[ derive( Clone , Debug ) ]
215
+ pub struct Once < T > {
216
+ first : bool ,
217
+ item : Option < T > ,
218
+ }
219
+
220
+ impl < T > StreamingIterator for Once < T > {
221
+ type Item = T ;
222
+
223
+ #[ inline]
224
+ fn advance ( & mut self ) {
225
+ if self . first {
226
+ self . first = false ;
227
+ } else {
228
+ self . item = None ;
229
+ }
230
+ }
231
+
232
+ #[ inline]
233
+ fn get ( & self ) -> Option < & Self :: Item > {
234
+ self . item . as_ref ( )
235
+ }
236
+
237
+ #[ inline]
238
+ fn size_hint ( & self ) -> ( usize , Option < usize > ) {
239
+ let len = self . first as usize ;
240
+ ( len, Some ( len) )
241
+ }
242
+ }
243
+
244
+ impl < T > DoubleEndedStreamingIterator for Once < T > {
245
+ #[ inline]
246
+ fn advance_back ( & mut self ) {
247
+ self . advance ( ) ;
248
+ }
249
+ }
You can’t perform that action at this time.
0 commit comments