Created
December 4, 2020 17:52
-
-
Save sigmaSd/4d5cb1b0302f6d2176f416c73d282c8f to your computer and use it in GitHub Desktop.
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
pub fn read_until_bytes<R: std::io::BufRead + ?Sized>( | |
r: &mut R, | |
delim: &[u8], | |
buffer: &mut Vec<u8>, | |
) -> std::io::Result<usize> { | |
let mut read = 0; | |
let mut count = 0; | |
loop { | |
let (done, used) = { | |
let available = match r.fill_buf() { | |
Ok(n) => n, | |
Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue, | |
Err(e) => return Err(e), | |
}; | |
match available.iter().position(|b| *b == delim[count]) { | |
Some(i) => { | |
buffer.extend_from_slice(&available[..=i]); | |
count += 1; | |
if count == delim.len() { | |
(true, i + 1) | |
} else { | |
(false, i + 1) | |
} | |
} | |
None => { | |
count = 0; | |
buffer.extend_from_slice(available); | |
(false, available.len()) | |
} | |
} | |
}; | |
r.consume(used); | |
read += used; | |
if done || used == 0 { | |
return Ok(read); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment