Last active
January 9, 2017 23:21
-
-
Save hroi/5307e020599b57fc77a7fc724de0a2a9 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 struct RawVec<T> { | |
mem: *mut T, | |
cap: usize, | |
} | |
impl<T> RawVec<T> { | |
pub fn with_capacity(cap: usize) -> RawVec<T> { | |
let mut vec = Vec::<T>::with_capacity(cap); | |
let ptr = vec.as_mut_ptr(); | |
mem::forget(vec); | |
RawVec { | |
mem: ptr, | |
cap: cap, | |
} | |
} | |
pub fn cap(&self) -> usize { | |
self.cap | |
} | |
pub fn ptr(&self) -> *mut T { | |
self.mem | |
} | |
pub fn reserve(&mut self, used_cap: usize, extra_cap: usize) { | |
let mut vec = unsafe { Vec::<T>::from_raw_parts(self.mem, used_cap, self.cap) }; | |
vec.reserve(extra_cap); | |
self.cap = vec.capacity(); | |
self.mem = vec.as_mut_ptr(); | |
mem::forget(vec); | |
} | |
} | |
impl<T> Drop for RawVec<T> { | |
fn drop(&mut self) { | |
unsafe { | |
Vec::from_raw_parts(self.mem, 0, self.cap); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment