forked from FireflyServer/firefly
/
MemoryPoolTextWriter.cs
136 lines (116 loc) · 3.85 KB
/
MemoryPoolTextWriter.cs
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
using System;
using System.IO;
using System.Text;
namespace Firefly.Utils
{
public class MemoryPoolTextWriter : TextWriter
{
private readonly IMemoryPool _memory;
private char[] _textArray;
private int _textBegin;
private int _textEnd;
// ReSharper disable InconsistentNaming
private const int _textLength = 128;
// ReSharper restore InconsistentNaming
private byte[] _dataArray;
private int _dataEnd;
private readonly Encoder _encoder;
public ArraySegment<byte> Buffer
{
get { return new ArraySegment<byte>(_dataArray, 0, _dataEnd); }
}
public MemoryPoolTextWriter(IMemoryPool memory)
{
_memory = memory;
_textArray = _memory.AllocChar(_textLength);
_dataArray = _memory.Empty;
_encoder = Encoding.Default.GetEncoder();
}
public override Encoding Encoding
{
get { return Encoding.Default; }
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_textArray != null)
{
_memory.FreeChar(_textArray);
_textArray = null;
}
if (_dataArray != null)
{
_memory.FreeByte(_dataArray);
_dataArray = null;
}
}
}
finally
{
base.Dispose(disposing);
}
}
private void Encode(bool flush)
{
var bytesNeeded = _encoder.GetByteCount(
_textArray, _textBegin, _textEnd - _textBegin,
flush);
Grow(bytesNeeded);
var bytesUsed = _encoder.GetBytes(
_textArray, _textBegin, _textEnd - _textBegin,
_dataArray, _dataEnd, flush);
_textBegin = _textEnd = 0;
_dataEnd += bytesUsed;
}
private void Grow(int minimumAvailable)
{
if (_dataArray.Length - _dataEnd >= minimumAvailable)
return;
var newLength = _dataArray.Length + Math.Max(_dataArray.Length, minimumAvailable);
var newArray = _memory.AllocByte(newLength);
Array.Copy(_dataArray, 0, newArray, 0, _dataEnd);
_memory.FreeByte(_dataArray);
_dataArray = newArray;
}
public override void Write(char value)
{
if (_textLength == _textEnd)
{
Encode(false);
if (_textLength == _textEnd)
{
throw new InvalidOperationException("Unexplainable failure to encode text");
}
}
_textArray[_textEnd++] = value;
}
public override void Write(string value)
{
var sourceIndex = 0;
var sourceLength = value.Length;
while (sourceIndex < sourceLength)
{
if (_textLength == _textEnd)
{
Encode(false);
}
var count = sourceLength - sourceIndex;
if (count > _textLength - _textEnd)
count = _textLength - _textEnd;
value.CopyTo(sourceIndex, _textArray, _textEnd, count);
sourceIndex += count;
_textEnd += count;
}
}
public override void Flush()
{
while (_textBegin != _textEnd)
{
Encode(true);
}
}
}
}