]> git.tdb.fi Git - libs/core.git/blob - source/io/poll.cpp
Use C++11 features with containers
[libs/core.git] / source / io / poll.cpp
1 #include <stdexcept>
2 #include <msp/core/algorithm.h>
3 #include "eventobject.h"
4 #include "poll.h"
5 #include "poll_platform.h"
6
7 using namespace std;
8
9 namespace Msp {
10 namespace IO {
11
12 Poller::Poller():
13         priv(new Private),
14         events_changed(false),
15         objs_changed(false)
16 { }
17
18 Poller::~Poller()
19 {
20         delete priv;
21 }
22
23 void Poller::set_object(EventObject &obj, PollEvent ev)
24 {
25         // Verify that the object has an event handle
26         if(ev)
27                 obj.get_event_handle();
28
29         auto i = find_member(objects, &obj, &PolledObject::object);
30         if(i!=objects.end())
31         {
32                 if(ev)
33                         i->events = ev;
34                 else
35                 {
36                         *i = objects.back();
37                         objects.pop_back();
38                         objs_changed = true;
39                 }
40                 events_changed = true;
41                 return;
42         }
43
44         if(!ev)
45                 return;
46
47 #ifdef _WIN32
48         if(objects.size()>=MAXIMUM_WAIT_OBJECTS)
49                 throw logic_error("Maximum number of wait objects reached");
50 #endif
51
52         objects.push_back(PolledObject(&obj, ev));
53         objs_changed = true;
54 }
55
56 unsigned Poller::poll()
57 {
58         return do_poll(-1);
59 }
60
61 unsigned Poller::poll(const Time::TimeDelta &timeout)
62 {
63         if(timeout<Time::zero)
64                 throw invalid_argument("Poller::poll");
65
66         return do_poll(static_cast<int>(timeout/Time::msec));
67 }
68
69 unsigned Poller::do_poll(int timeout)
70 {
71         if(objs_changed || events_changed)
72         {
73                 rebuild_array();
74                 events_changed = false;
75                 objs_changed = false;
76         }
77
78         poll_result.clear();
79
80         platform_poll(timeout);
81
82         return poll_result.size();
83 }
84
85
86 PollEvent platform_poll(EventObject &, PollEvent, int);
87
88 PollEvent poll(EventObject &obj, PollEvent pe)
89 {
90         return platform_poll(obj, pe, -1);
91 }
92
93 PollEvent poll(EventObject &obj, PollEvent pe, const Time::TimeDelta &timeout)
94 {
95         if(timeout<Time::zero)
96                 throw invalid_argument("poll");
97
98         return platform_poll(obj, pe, static_cast<int>(timeout/Time::msec));
99 }
100
101 } // namespace IO
102 } // namespace Msp