I have the next code:
struct Tokenizer {
reader: BufReader<File>,
buf: Vec<u8>,
token: String
}
impl Tokenizer {
fn new(path: &PathBuf) -> Tokenizer {
let file = File::open(path).expect("Unable to open file!");
Tokenizer {
reader: BufReader::new(file),
buf: Vec::<u8>::new(),
token: String::new()
}
}
fn next(&mut self) -> bool {
if self.buf.len() == 0 {
if self.reader.read_until(b'\n', &mut self.buf)
.expect("Unable to read file") == 0 {
return false;
}
}
let s = String::from_utf8(self.buf).expect("Unable to read file");
let mut start: i8 = -1;
let mut end: i8 = -1;
for (i, c) in s.char_indices() {
if start == -1 {
if !c.is_whitespace() {
start = i as i8;
}
} else {
if c.is_whitespace() {
end = i as i8;
}
}
}
self.token = s.chars().skip(start as usize).take((end - start) as usize).collect();
self.buf = s.into_bytes();
self.buf.clear();
return true;
}
}
But it doesn't work due to error:
error[E0507]: cannot move out of `self.buf` which is behind a mutable reference
--> src\parser.rs:28:35
|
28 | let s = String::from_utf8(self.buf).expect("Unable to read file");
| ^^^^^^^^ move occurs because `self.buf` has type `std::vec::Vec<u8>`, which does not implement the `Copy` trait
I've read similar questions that advice to use swap
but I didn't get how it will help me. How to fix this error and why does it not compile?