Advertisement
Guest User

Untitled

a guest
Feb 9th, 2023
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.06 KB | None | 0 0
  1. pub struct Scanner<R> {
  2.     reader: R,
  3.     buf_str: Vec<u8>,
  4.     offset: usize,
  5. }
  6.  
  7. impl<R: BufRead> Scanner<R> {
  8.     pub fn new(reader: R) -> Self {
  9.         Self {
  10.             reader,
  11.             buf_str: vec![],
  12.             offset: 0,
  13.         }
  14.     }
  15.  
  16.     pub fn token<T: std::str::FromStr>(&mut self) -> T {
  17.         loop {
  18.             if self.offset < self.buf_str.len() {
  19.                 let pos = self.buf_str[self.offset..]
  20.                     .iter()
  21.                     .position(|&c| c == b' ')
  22.                     .unwrap_or(self.buf_str.len() - self.offset);
  23.  
  24.                 let token = std::str::from_utf8(&self.buf_str[self.offset..self.offset + pos])
  25.                     .expect("non utf8")
  26.                     .trim();
  27.  
  28.                 self.offset += pos + 1;
  29.                 return token.parse().ok().expect("Failed parse");
  30.             }
  31.             self.buf_str.clear();
  32.             self.reader
  33.                 .read_until(b'\n', &mut self.buf_str)
  34.                 .expect("Failed read");
  35.             self.offset = 0;
  36.         }
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement