/
BinaryToTextInputStream.h
91 lines (75 loc) · 1.62 KB
/
BinaryToTextInputStream.h
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
#pragma once
#include "itextstream.h"
namespace stream
{
/// \brief A single-byte-reader wrapper around an InputStream.
/// Optimised for reading one byte at a time.
/// Uses a buffer to reduce the number of times the wrapped stream must be read.
template<typename InputStreamType>
class SingleByteInputStream
{
private:
typedef typename InputStreamType::byte_type byte_type;
static const std::size_t SIZE = 1024;
InputStreamType& _inputStream;
byte_type _buffer[SIZE];
byte_type* _cur;
byte_type* _end;
public:
SingleByteInputStream(InputStreamType& inputStream) :
_inputStream(inputStream),
_cur(_buffer + SIZE),
_end(_cur)
{}
bool readByte(byte_type& b)
{
if (_cur == _end)
{
if (_end != _buffer + SIZE)
{
return false;
}
_end = _buffer + _inputStream.read(_buffer, SIZE);
_cur = _buffer;
if (_end == _buffer)
{
return false;
}
}
b = *_cur++;
return true;
}
};
/// \brief A binary-to-text wrapper around an InputStream.
/// Converts CRLF or LFCR line-endings to LF line-endings.
template<typename BinaryInputStreamType>
class BinaryToTextInputStream :
public TextInputStream
{
private:
SingleByteInputStream<BinaryInputStreamType> _inputStream;
public:
BinaryToTextInputStream(BinaryInputStreamType& inputStream) :
_inputStream(inputStream)
{}
std::size_t read(char* buffer, std::size_t length) override
{
char* p = buffer;
for (;;)
{
if (length != 0 && _inputStream.readByte(*reinterpret_cast<typename BinaryInputStreamType::byte_type*>(p)))
{
if (*p != '\r')
{
++p;
--length;
}
}
else
{
return p - buffer;
}
}
}
};
}