Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::rc::{Rc, Weak};
- use std::cell::RefCell;
- use std::fmt;
- type DepReference = Rc<RefCell<Box<Dependency>>>;
- type DepWeak = Weak<RefCell<Box<Dependency>>>;
- trait Dependency {
- fn do_it(&mut self, i: &mut i32);
- fn name(&self) -> String;
- }
- impl fmt::Debug for Dependency {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "Dependency<{}>", self.name())
- }
- }
- struct Dependent {
- data: i32,
- dependency: DepWeak
- }
- impl fmt::Debug for Dependent {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "Dependent{{ data: {}, dependency: {:?} }}",
- self.data, self.dependency)
- }
- }
- impl Dependent {
- fn new(i: i32, dependency: DepWeak) -> Self {
- Dependent {
- data: i,
- dependency
- }
- }
- fn do_it(&mut self) {
- let rc: DepReference = self.dependency.upgrade().unwrap();
- (*rc).borrow_mut().do_it(&mut self.data);
- }
- }
- impl Drop for Dependent {
- fn drop(&mut self) {
- println!("Drop {:?}!", self);
- }
- }
- struct DependencyA {
- info: i32
- }
- struct DependencyB {
- info: i32
- }
- impl Dependency for DependencyA {
- fn do_it(&mut self, i: &mut i32) {
- self.info += 1;
- *i += self.info;
- }
- fn name(&self) -> String {
- "DependencyA".to_string()
- }
- }
- impl Drop for DependencyA {
- fn drop(&mut self) {
- println!("Drop DependencyA!");
- }
- }
- impl Dependency for DependencyB {
- fn do_it(&mut self, i: &mut i32) {
- self.info += 7;
- *i += self.info;
- }
- fn name(&self) -> String {
- "DependencyB".to_string()
- }
- }
- impl Drop for DependencyB {
- fn drop(&mut self) {
- println!("Drop DependencyB!");
- }
- }
- struct Container {
- data: Vec<DepReference>,
- content: Vec<Dependent>
- }
- impl Container {
- fn new() -> Container {
- let data: Vec<DepReference> = Vec::new();
- let content: Vec<Dependent> = Vec::new();
- Container { data, content }
- }
- fn add(&mut self, d: Box<Dependency>, i: i32) {
- let dp = Rc::new(RefCell::new(d));
- self.content.push(Dependent::new(i, Rc::downgrade(&dp)));
- self.data.push(dp);
- }
- fn do_it(&mut self) {
- for item in &mut self.content {
- item.do_it();
- }
- }
- }
- impl Drop for Container {
- fn drop(&mut self) {
- println!("Drop Container!");
- }
- }
- fn main() {
- let mut c = Container::new();
- c.add(Box::new(DependencyA{ info: 666 }), 25);
- c.add(Box::new(DependencyB{ info: 777 }), 37);
- c.do_it();
- }
Add Comment
Please, Sign In to add comment