Skip to content

Instantly share code, notes, and snippets.

Created September 24, 2016 18:07
Show Gist options
  • Save anonymous/e7b99487c9e53217230cd8a3271fb3dc to your computer and use it in GitHub Desktop.
Save anonymous/e7b99487c9e53217230cd8a3271fb3dc to your computer and use it in GitHub Desktop.
Shared via Rust Playground
//#![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