3 #include <msp/core/systemerror.h>
4 #include "eventreader.h"
5 #include "handle_private.h"
12 struct EventReader::Private
14 OVERLAPPED *overlapped;
23 EventReader::EventReader(Handle &h, unsigned size):
28 *priv->event = CreateEvent(0, true, false, 0);
29 priv->buf_size = size;
30 priv->buffer = new char[priv->buf_size];
32 priv->buf_next = priv->buffer;
35 EventReader::~EventReader()
37 CloseHandle(*priv->event);
38 delete priv->overlapped;
39 delete[] priv->buffer;
43 const Handle &EventReader::get_event()
49 void EventReader::start()
51 if(priv->buf_avail || priv->overlapped)
54 priv->overlapped = new OVERLAPPED;
55 memset(priv->overlapped, 0, sizeof(OVERLAPPED));
56 priv->overlapped->hEvent = *priv->event;
59 priv->buf_next = priv->buffer;
60 if(!ReadFile(*handle, priv->buffer, priv->buf_size, &ret, priv->overlapped))
62 unsigned err = GetLastError();
63 if(err!=ERROR_IO_PENDING)
64 throw system_error("ReadFile");
68 priv->buf_avail = ret;
69 delete priv->overlapped;
71 SetEvent(*priv->event);
75 void EventReader::wait()
81 if(!GetOverlappedResult(*handle, priv->overlapped, &ret, true))
82 throw system_error("GetOverlappedResult");
85 priv->buf_avail = ret;
86 delete priv->overlapped;
91 unsigned EventReader::read(char *buf, unsigned len)
95 // No data in buffer, try to get some
100 len = min(len, priv->buf_avail);
101 memcpy(buf, priv->buf_next, len);
102 priv->buf_next += len;
103 priv->buf_avail -= len;
107 ResetEvent(*priv->event);