Created
September 15, 2019 15:53
-
-
Save Skarlett/f6a2cda3c63d7c5a9a1efcd254534f4c to your computer and use it in GitHub Desktop.
A quick rust program to show how out-of-bounds compiling works in rust.
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
#[derive(Debug)] | |
struct Parent<T> { | |
children: Vec<T>, | |
} | |
impl<T> Parent<T> { | |
fn get(&self, index: usize) -> Option<&T> { | |
match self.children.get(index) { | |
Some(c) => Some(c), | |
None => None | |
} | |
} | |
} | |
impl<T> Default for Parent<T> where T: Default { | |
fn default() -> Self { | |
Self { | |
children: { | |
let mut x: Vec<T> = Vec::new(); | |
let child: T = T::default(); | |
x.push(child); | |
x | |
} | |
} | |
} | |
} | |
// illegal self referencing struct | |
//------------------------- | |
// struct SuperHero<'a, T> { | |
// parent: Parent<T>, | |
// children_second_gen: Vec<NeedsParent<'a, T>> | |
// } | |
// | |
// struct NeedsParent<'a, T> { | |
// inner: &'a T | |
// } | |
// | |
// impl<'a, T> SuperHero<'a, T> { | |
// fn save(&self, index: usize) { | |
// match self.parent.get(index) { | |
// Some(c) => { | |
// self.children_second_gen.push(c) | |
// }, | |
// None => () | |
// } | |
// } | |
// } | |
fn main() -> Result<(), Box<std::error::Error>> { | |
// Parent produces the reference/borrow/pointer | |
let x: Parent<u64> = Parent::default(); | |
// Get the pointer/borrow/reference | |
let reference = match x.get(0) { | |
Some(y) => y, | |
None => panic!("shit") | |
}; | |
// Should be usable | |
println!("{:?}", reference); | |
println!("dropping parent"); | |
drop(x); // Borrowed data dies | |
//println!("{:?}", reference); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment