Skip to content

Instantly share code, notes, and snippets.

@sethdusek
Created June 23, 2016 01:21
Show Gist options
  • Save sethdusek/a0f9309fbd777606a37c89b0be1f7ac2 to your computer and use it in GitHub Desktop.
Save sethdusek/a0f9309fbd777606a37c89b0be1f7ac2 to your computer and use it in GitHub Desktop.
#![feature(alloc, heap_api)]
extern crate alloc;
use std::ptr;
use alloc::heap;
use std::mem::{size_of, align_of};
struct Vecr<T> {
ptr: *mut T,
len: usize,
capacity: usize
}
fn malloc<T>(size: usize) -> *mut T {
unsafe { heap::allocate(size, align_of::<T>()) as *mut T }
}
fn realloc<T>(ptr: *mut T, old: usize, size: usize) -> *mut T {
unsafe { heap::reallocate(ptr as *mut u8, old, size, align_of::<T>()) as *mut T }
}
fn free<T>(ptr: *mut T, size: usize) {
unsafe { heap::deallocate(ptr as *mut u8, size, align_of::<T>()) }
}
impl <T> Vecr<T> {
fn new() -> Vecr<T> {
Vecr {
ptr: heap::EMPTY as *mut T,
len: 0,
capacity: 0
}
}
fn idx(&self, i: usize) -> &T {
assert!(i<self.len);
unsafe { &*self.ptr.offset(i as isize) }
}
fn push(&mut self, val: T) {
if self.capacity == 0 {
self.ptr = malloc(size_of::<T>());
self.capacity = 1;
}
self.len+=1;
if self.len > self.capacity {
self.ptr = realloc(self.ptr, self.capacity*size_of::<T>(), self.capacity*size_of::<T>()*2);
self.capacity = self.capacity*2
}
unsafe { ptr::write(self.ptr.offset(self.len as isize-1), val) }
}
fn pop(&mut self) -> Option<T> {
let new_len = self.len-1;
if self.len==0 { None }
else {
println!("len {}", self.len);
self.len-=1;
unsafe { Some(ptr::read(self.ptr.offset(self.len as isize))) }
}
}
fn len(&self) -> usize {
self.len
}
}
/*impl<T> std::ops::Drop for Vecr<T> {
fn drop(&mut self) {
free(self.ptr, self.capacity*size_of::<T>())
}
}*/
fn main() {
let mut vecr = Vecr::new();
vecr.push(5);
vecr.push(10);
vecr.push(15);
println!("here?");
for _ in 0..5 {
println!("{:?}", vecr.pop());
}
println!("maybe here!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment