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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
//! Actor lifecycle Manager
//!
extern crate alloc;

use crate::actor::Actor;
#[cfg(not(feature = "log"))]
use crate::log;
use alloc::{string::String, sync::Arc, vec::Vec};
use core::{
    any::{Any, TypeId},
    cell::UnsafeCell,
    fmt, hint,
    mem::transmute,
    ops::{Deref, DerefMut},
    sync::atomic::{AtomicBool, AtomicUsize, Ordering},
};

/// number of all actors that counts them
/// when a new actor is created, increase it
/// and use the current number as the id of the actor
static ACTORCOUNT: AtomicUsize = AtomicUsize::new(1);

/// Actor system register for all created actor
/// it serves as a index for all living actor of the system can
/// - query/update actor info(name/inner data/etc.)
/// - push new actor to
/// - delete stopped actor from
///
/// it built upon Vec which you use for iteration/filter/etc.
///
static mut REGISTER: Register = Register { inner: Vec::new() };
/// A atomic guard to protect mutate REGISTER
/// by multiple threads concurrently
static REGISTERSEAL: AtomicBool = AtomicBool::new(false);

/// An general record of running actors
///
/// when an actor get into running,
/// A record will registered into `Register` for future
/// usage (Create/Read/Update/Delete)
///
/// and the registered `ActorRegister` will be removed
/// when the actor is closed
pub struct Register {
    inner: Vec<ActorRegister>,
}

impl Register {
    /// create an instance of Register
    pub fn new() -> &'static Self {
        unsafe { &REGISTER }
    }

    /// push an actor into REGISTER and
    /// return its guarded underlying actor
    pub fn push<A: Actor>(item: ActorRegister) -> ActorGuard<A> {
        // the underlying actor is required to be downcasted;
        let data = item.downcast_ref_cell();
        while REGISTERSEAL.load(Ordering::Acquire) {
            hint::spin_loop();
        }
        REGISTERSEAL.store(true, Ordering::Release);
        log::debug!("actor registered: {:?}", item);
        unsafe {
            REGISTER.inner.push(item);
        }
        REGISTERSEAL.store(false, Ordering::Relaxed);
        data
    }

    /// get an actor register by id
    pub fn get(id: usize) -> Option<&'static ActorRegister> {
        Self::as_ref().iter().find(|reg| reg.id() == id)
    }

    /// clear closed actor as long as
    /// - `ActorRegister.closed` marked `true`
    /// - All other `ActorGuard` copys dropped
    pub(crate) fn update() -> Vec<ActorRegister> {
        let mut items = Vec::new();
        let mut index = 0;
        // wait for `REGISTER` to be available
        while REGISTERSEAL.load(Ordering::Acquire) {
            hint::spin_loop();
        }
        // seal it to get mutable reference
        REGISTERSEAL.store(true, Ordering::Release);
        let inner = unsafe { &mut REGISTER.inner };
        while index < inner.len() {
            let item = &mut inner[index];
            if item.is_closed() && Arc::strong_count(&item.inner) == 1 {
                let item = inner.swap_remove(index);
                log::debug!("Actor Register removed: {:?}", item);
                items.push(item);
                continue;
            }
            index += 1;
        }
        REGISTERSEAL.store(false, Ordering::Release);
        items
    }

    /// get the number of all created actors
    pub fn len() -> usize {
        unsafe { &REGISTER.inner }.len()
    }

    /// take the reference of Register
    pub fn as_ref() -> &'static Vec<ActorRegister> {
        //while REGISTERSEAL.load(Ordering::Relaxed) {
        //hint::spin_loop();
        //}
        unsafe { &REGISTER.inner }
    }
}

/// A record will registered into `REGISTER` for
/// future use (Create/Read/Update/Delete)
///
/// each record contains
/// - `id`: `usize`
/// - `actor`: the type implemented [`Acotr`](Actor) trait
/// - `sealed`: `AtomicBool`, marker whether the actor is mutably borrowed or not
/// - `type_id`: the type id of the type implemented [`Acotr`](Actor) trait
/// - `message_id`: the type id of the type implemented [`Message`](crate::message::Message) trait
/// - `name`: String
/// - `closed`: `AtomicBool`, marker whether the actor is closed or not
#[derive(Debug)]
pub struct ActorRegister {
    id: usize,
    name: String,
    type_id: TypeId,
    message_id: TypeId,
    inner: Arc<UnsafeCell<dyn Any>>,
    sealed: Arc<AtomicBool>,
    closed: AtomicBool,
}

/// An guardian created when Actor gets registered
pub struct ActorGuard<A: Actor> {
    inner: Arc<UnsafeCell<A>>,
    sealed: Arc<AtomicBool>,
}

impl<A: Actor> fmt::Debug for ActorGuard<A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ActorGuard<_>")
            .field("inner", &"UnsafeCell<Actor>")
            .field("sealed", &self.sealed)
            .finish()
    }
}

impl<A: Actor> Deref for ActorGuard<A> {
    type Target = A;

    fn deref(&self) -> &Self::Target {
        let ptr = Arc::as_ptr(&self.inner);
        let actor_cell: *mut A = UnsafeCell::raw_get(ptr as *const _);
        unsafe { transmute::<*mut A, &A>(actor_cell) }
    }
}

impl<A: Actor> DerefMut for ActorGuard<A> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        let ptr = Arc::as_ptr(&self.inner);
        let actor_cell: *mut A = UnsafeCell::raw_get(ptr as *const _);
        unsafe { transmute::<*mut A, &mut A>(actor_cell) }
    }
}

/// **Safety**: since it is guardted with AtomicBool
/// for generic `A: Actor`
/// - nothing changes to the Inner data when downcasted to &A,
/// - seal the inner to deny more than one access when downcasted to &mut A
///
/// So it is safe to send &A between threads
unsafe impl Send for ActorRegister {}
/// **Safety**: since it is guardted with AtomicBool
/// for generic `A: Actor`
/// - nothing changes to the Inner data when downcasted to &A,
/// - seal the inner to deny more than one access when downcasted to &mut A
///
/// So it is safe to send &A between threads
unsafe impl Sync for ActorRegister {}

impl ActorRegister {
    /// create a Actor Register for an
    /// actor instance
    pub fn new<A>(act: A) -> Self
    where
        A: Actor,
    {
        let id = ACTORCOUNT.fetch_add(1, Ordering::Relaxed);
        Self {
            id,
            type_id: TypeId::of::<A>(),
            message_id: TypeId::of::<A::Message>(),
            name: format!("Actor-{}", id),
            inner: Arc::new(UnsafeCell::new(act)),
            sealed: Arc::new(AtomicBool::new(false)),
            closed: AtomicBool::new(false),
        }
    }

    /// the unqiue identity of the Actor
    pub fn id(&self) -> usize {
        self.id
    }

    /// the TypeId of the Actor
    pub fn type_id(&self) -> TypeId {
        self.type_id
    }

    /// the TypeId of the [Actor::Message](crate::actor::Actor::Message)
    pub fn message_id(&self) -> TypeId {
        self.message_id
    }

    /// the name of the Actor
    /// you can set it with `set_name`
    pub fn name(&self) -> &str {
        &self.name
    }

    /// set the name of the Actor
    pub fn set_name<T: Into<String>>(&mut self, name: T) {
        self.name = name.into();
    }

    /// the state of the Actor
    /// you can set it with `set_closed`
    pub fn is_closed(&self) -> bool {
        self.closed.load(Ordering::Relaxed)
    }

    /// set the actor is closed
    pub fn set_closed(&self, state: bool) {
        self.closed.store(state, Ordering::Relaxed);
    }

    /// indicator that whether the Actor is
    /// being downcasted to Actor and mutating
    pub fn is_sealed(&self) -> bool {
        self.sealed.load(Ordering::Relaxed)
    }

    /// downcast the type Actor type `&A`
    pub fn downcast_ref<A: Actor>(&self) -> Option<&A> {
        // make sure that the inner is being mutating and sealed
        // if ture, wait in a spin loop for completion
        while self.sealed.load(Ordering::Relaxed) {
            hint::spin_loop();
        }
        let ptr = self.inner.as_ref().get();
        let dyn_ptr = unsafe { transmute::<*mut dyn Any, &dyn Any>(ptr) };
        dyn_ptr.downcast_ref::<A>()
    }

    /// downcast the type Actor guard `ActorGuard`
    pub(crate) fn downcast_ref_cell<A: Actor>(&self) -> ActorGuard<A> {
        // make sure that the inner is being mutating and sealed
        // if ture, wait in a spin loop for completion
        while self.sealed.load(Ordering::Relaxed) {
            hint::spin_loop();
        }
        let ptr = Arc::as_ptr(&self.inner);
        let actor_cell: *mut A = UnsafeCell::raw_get(ptr as *const _);
        // **Safety**: as the inner data is guarded
        // with Arc, it is safe to downcast from
        // `Arc<UnsafeCell<A>>` to `Arc<A>`
        // as UnsafeCell<A> and A has the same size
        // and both are not mutable with Arc
        let actor_inner: *const UnsafeCell<_> =
            unsafe { transmute::<*mut A, *const UnsafeCell<A>>(actor_cell) };
        unsafe { Arc::increment_strong_count(actor_inner) };
        ActorGuard {
            //inner: Arc::new(UnsafeCell::new(actor_inner)),
            inner: unsafe { Arc::from_raw(actor_inner) },
            sealed: self.sealed.clone(),
        }
    }

    /// downcast the type Actor type `&mut A`
    /// then mutate it with the function `f`
    ///
    /// and return
    /// - `None`: downcast failed
    /// - `Some(false)`: downcasted and `f` return `Err(_)`
    /// - `Some(true)`: downcasted and `f` return `Ok(_)`
    ///
    /// the underlying actor will be
    /// guarded when downcasted
    /// no more mutable access is allowed during downcasted
    pub fn downcast_mut<A: Actor, F>(&self, mut f: F) -> Option<bool>
    where
        F: FnMut(&mut A) -> Result<(), ()>,
    {
        while self.sealed.load(Ordering::Acquire) {
            hint::spin_loop();
        }
        self.sealed.store(true, Ordering::Release);
        let ptr = self.inner.as_ref().get();
        let dyn_ptr = unsafe { transmute::<*mut dyn Any, &mut dyn Any>(ptr) };
        let inner = dyn_ptr.downcast_mut::<A>();
        match inner {
            None => None,
            Some(data) => match f(data) {
                Ok(_) => Some(true),
                Err(_) => Some(false),
            },
        }
    }
}

#[test]
fn test_downcast_cell() {
    extern crate alloc;
    use alloc::sync::Arc;
    use core::{cell::UnsafeCell, mem::transmute};

    struct Se {}

    let inner = Arc::new(UnsafeCell::new(Se {}));
    let _a = inner.clone();

    let ptr = Arc::as_ptr(&inner);
    let actor_cell: *mut Se = UnsafeCell::raw_get(ptr as *const _);
    let actor_inner: *const UnsafeCell<_> =
        unsafe { transmute::<*mut Se, *const UnsafeCell<Se>>(actor_cell) };

    let inn = unsafe { Arc::from_raw(actor_inner) };
    unsafe { Arc::increment_strong_count(actor_inner) };
    assert_eq!(Arc::strong_count(&inn), Arc::strong_count(&inner));
    assert_eq!(Arc::weak_count(&inn), Arc::weak_count(&inner));
    drop(_a);
    drop(inner);
    assert_eq!(Arc::strong_count(&inn), 1);
    assert_eq!(Arc::weak_count(&inn), 0);
}