-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAsyncHtmlEncodingTextWriter.cs
More file actions
223 lines (200 loc) · 7.74 KB
/
AsyncHtmlEncodingTextWriter.cs
File metadata and controls
223 lines (200 loc) · 7.74 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
using System;
using System.Buffers;
using System.Globalization;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading;
using System.Threading.Tasks;
namespace Eighty
{
/// <summary>
/// This has to be a class because its mutating methods are async and would operate on a copy of the struct if this were a struct
///
/// NB. Any changes to this file need to be paralleled in HtmlEncodingTextWriter
///
/// See also https://github.com/dotnet/corefx/blob/3de3cd74ce3d81d13f75928eae728fb7945b6048/src/System.Runtime.Extensions/src/System/Net/WebUtility.cs
/// </summary>
internal class AsyncHtmlEncodingTextWriter
{
private readonly TextWriter _underlyingWriter;
private readonly HtmlEncoder _htmlEncoder;
private char[] _buffer;
private char[] _scratchpad;
private int _bufPos;
public AsyncHtmlEncodingTextWriter(TextWriter underlyingWriter, HtmlEncoder htmlEncoder)
{
_underlyingWriter = underlyingWriter;
_htmlEncoder = htmlEncoder;
_buffer = ArrayPool<char>.Shared.Rent(2048);
_scratchpad = ArrayPool<char>.Shared.Rent(_htmlEncoder.MaxOutputCharactersPerInputCharacter);
_bufPos = 0;
}
public async Task FlushAndClear()
{
await Flush().ConfigureAwait(false);
ArrayPool<char>.Shared.Return(_buffer);
_buffer = null;
ArrayPool<char>.Shared.Return(_scratchpad);
_scratchpad = null;
_bufPos = 0;
}
public async Task Write(string s)
{
var position = 0;
while (position < s.Length)
{
var safeChunkLength = _htmlEncoder.FindFirstCharacterToEncode(s, position);
if (safeChunkLength == -1) // no encoding chars in the input, write the whole string without encoding
{
safeChunkLength = s.Length - position;
}
await WriteRawImpl(s, position, safeChunkLength).ConfigureAwait(false);
position += safeChunkLength;
if (position < s.Length)
{
// we're now looking at an HTML-encoding character
position = await WriteEncodingChars(s, position).ConfigureAwait(false);
}
}
}
/// <summary>
/// Consume a run of HTML-encoding characters from the string
/// </summary>
/// <returns>The new position</returns>
private async ValueTask<int> WriteEncodingChars(string s, int position)
{
while (position < s.Length)
{
var isSurrogatePair = char.IsSurrogatePair(s, position);
if (char.IsSurrogate(s, position) && !isSurrogatePair)
{
await WriteUnicodeReplacementChar().ConfigureAwait(false);
position++;
continue;
}
var codePoint = char.ConvertToUtf32(s, position); // won't fail because we checked the precondition
if (!_htmlEncoder.WillEncode(codePoint))
{
break;
}
position += isSurrogatePair ? 2 : 1;
if (_bufPos + _htmlEncoder.MaxOutputCharactersPerInputCharacter < _buffer.Length)
{
// there's definitely enough space in the buffer, write the encoded html directly
EncodeIntoBuffer(codePoint);
}
else
{
// write it to the scratchpad first, because it definitely has enough space, then copy over in chunks
var numberOfCharactersWritten = EncodeIntoScratchpad(codePoint);
await WriteRawImpl(_scratchpad, 0, numberOfCharactersWritten).ConfigureAwait(false);
}
}
return position;
}
private unsafe void EncodeIntoBuffer(int codePoint)
{
bool success;
int numberOfCharactersWritten;
fixed (char* b = _buffer)
{
success = _htmlEncoder.TryEncodeUnicodeScalar(codePoint, b + _bufPos, _buffer.Length - _bufPos, out numberOfCharactersWritten);
}
if (!success)
{
// should be unreachable
throw new InvalidOperationException("Buffer overflow when encoding HTML. Please report this as a bug in Eighty!");
}
_bufPos += numberOfCharactersWritten;
}
private unsafe int EncodeIntoScratchpad(int codePoint)
{
bool success;
int numberOfCharactersWritten;
fixed (char* b = _scratchpad)
{
success = _htmlEncoder.TryEncodeUnicodeScalar(codePoint, b, _scratchpad.Length, out numberOfCharactersWritten);
}
if (!success)
{
// should be unreachable
throw new InvalidOperationException("Buffer overflow when encoding HTML. Please report this as a bug in Eighty!");
}
return numberOfCharactersWritten;
}
public async Task WriteRaw(char c)
{
await FlushIfNecessary().ConfigureAwait(false);
_buffer[_bufPos] = c;
_bufPos++;
}
public Task WriteRaw(string s)
{
return WriteRawImpl(s, 0, s.Length);
}
private Task WriteRawImpl(string s, int start, int count)
{
if (count <= _buffer.Length - _bufPos)
{
// the whole string fits in the buffer, no need to flush
s.CopyTo(start, _buffer, _bufPos, count);
_bufPos += count;
return Task.CompletedTask;
}
return WriteInChunks(s, start, count);
}
private async Task WriteInChunks(string s, int start, int count)
{
while (count > 0)
{
var chunkSize = Math.Min(count, _buffer.Length - _bufPos);
s.CopyTo(start, _buffer, _bufPos, chunkSize);
count -= chunkSize;
start += chunkSize;
_bufPos += chunkSize;
await FlushIfNecessary().ConfigureAwait(false);
}
}
private Task WriteRawImpl(char[] arr, int start, int count)
{
if (count <= _buffer.Length - _bufPos)
{
// the whole string fits in the buffer, no need to flush
Array.Copy(arr, start, _buffer, _bufPos, count);
_bufPos += count;
return Task.CompletedTask;
}
return WriteInChunks(arr, start, count);
}
private async Task WriteInChunks(char[] arr, int start, int count)
{
while (count > 0)
{
var chunkSize = Math.Min(count, _buffer.Length - _bufPos);
Array.Copy(arr, start, _buffer, _bufPos, chunkSize);
count -= chunkSize;
start += chunkSize;
_bufPos += chunkSize;
await FlushIfNecessary().ConfigureAwait(false);
}
}
private Task WriteUnicodeReplacementChar()
{
return WriteRaw(HtmlEncodingHelpers.UNICODE_REPLACEMENT_CHAR);
}
private Task FlushIfNecessary()
{
if (_bufPos == _buffer.Length)
{
return Flush();
}
return Task.CompletedTask;
}
private Task Flush()
{
var len = _bufPos;
_bufPos = 0;
return _underlyingWriter.WriteAsync(_buffer, 0, len);
}
}
}