Last active
February 6, 2019 16:09
-
-
Save coolreader18/db055d2c8a15d920147047750cd3ce3d to your computer and use it in GitHub Desktop.
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
use std::rc::*; | |
pub enum RefCount<T> { | |
Rc(Rc<T>), | |
Weak(Weak<T>), | |
} | |
impl<T> RefCount<T> { | |
pub fn new_rc(value: T) -> RefCount<T> { | |
RefCount::Rc(Rc::new(value)) | |
} | |
pub fn downgrade(&self) -> Weak<T> { | |
match self { | |
RefCount::Rc(ref rc) => Rc::downgrade(rc), | |
RefCount::Weak(ref weak) => weak.clone(), | |
} | |
} | |
pub fn downgrade_self(&mut self) -> Weak<T> { | |
let weak = match self { | |
RefCount::Rc(ref rc) => Rc::downgrade(rc), | |
RefCount::Weak(ref weak) => return weak.clone(), | |
}; | |
*self = RefCount::Weak(weak.clone()); | |
weak | |
} | |
pub fn upgrade(&self) -> Option<Rc<T>> { | |
match self { | |
RefCount::Rc(ref rc) => Some(rc.clone()), | |
RefCount::Weak(ref weak) => Weak::upgrade(weak), | |
} | |
} | |
pub fn upgrade_self(&mut self) -> Option<Rc<T>> { | |
let rc = match self { | |
RefCount::Rc(ref rc) => return Some(rc.clone()), | |
RefCount::Weak(ref weak) => Weak::upgrade(weak)?, | |
}; | |
*self = RefCount::Rc(rc.clone()); | |
Some(rc) | |
} | |
} | |
impl<T> Clone for RefCount<T> { | |
fn clone(&self) -> Self { | |
match self { | |
RefCount::Rc(ref rc) => RefCount::Rc(rc.clone()), | |
RefCount::Weak(ref weak) => RefCount::Weak(weak.clone()), | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment