Trait dep_obj::DepType[][src]

pub trait DepType: Debug {
    type Id: ComponentId;
}
Expand description

A dependency type. Use the dep_type or the dep_type_with_builder macro to create a type implementing this trait.

Examples

use components_arena::{Arena, Component, NewtypeComponentId, Id};
use dep_obj::{dep_obj, dep_type};
use dep_obj::binding::{Bindings, Binding1};
use dyn_context::state::{State, StateExt};
use macro_attr_2018::macro_attr;
use std::any::{Any, TypeId};

dep_type! {
    #[derive(Debug)]
    pub struct MyDepType in MyDepTypeId {
        prop_1: bool = false,
        prop_2: i32 = 10,
    }
}

macro_attr! {
    #[derive(Component!, Debug)]
    struct MyDepTypePrivateData {
        dep_data: MyDepType,
    }
}

macro_attr! {
    #[derive(NewtypeComponentId!, Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
    pub struct MyDepTypeId(Id<MyDepTypePrivateData>);
}

pub struct MyApp {
    bindings: Bindings,
    my_dep_types: Arena<MyDepTypePrivateData>,
    res: i32,
}

impl State for MyApp {
    fn get_raw(&self, ty: TypeId) -> Option<&dyn Any> {
        if ty == TypeId::of::<Bindings>() {
            Some(&self.bindings)
        } else if ty == TypeId::of::<MyApp>() {
            Some(self)
        } else {
            None
        }
    }

    fn get_mut_raw(&mut self, ty: TypeId) -> Option<&mut dyn Any> {
        if ty == TypeId::of::<Bindings>() {
            Some(&mut self.bindings)
        } else if ty == TypeId::of::<MyApp>() {
            Some(self)
        } else {
            None
        }
    }
}

impl MyDepTypeId {
    pub fn new(state: &mut dyn State) -> MyDepTypeId {
        let app: &mut MyApp = state.get_mut();
        app.my_dep_types.insert(|id| (MyDepTypePrivateData {
            dep_data: MyDepType::new_priv()
        }, MyDepTypeId(id)))
    }

    pub fn drop_my_dep_type(self, state: &mut dyn State) {
        self.drop_bindings_priv(state);
        let app: &mut MyApp = state.get_mut();
        app.my_dep_types.remove(self.0);
    }

    dep_obj! {
        pub fn obj(self as this, app: MyApp) -> MyDepType {
            if mut {
                &mut app.my_dep_types[this.0].dep_data
            } else {
                &app.my_dep_types[this.0].dep_data
            }
        }
    }
}

fn main() {
    let app = &mut MyApp {
        bindings: Bindings::new(),
        my_dep_types: Arena::new(),
        res: 0,
    };
    let id = MyDepTypeId::new(app);
    let res = Binding1::new(&mut app.bindings, (), |(), (_, x)| Some(x));
    res.set_source_1(app, &mut MyDepType::PROP_2.source(id.obj()));
    res.set_target_fn(app, (), |app, (), value| {
        let app: &mut MyApp = app.get_mut();
        app.res = value;
    });
    assert_eq!(app.res, 10);
    MyDepType::PROP_2.set_distinct(app, id.obj(), 5);
    assert_eq!(app.res, 5);
    id.drop_my_dep_type(app);
    res.drop_binding(app);
}

Associated Types

Implementors