forked from ServiceStack/ServiceStack.Text
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectStreamWriter.cs
More file actions
85 lines (73 loc) · 2.17 KB
/
DirectStreamWriter.cs
File metadata and controls
85 lines (73 loc) · 2.17 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
using System;
using System.IO;
using System.Text;
namespace ServiceStack.Text
{
public class DirectStreamWriter : TextWriter
{
private const int optimizedBufferLength = 256;
private const int maxBufferLength = 1024;
private Stream stream;
private StreamWriter writer = null;
private byte[] curChar = new byte[1];
private bool needFlush = false;
private Encoding encoding;
public override Encoding Encoding => encoding;
public DirectStreamWriter(Stream stream, Encoding encoding)
{
this.stream = stream;
this.encoding = encoding;
}
public override void Write(string s)
{
if (s.IsNullOrEmpty())
return;
if (s.Length <= optimizedBufferLength)
{
if (needFlush)
{
writer.Flush();
needFlush = false;
}
byte[] buffer = Encoding.GetBytes(s);
stream.Write(buffer, 0, buffer.Length);
} else
{
if (writer == null)
writer = new StreamWriter(stream, Encoding, s.Length < maxBufferLength ? s.Length : maxBufferLength);
writer.Write(s);
needFlush = true;
}
}
public override void Write(char c)
{
if ((int)c < 128)
{
if (needFlush)
{
writer.Flush();
needFlush = false;
}
curChar[0] = (byte)c;
stream.Write(curChar, 0, 1);
} else
{
if (writer == null)
writer = new StreamWriter(stream, Encoding, optimizedBufferLength);
writer.Write(c);
needFlush = true;
}
}
public override void Flush()
{
if (writer != null)
{
writer.Flush();
}
else
{
stream.Flush();
}
}
}
}