Created
May 14, 2017 20:14
-
-
Save filcuc/48d52eb0cee06b042162b499f846b032 to your computer and use it in GitHub Desktop.
Example of polymorphism with Iterators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fs::File; | |
use std::io::BufReader; | |
use std::io::BufRead; | |
use std::io::Lines; | |
struct FileLinesIteratorWrapper { | |
iterator: Lines<BufReader<File>> | |
} | |
impl Iterator for FileLinesIteratorWrapper { | |
type Item = String; | |
fn next(&mut self) -> Option<Self::Item> { | |
while let Some(line) = self.iterator.next() { | |
if let Ok(line) = line { | |
return Some(line); | |
} | |
} | |
None | |
} | |
} | |
struct StringLinesIteratorWrapper<'a> { | |
iterator: std::str::Lines<'a> | |
} | |
impl<'a> Iterator for StringLinesIteratorWrapper<'a> { | |
type Item = String; | |
fn next(&mut self) -> Option<Self::Item> { | |
while let Some(line) = self.iterator.next() { | |
return Some(line.to_string()); | |
} | |
None | |
} | |
} | |
struct UnfoldedLinesIterator<'a> { | |
iterator: Box<Iterator<Item=String> + 'a> | |
} | |
impl<'a> Iterator for UnfoldedLinesIterator<'a> { | |
type Item = String; | |
fn next(&mut self) -> Option<Self::Item> { | |
while let Some(line) = self.iterator.next() { | |
return Some(line); | |
} | |
None | |
} | |
} | |
trait UnfoldedLines<'a> { | |
fn unfolded_lines(self) -> UnfoldedLinesIterator<'a>; | |
} | |
impl<'a> UnfoldedLines<'a> for File { | |
fn unfolded_lines(self) -> UnfoldedLinesIterator<'a> { | |
UnfoldedLinesIterator { | |
iterator: Box::new(FileLinesIteratorWrapper { | |
iterator: BufReader::new(self).lines() | |
}) | |
} | |
} | |
} | |
impl<'a> UnfoldedLines<'a> for &'a str { | |
fn unfolded_lines(self) -> UnfoldedLinesIterator<'a> { | |
UnfoldedLinesIterator { | |
iterator: Box::new(StringLinesIteratorWrapper { | |
iterator: self.lines() | |
}) | |
} | |
} | |
} | |
fn parse_vevent(iterator: &mut UnfoldedLinesIterator) { | |
for l in iterator { | |
println!("Line in file {}", l); | |
} | |
} | |
fn main() { | |
let f = File::open("/home/filippo/test_calendar").unwrap(); | |
for l in f.unfolded_lines() { | |
println!("Line in file {}", l); | |
} | |
let c = "Hello\nWorld\n"; | |
for l in c.unfolded_lines() { | |
println!("Line {}", l); | |
} | |
parse_vevent(&mut c.unfolded_lines()); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment