forked from WWU-cptr143-sprouts/sprouts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.cpp
122 lines (112 loc) · 2.47 KB
/
stream.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include "stream.h"
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <queue>
using namespace std;
namespace
{
const size_t bufferSize = 8192;
struct Pipe
{
mutex lock;
condition_variable_any cond;
bool closed = false;
queue<uint8_t> buffer;
};
class PipeReader final : public Reader
{
private:
shared_ptr<Pipe> pipe;
public:
PipeReader(shared_ptr<Pipe> pipe)
: pipe(pipe)
{
}
virtual ~PipeReader()
{
pipe->lock.lock();
pipe->closed = true;
pipe->cond.notify_all();
pipe->lock.unlock();
}
virtual uint8_t readByte() override
{
pipe->lock.lock();
if(pipe->buffer.empty())
{
pipe->cond.notify_all();
}
while(true)
{
if(!pipe->buffer.empty())
break;
if(pipe->closed)
{
pipe->lock.unlock();
throw EOFException();
}
pipe->cond.wait(pipe->lock);
}
uint8_t retval = pipe->buffer.front();
pipe->buffer.pop();
pipe->lock.unlock();
return retval;
}
};
class PipeWriter final : public Writer
{
private:
shared_ptr<Pipe> pipe;
public:
PipeWriter(shared_ptr<Pipe> pipe)
: pipe(pipe)
{
}
virtual ~PipeWriter()
{
pipe->lock.lock();
pipe->closed = true;
pipe->cond.notify_all();
pipe->lock.unlock();
}
virtual void writeByte(uint8_t v) override
{
pipe->lock.lock();
while(true)
{
if(pipe->closed)
{
pipe->lock.unlock();
throw IOException("IO Error : can't write to pipe");
}
if(pipe->buffer.size() < bufferSize)
break;
pipe->cond.notify_all();
pipe->cond.wait(pipe->lock);
}
pipe->buffer.push(v);
pipe->lock.unlock();
}
virtual void flush() override
{
pipe->lock.lock();
pipe->cond.notify_all();
pipe->lock.unlock();
}
};
}
StreamPipe::StreamPipe()
{
shared_ptr<Pipe> pipe = make_shared<Pipe>();
readerInternal = shared_ptr<Reader>(new PipeReader(pipe));
writerInternal = shared_ptr<Writer>(new PipeWriter(pipe));
}
uint8_t DumpingReader::readByte()
{
uint8_t retval = reader.readByte();
cerr << "Read Byte : " << (unsigned)retval << "\n";
return retval;
}