-
-
Save anka-213/d0d8825ace9435341cc53f4cc3effc61 to your computer and use it in GitHub Desktop.
(un)Safe reusable buffers
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
//#![feature(question_mark)] | |
use std::ops::Deref; | |
use std::ops::DerefMut; | |
#[derive(Debug, Default)] | |
struct ReuseBuf { | |
inner: Vec<u32>, | |
used: bool | |
} | |
impl ReuseBuf { | |
pub fn new() -> ReuseBuf { | |
Default::default() | |
} | |
pub fn get_buf<'a>(& 'a mut self) -> Buf<'a> { | |
assert!(!self.used); | |
assert!(self.inner.is_empty()); | |
self.used = true; | |
Buf { inner: self } | |
} | |
} | |
#[derive(Debug)] | |
struct Buf<'a> { | |
inner: &'a mut ReuseBuf, | |
} | |
impl<'a> Deref for Buf<'a> { | |
type Target=Vec<u32>; | |
fn deref(&self) -> & Vec<u32> { | |
&self.inner.inner | |
} | |
} | |
impl<'a> DerefMut for Buf<'a> { | |
fn deref_mut(&mut self) -> &mut Vec<u32> { | |
&mut self.inner.inner | |
} | |
} | |
impl<'a> Drop for Buf<'a> { | |
fn drop(&mut self) { | |
self.inner.used = false; | |
self.inner.inner.clear(); | |
} | |
} | |
fn main2() { | |
let mut buf = ReuseBuf::new(); | |
println!("Printing stuff {:?}", buf); | |
{ | |
let ref mut b1 = *buf.get_buf(); | |
b1.push(1); | |
b1.push(2); | |
println!("Printing stuff {:?}", b1); | |
// let mut b2 = buf.get_buf(); | |
// b2.push(1); | |
// b2.push(2); | |
// println!("Printing stuff {:?}, {:?}", b2, *b2); | |
} | |
println!("Printing stuff {:?}", buf); | |
{ | |
let mut b1 = buf.get_buf(); | |
b1.push(3); | |
println!("Printing stuff {:?}, {:?}", b1, *b1); | |
} | |
println!("Printing stuff {:?}", buf); | |
} | |
fn main() {main2();} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment