BufferTextWriter.cs
8.58 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// Copyright (c) Andrew Arnott. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
using System;
using System.Buffers;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft;
namespace SoapCore.MessageEncoder
{
/// <summary>
/// A <see cref="TextWriter"/> that writes to a reassignable instance of <see cref="IBufferWriter{T}"/>.
/// </summary>
/// <remarks>
/// Using this is much more memory efficient than a <see cref="StreamWriter"/> when writing to many different
/// <see cref="IBufferWriter{T}"/> because the same writer, with all its buffers, can be reused.
/// </remarks>
public class BufferTextWriter : TextWriter
{
/// <summary>
/// A buffer of written characters that have not yet been encoded.
/// The <see cref="_charBufferPosition"/> field tracks how many characters are represented in this buffer.
/// </summary>
private readonly char[] _charBuffer = new char[512];
/// <summary>
/// The internal buffer writer to use for writing encoded characters.
/// </summary>
private IBufferWriter<byte> _bufferWriter;
/// <summary>
/// The last buffer received from <see cref="_bufferWriter"/>.
/// </summary>
private Memory<byte> _memory;
/// <summary>
/// The number of characters written to the <see cref="_memory"/> buffer.
/// </summary>
private int _memoryPosition;
/// <summary>
/// The number of characters written to the <see cref="_charBuffer"/>.
/// </summary>
private int _charBufferPosition;
/// <summary>
/// Whether the encoding preamble has been written since the last call to <see cref="Initialize(IBufferWriter{byte}, Encoding)"/>.
/// </summary>
private bool _preambleWritten;
/// <summary>
/// The encoding currently in use.
/// </summary>
private Encoding _encoding;
/// <summary>
/// The preamble for the current <see cref="_encoding"/>.
/// </summary>
/// <remarks>
/// We store this as a field to avoid calling <see cref="Encoding.GetPreamble"/> repeatedly,
/// since the typical implementation allocates a new array for each call.
/// </remarks>
private ReadOnlyMemory<byte> _encodingPreamble;
/// <summary>
/// An encoder obtained from the current <see cref="_encoding"/> used for incrementally encoding written characters.
/// </summary>
private Encoder _encoder;
/// <summary>
/// Initializes a new instance of the <see cref="BufferTextWriter"/> class.
/// </summary>
/// <param name="bufferWriter">The buffer writer to write to.</param>
/// <param name="encoding">The encoding to use.</param>
public BufferTextWriter(IBufferWriter<byte> bufferWriter, Encoding encoding)
{
Initialize(bufferWriter, encoding);
}
/// <inheritdoc />
public override Encoding Encoding => _encoding;
/// <summary>
/// Gets the number of uninitialized characters remaining in <see cref="_charBuffer"/>.
/// </summary>
private int CharBufferSlack => _charBuffer.Length - _charBufferPosition;
/// <summary>
/// Prepares for writing to the specified buffer.
/// </summary>
/// <param name="bufferWriter">The buffer writer to write to.</param>
/// <param name="encoding">The encoding to use.</param>
public void Initialize(IBufferWriter<byte> bufferWriter, Encoding encoding)
{
Requires.NotNull(bufferWriter, nameof(bufferWriter));
Requires.NotNull(encoding, nameof(encoding));
Verify.Operation(_memoryPosition == 0 && _charBufferPosition == 0, "This instance must be flushed before being reinitialized.");
_preambleWritten = false;
_bufferWriter = bufferWriter;
if (encoding != _encoding)
{
_encoding = encoding;
_encoder = _encoding.GetEncoder();
_encodingPreamble = _encoding.GetPreamble();
}
else
{
// encoder != null because if it were, encoding == null too, so we would have been in the first branch above.
_encoder.Reset();
}
}
/// <summary>
/// Clears references to the <see cref="IBufferWriter{T}"/> set by a prior call to <see cref="Initialize(IBufferWriter{byte}, Encoding)"/>.
/// </summary>
public void Reset()
{
_bufferWriter = null;
}
/// <inheritdoc />
public override void Flush()
{
ThrowIfNotInitialized();
EncodeCharacters(flushEncoder: true);
CommitBytes();
}
/// <inheritdoc />
public override Task FlushAsync()
{
try
{
Flush();
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
/// <inheritdoc />
public override void Write(char value)
{
ThrowIfNotInitialized();
_charBuffer[_charBufferPosition++] = value;
EncodeCharactersIfBufferFull();
}
/// <inheritdoc />
public override void Write(string value)
{
if (value == null)
{
return;
}
Write(value.AsSpan());
}
/// <inheritdoc />
public override void Write(char[] buffer, int index, int count) => Write(Requires.NotNull(buffer, nameof(buffer)).AsSpan(index, count));
#if SPAN_BUILTIN
/// <inheritdoc />
public override void Write(ReadOnlySpan<char> buffer)
#else
/// <summary>
/// Copies a given span of characters into the writer.
/// </summary>
/// <param name="buffer">The characters to write.</param>
public virtual void Write(ReadOnlySpan<char> buffer)
#endif
{
ThrowIfNotInitialized();
// Try for fast path
if (buffer.Length <= CharBufferSlack)
{
buffer.CopyTo(_charBuffer.AsSpan(_charBufferPosition));
_charBufferPosition += buffer.Length;
EncodeCharactersIfBufferFull();
}
else
{
int charsCopied = 0;
while (charsCopied < buffer.Length)
{
int charsToCopy = Math.Min(buffer.Length - charsCopied, CharBufferSlack);
buffer.Slice(charsCopied, charsToCopy).CopyTo(_charBuffer.AsSpan(_charBufferPosition));
charsCopied += charsToCopy;
_charBufferPosition += charsToCopy;
EncodeCharactersIfBufferFull();
}
}
}
#if SPAN_BUILTIN
/// <inheritdoc />
public override void WriteLine(ReadOnlySpan<char> buffer)
#else
/// <summary>
/// Writes a span of characters followed by a <see cref="TextWriter.NewLine"/>.
/// </summary>
/// <param name="buffer">The characters to write.</param>
public virtual void WriteLine(ReadOnlySpan<char> buffer)
#endif
{
Write(buffer);
WriteLine();
}
/// <summary>
/// Encodes the written characters if the character buffer is full.
/// </summary>
private void EncodeCharactersIfBufferFull()
{
if (_charBufferPosition == _charBuffer.Length)
{
EncodeCharacters(flushEncoder: false);
}
}
/// <summary>
/// Encodes characters written so far to a buffer provided by the underyling <see cref="_bufferWriter"/>.
/// </summary>
/// <param name="flushEncoder"><c>true</c> to flush the characters in the encoder; useful when finalizing the output.</param>
private void EncodeCharacters(bool flushEncoder)
{
if (_charBufferPosition > 0)
{
int maxBytesLength = Encoding.GetMaxByteCount(_charBufferPosition);
if (!_preambleWritten)
{
maxBytesLength += _encodingPreamble.Length;
}
if (_memory.Length - _memoryPosition < maxBytesLength)
{
CommitBytes();
_memory = _bufferWriter.GetMemory(maxBytesLength);
}
if (!_preambleWritten)
{
_encodingPreamble.Span.CopyTo(_memory.Span.Slice(_memoryPosition));
_memoryPosition += _encodingPreamble.Length;
_preambleWritten = true;
}
if (MemoryMarshal.TryGetArray(_memory, out ArraySegment<byte> segment))
{
_memoryPosition += _encoder.GetBytes(_charBuffer, 0, _charBufferPosition, segment.Array, segment.Offset + _memoryPosition, flush: flushEncoder);
}
else
{
byte[] rentedByteBuffer = ArrayPool<byte>.Shared.Rent(maxBytesLength);
try
{
int bytesWritten = _encoder.GetBytes(_charBuffer, 0, _charBufferPosition, rentedByteBuffer, 0, flush: flushEncoder);
rentedByteBuffer.CopyTo(_memory.Span.Slice(_memoryPosition));
_memoryPosition += bytesWritten;
}
finally
{
ArrayPool<byte>.Shared.Return(rentedByteBuffer);
}
}
_charBufferPosition = 0;
if (_memoryPosition == _memory.Length)
{
Flush();
}
}
}
/// <summary>
/// Commits any written bytes to the underlying <see cref="_bufferWriter"/>.
/// </summary>
private void CommitBytes()
{
if (_memoryPosition > 0)
{
_bufferWriter.Advance(_memoryPosition);
_memoryPosition = 0;
_memory = default;
}
}
private void ThrowIfNotInitialized()
{
if (_bufferWriter == null)
{
throw new InvalidOperationException("Call " + nameof(Initialize) + " first.");
}
}
}
}