Created
April 23, 2015 05:32
-
-
Save isagalaev/0bcc45df34f0826abda6 to your computer and use it in GitHub Desktop.
lifetime parameters
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
const BUFSIZE: usize = 64 * 1024; | |
use std::fs::File; | |
use std::io::Read; | |
struct Lexer<'a> { | |
buf: & 'a mut [u8; BUFSIZE], | |
len: usize, | |
pos: usize, | |
f: File, | |
} | |
impl<'a> Iterator for Lexer<'a> { | |
type Item = &'a [u8]; | |
fn next(&mut self) -> Option<&'a [u8]> { | |
if self.len == 0 { | |
self.f.read(self.buf).ok().expect("Error reading file"); | |
} | |
while self.pos < self.len && self.buf[self.pos] == b' ' { | |
self.pos += 1; | |
} | |
let start = self.pos; | |
while self.pos < self.len && self.buf[self.pos] != b' ' { | |
self.pos += 1; | |
} | |
if start < self.pos { | |
Some(&self.buf[start..self.pos]) | |
} else { | |
None | |
} | |
} | |
} | |
fn main() { | |
let lexer = Lexer { | |
buf: &mut[0; BUFSIZE], | |
len: 0, | |
pos: 0, | |
f: File::open("test.txt").ok().unwrap(), | |
}; | |
for chunk in lexer { | |
println!("{:?}", chunk); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment