Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::cell::RefCell;
- use std::rc::Rc;
- //use std::ops::{Deref, DerefMut};
- use std::clone::Clone;
- struct SimContext {
- modules: Vec<Module<ModuleInterface>>
- }
- impl SimContext {
- fn new() -> Self {
- SimContext {
- modules: Vec::new()
- }
- }
- }
- trait ModuleInterface {
- fn get_submodules(&mut self) -> Vec<Module<ModuleInterface>> {
- Vec::new()
- }
- }
- trait Elaborate: ModuleInterface + Sized {
- fn elaborate() -> Module<Self>;
- }
- #[derive(Debug)]
- struct Module<T>(Rc<RefCell<T>>) where T: ModuleInterface + ?Sized;
- impl<T> Module<T> where T: ModuleInterface + Sized {
- fn new(t: T) -> Self {
- Module(Rc::new(RefCell::new(t)))
- }
- }
- impl<T> Clone for Module<T> where T: ModuleInterface + ?Sized {
- fn clone(&self) -> Module<T> {
- Module(self.0.clone())
- }
- }
- impl<T> ModuleInterface for Module<T> where T: ModuleInterface {
- fn get_submodules(&mut self) -> Vec<Module<ModuleInterface>> {
- (*self.0).borrow_mut().get_submodules()
- }
- }
- impl<T> From<Module<T>> for Module<ModuleInterface> where T: ModuleInterface + 'static {
- fn from(t: Module<T>) -> Module<ModuleInterface> {
- Module(t.0)
- }
- }
- ///// ----- Tests
- struct T2 {
- }
- impl ModuleInterface for T2 {}
- impl Elaborate for T2 {
- fn elaborate() -> Module<Self> {
- Module::new(T2 {})
- }
- }
- struct T1 {
- sub: Module<T2>,
- id: usize,
- }
- impl ModuleInterface for T1 {
- fn get_submodules(&mut self) -> Vec<Module<ModuleInterface>> {
- let mut local = Vec::new();
- {
- let mut vec = self.sub.get_submodules();
- local.append(&mut vec);
- local.push(self.sub.clone().into());
- }
- local
- }
- }
- impl Elaborate for T1 {
- fn elaborate() -> Module<Self> {
- let m = T1 {
- sub: Elaborate::elaborate(),
- id: 0
- };
- Module::new(m)
- }
- }
- fn main() {
- let mut simctx = SimContext::new();
- let mut b = T1::elaborate();
- println!("{}", b.get_submodules().len());
- simctx.modules.append(&mut b.get_submodules());
- simctx.modules.push(b.clone().into());
- println!("{}", (*b.0).borrow().id);
- println!("{}", (*b.0).borrow().id);
- println!("{}", simctx.modules.len());
- }
- //////////////// ---------------------------------------------------------------
- /*
- trait Dispatcher {
- fn dispatch(&self);
- }
- struct MethodDispatcher<T> {
- object: Rc<RefCell<T>>,
- method: Box<Fn (&mut T)>
- }
- impl<T> Dispatcher for MethodDispatcher<T> {
- fn dispatch(&self) {
- let mut object = self.object.borrow_mut();
- (*self.method)(&mut object);
- }
- }
- */
Add Comment
Please, Sign In to add comment