| 1 | #pragma once |
| 2 | |
| 3 | #include <mbgl/actor/mailbox.hpp> |
| 4 | #include <mbgl/actor/message.hpp> |
| 5 | #include <mbgl/actor/actor_ref.hpp> |
| 6 | |
| 7 | #include <memory> |
| 8 | #include <future> |
| 9 | #include <type_traits> |
| 10 | #include <cassert> |
| 11 | |
| 12 | namespace mbgl { |
| 13 | |
| 14 | template <class Object> |
| 15 | class EstablishedActor; |
| 16 | |
| 17 | template <class Object> |
| 18 | class Actor; |
| 19 | |
| 20 | /* |
| 21 | An `AspiringActor<O>` is one half of the pair of types that comprise an actor (see `Actor<O>`), |
| 22 | the other half being `EstablishedActor<O>`. It is responsible for: |
| 23 | - ownership of the actor's `Mailbox` |
| 24 | - allocating the memory for (but *not* constructing) the target object `O` |
| 25 | |
| 26 | Using these two pieces--the mailbox and a stable address for `O`--an `AspiringActor<O>` can |
| 27 | accept messages for the target object, or provide `ActorRef<O>`s that do so, before the object |
| 28 | has actually been constructed by the corresponding `EstablishedActor<O>`. (Such messages are |
| 29 | queued in the mailbox until after the object is constructed.) |
| 30 | |
| 31 | This allows for an `AspiringActor<O>` to be created and safely used by a thread other than the |
| 32 | one on which the target object will (eventually) live. |
| 33 | */ |
| 34 | template <class Object> |
| 35 | class AspiringActor { |
| 36 | public: |
| 37 | AspiringActor() : mailbox(std::make_shared<Mailbox>()) { |
| 38 | // mailbox starts closed because the `Object` hasn't yet been constructed |
| 39 | assert(!mailbox->isOpen()); |
| 40 | } |
| 41 | |
| 42 | AspiringActor(const AspiringActor&) = delete; |
| 43 | |
| 44 | ActorRef<std::decay_t<Object>> self() { |
| 45 | return ActorRef<std::decay_t<Object>>(object(), mailbox); |
| 46 | } |
| 47 | |
| 48 | private: |
| 49 | std::shared_ptr<Mailbox> mailbox; |
| 50 | std::aligned_storage_t<sizeof(Object)> objectStorage; |
| 51 | |
| 52 | Object& object() { |
| 53 | return *reinterpret_cast<Object *>(&objectStorage); |
| 54 | } |
| 55 | |
| 56 | friend class EstablishedActor<Object>; |
| 57 | friend class Actor<Object>; |
| 58 | }; |
| 59 | |
| 60 | } // namespace mbgl |
| 61 | |