forked from Code-Sharp/uHttpSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIStreamReader.cs
More file actions
122 lines (95 loc) · 3.18 KB
/
Copy pathIStreamReader.cs
File metadata and controls
122 lines (95 loc) · 3.18 KB
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
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace uhttpsharp.RequestProviders
{
public interface IStreamReader
{
Task<string> ReadLine();
Task<byte[]> ReadBytes(int count);
}
class StreamReaderAdapter : IStreamReader
{
private readonly StreamReader _reader;
public StreamReaderAdapter(StreamReader reader)
{
_reader = reader;
}
public async Task<string> ReadLine()
{
return await _reader.ReadLineAsync().ConfigureAwait(false);
}
public async Task<byte[]> ReadBytes(int count)
{
var tempBuffer = new char[count];
await _reader.ReadBlockAsync(tempBuffer, 0, count).ConfigureAwait(false);
var retVal = new byte[count];
for (int i = 0; i < tempBuffer.Length; i++)
{
retVal[i] = (byte)tempBuffer[i];
}
return retVal;
}
}
class MyStreamReader : IStreamReader
{
private const int BufferSize = 8096 / 4;
private readonly Stream _underlyingStream;
private readonly byte[] _middleBuffer = new byte[BufferSize];
private int _index;
private int _count;
public MyStreamReader(Stream underlyingStream)
{
_underlyingStream = underlyingStream;
}
private async Task ReadBuffer()
{
do
{
_count = await _underlyingStream.ReadAsync(_middleBuffer, 0, BufferSize).ConfigureAwait(false);
}
while (_count == 0);
_index = 0;
}
public async Task<string> ReadLine()
{
var builder = new StringBuilder(64);
if (_index == _count)
{
await ReadBuffer().ConfigureAwait(false);
}
var readByte = _middleBuffer[_index++];
while (readByte != '\n' && (builder.Length == 0 || builder[builder.Length - 1] != '\r'))
{
builder.Append((char)readByte);
if (_index == _count)
{
await ReadBuffer().ConfigureAwait(false);
}
readByte = _middleBuffer[_index++];
}
//Debug.WriteLine("Readline : " + sw.ElapsedMilliseconds);
return builder.ToString(0, builder.Length - 1);
}
public async Task<byte[]> ReadBytes(int count)
{
var buffer = new byte[count];
int currentByte = 0;
// Empty the buffer
int bytesToRead = Math.Min(_count - _index, count) + _index;
for (int i = _index; i < bytesToRead; i++)
{
buffer[currentByte++] = _middleBuffer[i];
}
_index = _count;
// Read from stream
while (currentByte < count)
{
currentByte += await _underlyingStream.ReadAsync(buffer, currentByte, count - currentByte).ConfigureAwait(false);
}
//Debug.WriteLine("ReadBytes(" + count + ") : " + sw.ElapsedMilliseconds);
return buffer;
}
}
}