-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoundedTextWriter.cs
More file actions
53 lines (42 loc) · 1.32 KB
/
Copy pathBoundedTextWriter.cs
File metadata and controls
53 lines (42 loc) · 1.32 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
using System.Text;
namespace DotPython.Worker.Host;
internal sealed class BoundedTextWriter(int maxBytes) : TextWriter
{
private static readonly Encoding Utf8 = new UTF8Encoding(false, true);
private readonly StringBuilder _builder = new();
private int _byteCount;
public override Encoding Encoding => Utf8;
public override void Write(char value)
{
Span<char> text = stackalloc char[1];
text[0] = value;
Append(text);
}
public override void Write(string? value)
{
if (value is not null)
{
Append(value.AsSpan());
}
}
public override string ToString() => _builder.ToString();
private void Append(ReadOnlySpan<char> value)
{
var bytes = Utf8.GetByteCount(value);
if (bytes > maxBytes - _byteCount)
{
throw new WorkerOutputLimitException();
}
_builder.Append(value);
_byteCount += bytes;
}
}
internal sealed class WorkerOutputLimitException : Exception
{
public WorkerOutputLimitException()
: base("Worker output exceeded the configured limit.") { }
public WorkerOutputLimitException(string message)
: base(message) { }
public WorkerOutputLimitException(string message, Exception innerException)
: base(message, innerException) { }
}