I'm trying to write a little buffer-thing for parsing so I can pull records off the front of as I parse them out, ideally without making any copies and just transferring ownership of chunks of the front of the buffer off as I run. Here's my implementation:
struct BufferThing {
buf: Vec<u8>,
}
impl BufferThing {
fn extract(&mut self, size: usize) -> Vec<u8> {
assert!(size <= self.buf.len());
let remaining: usize = self.buf.len() - size;
let ptr: *mut u8 = self.buf.as_mut_ptr();
unsafe {
self.buf = Vec::from_raw_parts(ptr.offset(size as isize), remaining, remaining);
Vec::from_raw_parts(ptr, size, size)
}
}
}
This compiles, but panics with a signal: 11, SIGSEGV: invalid memory reference
as it starts running. This is mostly the same code as the example in the Nomicon, but I'm trying to do it on Vec
's and I'm trying to split a field instead of the object itself.
Is it possible to do this without copying out one of the Vec
s? And is there some section of the Nomicon or other documentation that explains why I'm blowing everything up in the unsafe
block?
unsafe
code if you cannot explain why it is indeed safe. – Soissons