Skip to content

Instantly share code, notes, and snippets.

@sajattack
Last active November 22, 2017 19:05
Show Gist options
  • Save sajattack/ea47a7be9704c93ea60114fc5423110b to your computer and use it in GitHub Desktop.
Save sajattack/ea47a7be9704c93ea60114fc5423110b to your computer and use it in GitHub Desktop.
extern crate libc;
extern crate core;
use core::mem;
use core::ptr;
use core::ptr::null_mut;
use core::str;
/// Implements an `Iterator` which returns on either newline or EOF.
pub struct RawLineBuffer {
fd: usize,
cur: usize,
read: usize,
buf: [u8; 8 * 1024]
}
impl RawLineBuffer {
pub fn new(fd: usize) -> RawLineBuffer {
RawLineBuffer {
fd: fd,
cur: 0,
read: 0,
buf: unsafe { mem::uninitialized() },
}
}
}
impl Iterator for RawLineBuffer {
type Item = Result<Box<str>, i32>;
fn next(&mut self) -> Option<Self::Item> {
if self.cur != 0 && self.read != 0 {
if let Some(mut pos) = self.buf[self.cur..self.read].iter().position(|&x| x == b'\n') {
pos += self.cur;
let line = unsafe {str::from_utf8_unchecked(&self.buf[self.cur..pos])};
let boxed_array: Box<[u8]> = Box::from(line.as_bytes());
let boxed_line: Box<str> = unsafe {mem::transmute(boxed_array)};
self.cur = pos;
return Some(Ok(boxed_line));
}
let mut temp: [u8; 8 * 1024] = unsafe { mem::uninitialized() };
unsafe {
ptr::copy(self.buf[self.cur..].as_ptr(), temp.as_mut_ptr(), self.read);
ptr::swap(self.buf.as_mut_ptr(), temp.as_mut_ptr());
};
self.read -= self.cur;
self.cur = 0;
}
let cbuf: *mut libc::c_void = &mut self.buf[self.cur..] as *mut _ as *mut libc::c_void;
let end: usize;
unsafe {
end = match libc::read(self.fd as i32, cbuf, self.buf.len()) {
0 => return None,
read => {
self.read += read as usize;
self.buf[..self.read].iter().position(|&x| x == b'\n').unwrap_or(0)
}
};
}
self.cur = end;
let line = unsafe {str::from_utf8_unchecked(&self.buf[..end])};
let boxed_array: Box<[u8]> = Box::from(line.as_bytes());
let boxed_line: Box<str> = unsafe {mem::transmute(boxed_array)};
Some(Ok(boxed_line))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment