OSDN Git Service

communicationの具体的な実装を追加
[gikomona/libcore.git] / src / communication.cpp
1 #include <sstream>
2
3 #include <boost/range/algorithm.hpp>
4
5 #include "communication.hpp"
6 #include "reference-counter.hpp"
7 #include "message/request.hpp"
8 #include "message/failure.hpp"
9 #include "message/succeed.hpp"
10
11 namespace ipc = boost::interprocess;
12
13 namespace monazilla { namespace GikoMona { namespace core {
14
15 communication::communication(const communicate_id self_id) : self(self_id) {
16     gm_shmem = shared_memory(ipc::open_or_create, shared_memory_name, 1024 * 4);
17
18     my_mailbox = construct_object<mailbox>(create_mailbox_name(self));
19     
20     if(auto obj = find_object<reference_counter>(ref_counter_name)) {
21         auto locker = obj->scoped_lock();
22         ++(*obj);
23     } else {
24         construct_object<reference_counter>(ref_counter_name);
25     }
26 }
27
28 communication::~communication() {
29     disconnect_all();
30     
31     if(auto obj = find_object<reference_counter>(ref_counter_name)) {
32         if(obj->count() == 1) {
33             ipc::shared_memory_object::remove(shared_memory_name);
34         } else {
35             auto locker = obj->scoped_lock();
36             --(*obj);
37         }
38     } else {
39         /* error!!!!! */
40     }
41 }
42
43 bool communication::connect(const communicate_id connect_to) {
44     auto obj = find_object<mailbox>(gm_shmem, create_mailbox_name(connect_to));
45     
46     if(obj) {
47         mailbox_map[connect_to] = *obj;
48         send(connect_to, succeed::find_your_mailbox("").to_string());
49     
50         do {
51             mona_string mail = receive(connect_to);
52         } while(is_same_mail(mail, succeed::allow_you_to_send_mail("")));
53     }
54     
55     return obj;
56 }
57
58 bool communication::disconnect(const communicate_id disconnect_from) {
59     return mailbox_map.erase(disconnect_from);
60 }
61
62 mona_string communication::receive(const communicate_id originator_id) {
63     boost::find_if
64 }
65     
66 bool communication::send_string(const communicate_id to, mona_string&& src) {
67     auto obj = find_object<mailbox>(gm_shmem, create_mailbox_name(to));
68     
69     if(obj) {
70         std::ostringstream str_builder;
71         str_builder << to_string(self) << "-" << src;
72         
73         obj->push_back(str_builder.str());
74     }
75     
76     return obj;
77 }
78
79 std::string communication::create_mailbox_name(const communicate_id mb_user_id) {
80     std::ostringstream str_builder;
81     str_builder << "mailbox:" << to_string(mb_user_id);
82     
83     return str_builder.str();
84 }
85
86 } } }