]> git.lizzy.rs Git - rust.git/commitdiff
std: Add iterator::Repeat to repeat an element endlessly
authorblake2-ppc <blake2-ppc>
Sat, 3 Aug 2013 19:34:00 +0000 (21:34 +0200)
committerblake2-ppc <blake2-ppc>
Tue, 6 Aug 2013 02:05:07 +0000 (04:05 +0200)
src/libstd/iterator.rs

index 372afd7402d45c3eeea3e28cdfc1e3ddd1cdb683..bf55b4f7ce2e311d7424866778a163c338e9fa1b 100644 (file)
@@ -1565,6 +1565,39 @@ fn size_hint(&self) -> (uint, Option<uint>) {
     }
 }
 
+/// An iterator that repeats an element endlessly
+#[deriving(Clone, DeepClone)]
+pub struct Repeat<A> {
+    priv element: A
+}
+
+impl<A: Clone> Repeat<A> {
+    /// Create a new `Repeat` that enlessly repeats the element `elt`.
+    #[inline]
+    pub fn new(elt: A) -> Repeat<A> {
+        Repeat{element: elt}
+    }
+}
+
+impl<A: Clone> Iterator<A> for Repeat<A> {
+    #[inline]
+    fn next(&mut self) -> Option<A> { self.idx(0) }
+    #[inline]
+    fn size_hint(&self) -> (uint, Option<uint>) { (uint::max_value, None) }
+}
+
+impl<A: Clone> DoubleEndedIterator<A> for Repeat<A> {
+    #[inline]
+    fn next_back(&mut self) -> Option<A> { self.idx(0) }
+}
+
+impl<A: Clone> RandomAccessIterator<A> for Repeat<A> {
+    #[inline]
+    fn indexable(&self) -> uint { uint::max_value }
+    #[inline]
+    fn idx(&self, _: uint) -> Option<A> { Some(self.element.clone()) }
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;