5 #include <msp/core/systemerror.h>
6 #include "eventreader.h"
7 #include "handle_private.h"
14 struct EventReader::Private
17 OVERLAPPED *overlapped;
27 EventReader::EventReader(Handle &h, unsigned size):
35 *priv->event = CreateEvent(0, true, false, 0);
36 priv->buf_size = size;
37 priv->buffer = new char[priv->buf_size];
39 priv->buf_next = priv->buffer;
45 EventReader::~EventReader()
48 CloseHandle(*priv->event);
49 delete priv->overlapped;
50 delete[] priv->buffer;
55 const Handle &EventReader::get_event()
65 void EventReader::start()
68 if(priv->buf_avail || priv->overlapped)
71 priv->overlapped = new OVERLAPPED;
72 memset(priv->overlapped, 0, sizeof(OVERLAPPED));
73 priv->overlapped->hEvent = *priv->event;
76 priv->buf_next = priv->buffer;
77 if(!ReadFile(*handle, priv->buffer, priv->buf_size, &ret, priv->overlapped))
79 unsigned err = GetLastError();
80 if(err!=ERROR_IO_PENDING)
81 throw system_error("ReadFile");
85 priv->buf_avail = ret;
86 delete priv->overlapped;
88 SetEvent(*priv->event);
93 void EventReader::wait()
100 if(!GetOverlappedResult(*handle, priv->overlapped, &ret, true))
101 throw system_error("GetOverlappedResult");
104 priv->buf_avail = ret;
105 delete priv->overlapped;
106 priv->overlapped = 0;
111 unsigned EventReader::read(char *buf, unsigned len)
116 // No data in buffer, try to get some
121 len = min(len, priv->buf_avail);
122 memcpy(buf, priv->buf_next, len);
123 priv->buf_next += len;
124 priv->buf_avail -= len;
128 ResetEvent(*priv->event);
134 return sys_read(handle, buf, len);