Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #![allow(dead_code)]
- extern crate libc; // 0.2.62
- use std::mem::size_of;
- struct Vector<T> {
- length: usize,
- capacity: usize,
- ptr: Option<*mut T>
- }
- impl<T> Vector<T> {
- pub fn new()->Self{
- Vector {
- length: 0,
- capacity: 0,
- ptr: None //null ptr
- }
- }
- fn grow(&mut self, n:usize){
- self.capacity += n;
- let new_ptr = unsafe { libc::malloc(size_of::<T>()*self.capacity) as *mut T };
- unsafe {
- if let Some(ptr) = self.ptr {
- std::ptr::copy(ptr, new_ptr, self.length);
- libc::free(ptr as *mut libc::c_void);
- }
- }
- std::mem::swap(&mut self.ptr, &mut Some(new_ptr));
- }
- unsafe fn grow_to(&mut self, new_capacity: usize) {
- self.grow(new_capacity - self.capacity);
- }
- pub fn push(&mut self, item:T){
- if self.capacity <= self.length {
- unsafe {
- self.grow_to(self.capacity + 1);
- }
- }
- let ptr = self.ptr.unwrap();
- let slice = unsafe { std::slice::from_raw_parts_mut(ptr, self.capacity) };
- slice[self.length] = item;
- self.length+=1;
- }
- pub fn get(&self, i:usize)->&T {
- let slice = unsafe {
- std::slice::from_raw_parts(self.ptr.unwrap(), self.length)
- };
- &slice[i]
- }
- }
- fn main() {
- let mut vector = Vector::new();
- for i in 0..1000 {
- vector.push(i*5);
- }
- println!("{}", vector.get(50));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement