crb_agent/
context.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use crate::address::{Address, AddressJoint};
use crate::agent::Agent;
use crate::performers::Next;
use crb_runtime::{Context, Controller, ManagedContext};
use derive_more::{Deref, DerefMut};

pub trait AgentContext<T: Agent>: Context<Address = Address<T>> {
    fn session(&mut self) -> &mut AgentSession<T>;
}

#[derive(Deref, DerefMut)]
pub struct AgentSession<T: Agent> {
    pub controller: Controller,
    pub next_state: Option<Next<T>>,
    pub joint: AddressJoint<T>,
    #[deref]
    #[deref_mut]
    pub address: Address<T>,
}

impl<T: Agent> AgentSession<T> {
    pub fn joint(&mut self) -> &mut AddressJoint<T> {
        &mut self.joint
    }

    pub fn do_next(&mut self, next_state: Next<T>) {
        self.next_state = Some(next_state);
    }
}

impl<T: Agent> Default for AgentSession<T> {
    fn default() -> Self {
        let controller = Controller::default();
        let (address, joint) = AddressJoint::new_pair();
        Self {
            controller,
            next_state: None,
            joint,
            address,
        }
    }
}

impl<T: Agent> Context for AgentSession<T> {
    type Address = Address<T>;

    fn address(&self) -> &Self::Address {
        &self.address
    }
}

impl<T: Agent> ManagedContext for AgentSession<T> {
    fn controller(&mut self) -> &mut Controller {
        &mut self.controller
    }

    fn shutdown(&mut self) {
        self.joint.close();
    }
}

impl<T: Agent> AgentContext<T> for AgentSession<T> {
    fn session(&mut self) -> &mut AgentSession<T> {
        self
    }
}