Created
February 4, 2018 03:28
-
-
Save BartMassey/d2a93f81f4f3d22587bff1a846e73c3a to your computer and use it in GitHub Desktop.
Memory safety demo in Rust by Will Chrichton. Compile with `rustc -o memsafe memsafe.rs`
This file contains 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
// http://willcrichton.net/notes/rust-memory-safety/ | |
// Modified by Bart Massey 2018-02-03 | |
#![feature(alloc, allocator_api)] | |
extern crate alloc; | |
use std::slice; | |
use std::heap::{Heap, Alloc}; | |
use alloc::allocator::Layout; | |
struct Vec2 { | |
data: Box<[isize]>, | |
length: usize, | |
capacity: usize | |
} | |
fn new() -> Vec2 { | |
Vec2 { | |
data: Box::new([]), | |
length: 0, | |
capacity: 0 | |
} | |
} | |
fn push(v: &mut Vec2, n: isize) { | |
while v.length >= v.capacity { | |
let new_capacity = | |
if v.capacity == 0 { | |
1 | |
} else { | |
v.capacity * 2 | |
}; | |
let mut new_data = unsafe { | |
let ptr = Heap::default() | |
.alloc(Layout::array::<isize>(new_capacity).unwrap()) | |
.unwrap() as *mut isize; | |
Box::from_raw(slice::from_raw_parts_mut(ptr, new_capacity)) | |
}; | |
for i in 0..v.length { | |
new_data[i] = v.data[i]; | |
} | |
v.data = new_data; | |
v.capacity = new_capacity; | |
} | |
v.data[v.length] = n; | |
v.length += 1; | |
} | |
fn main() { | |
let mut vec = new(); | |
push(&mut vec, 107); | |
let n = vec.data[0]; | |
push(&mut vec, 110); | |
println!("{}", n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment