Actor

Struct Actor 

Source
pub struct Actor<T> { /* private fields */ }
Expand description

coroutine based Actor.

The type Actor<T> wraps T into an Actor. You can send message to the actor by calling it’s call method. You can run a closure synchronously with the actor internal state by calling it’s with method.

§Examples

use may_actor::Actor;

let a = Actor::new(40);
a.call(|me| *me += 2);
a.with(|me| assert_eq!(*me, 42));

Implementations§

Source§

impl<T> Actor<T>

Source

pub fn new(actor: T) -> Self

create an actor by consuming the actual actor implementation

Examples found in repository?
examples/hello_world.rs (line 5)
3fn main() {
4    struct HelloActor(u32);
5    let a = Actor::new(HelloActor(0));
6
7    a.call(|me| {
8        me.0 = 10;
9        println!("hello world");
10    });
11    // the view would wait previous messages process done
12    a.with(|me| println!("actor value is {}", me.0));
13}
More examples
Hide additional examples
examples/pi.rs (line 77)
55fn pi_actor() -> f64 {
56    const WORKS: usize = TOTAL_NUM / WORK_LOAD;
57
58    struct Worker;
59    impl Worker {
60        fn work(&self, master: Actor<Master>, start: usize, end: usize) {
61            let data = calc_work(start, end);
62            master.call(move |me| me.recv_data(data));
63        }
64    }
65
66    struct Master {
67        pi: f64,
68        count: usize,
69        tx: mpsc::Sender<f64>,
70    }
71
72    impl Master {
73        fn start(&self) {
74            // create the worker actors
75            let mut workers = Vec::with_capacity(ACTOR_NUMBER);
76            for _ in 0..ACTOR_NUMBER {
77                workers.push(Actor::new(Worker));
78            }
79
80            // send work load to workers
81            let mut start = 0;
82            for i in 0..WORKS {
83                let end = start + WORK_LOAD;
84                let master = unsafe { Actor::from(self) };
85                workers[i % ACTOR_NUMBER].call(move |me| me.work(master, start, end));
86                start = end;
87            }
88        }
89
90        fn recv_data(&mut self, data: f64) {
91            self.pi += data;
92            self.count += 1;
93            if self.count == WORKS {
94                self.tx.send(self.pi).unwrap();
95            }
96        }
97    }
98
99    let (tx, rx) = mpsc::channel();
100
101    // create the master actor
102    let master = Actor::new(Master {
103        pi: 0.0,
104        count: 0,
105        tx: tx,
106    });
107
108    master.call(|me| me.start());
109
110    rx.recv().unwrap() * 4.0
111}
Source

pub fn drive_new<F>(data: T, f: F) -> Self
where F: FnOnce(DriverActor<T>) + Send + 'static, T: Send + 'static,

create an actor with a driver coroutine running in background when all actor instances got dropped, the driver coroutine would be cancelled

Source

pub unsafe fn from(inner: &T) -> Self

convert from inner ref to actor

§Safety

only valid if &Tis coming from an actor. normally this is used to convert &self to Actor<T>

Examples found in repository?
examples/pi.rs (line 84)
73        fn start(&self) {
74            // create the worker actors
75            let mut workers = Vec::with_capacity(ACTOR_NUMBER);
76            for _ in 0..ACTOR_NUMBER {
77                workers.push(Actor::new(Worker));
78            }
79
80            // send work load to workers
81            let mut start = 0;
82            for i in 0..WORKS {
83                let end = start + WORK_LOAD;
84                let master = unsafe { Actor::from(self) };
85                workers[i % ACTOR_NUMBER].call(move |me| me.work(master, start, end));
86                start = end;
87            }
88        }
Source

pub fn call<F>(&self, f: F)
where F: FnOnce(&mut T) + Send + 'static, T: Send + 'static,

send the actor a ‘message’ by a closure.

the closure would get the &mut T as parameter, so that you can manipulate its internal state.

the raw actor type must be Send and 'static so that it can be used by multi threads.

the closure would be executed asynchronously

Examples found in repository?
examples/pi.rs (line 62)
55fn pi_actor() -> f64 {
56    const WORKS: usize = TOTAL_NUM / WORK_LOAD;
57
58    struct Worker;
59    impl Worker {
60        fn work(&self, master: Actor<Master>, start: usize, end: usize) {
61            let data = calc_work(start, end);
62            master.call(move |me| me.recv_data(data));
63        }
64    }
65
66    struct Master {
67        pi: f64,
68        count: usize,
69        tx: mpsc::Sender<f64>,
70    }
71
72    impl Master {
73        fn start(&self) {
74            // create the worker actors
75            let mut workers = Vec::with_capacity(ACTOR_NUMBER);
76            for _ in 0..ACTOR_NUMBER {
77                workers.push(Actor::new(Worker));
78            }
79
80            // send work load to workers
81            let mut start = 0;
82            for i in 0..WORKS {
83                let end = start + WORK_LOAD;
84                let master = unsafe { Actor::from(self) };
85                workers[i % ACTOR_NUMBER].call(move |me| me.work(master, start, end));
86                start = end;
87            }
88        }
89
90        fn recv_data(&mut self, data: f64) {
91            self.pi += data;
92            self.count += 1;
93            if self.count == WORKS {
94                self.tx.send(self.pi).unwrap();
95            }
96        }
97    }
98
99    let (tx, rx) = mpsc::channel();
100
101    // create the master actor
102    let master = Actor::new(Master {
103        pi: 0.0,
104        count: 0,
105        tx: tx,
106    });
107
108    master.call(|me| me.start());
109
110    rx.recv().unwrap() * 4.0
111}
More examples
Hide additional examples
examples/hello_world.rs (lines 7-10)
3fn main() {
4    struct HelloActor(u32);
5    let a = Actor::new(HelloActor(0));
6
7    a.call(|me| {
8        me.0 = 10;
9        println!("hello world");
10    });
11    // the view would wait previous messages process done
12    a.with(|me| println!("actor value is {}", me.0));
13}
Source

pub fn with<R, F>(&self, f: F) -> R
where F: FnOnce(&mut T) -> R + Send, T: Send, R: Send,

execute a closure in the actor’s coroutine context and wait for the result.

This is a sync version of call method, it will block until finished, panic will be propagate to the caller’s context. You can use this method to monitor the internal state

Examples found in repository?
examples/hello_world.rs (line 12)
3fn main() {
4    struct HelloActor(u32);
5    let a = Actor::new(HelloActor(0));
6
7    a.call(|me| {
8        me.0 = 10;
9        println!("hello world");
10    });
11    // the view would wait previous messages process done
12    a.with(|me| println!("actor value is {}", me.0));
13}
Source

pub fn key(&self) -> usize

get the heap address as key, unique for each actor can be used to compare if two actors are the same

Trait Implementations§

Source§

impl<T> Clone for Actor<T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug> Debug for Actor<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Send for Actor<T>

Auto Trait Implementations§

§

impl<T> Freeze for Actor<T>

§

impl<T> RefUnwindSafe for Actor<T>

§

impl<T> Sync for Actor<T>
where T: Send,

§

impl<T> Unpin for Actor<T>

§

impl<T> UnwindSafe for Actor<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.