Created
December 13, 2018 10:53
-
-
Save geekoff7/4d5cec65ddaf3655dc07f27d6dd94872 to your computer and use it in GitHub Desktop.
rust string reader
This file contains hidden or 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::slice::Iter; | |
pub struct StringReader<'a> { | |
iter: Iter<'a, u8>, | |
len: usize, | |
pos: usize, | |
} | |
impl<'a> StringReader<'a> { | |
pub fn new(data: &'a str) -> Self { | |
Self { | |
iter: data.as_bytes().iter(), | |
len: data.len(), | |
pos: 0, | |
} | |
} | |
pub fn read_line(&mut self) -> Option<String> { | |
let mut result = String::new(); | |
if self.pos >= self.len { | |
return None; | |
} | |
for _ in self.pos..self.len { | |
self.pos += 1; | |
let c = *self.iter.next().unwrap() as char; | |
result.push(c); | |
if c == '\n' { | |
break; | |
} | |
} | |
return Some(result.trim().to_owned()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment